4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
34 #include <sys/types.h>
36 #include "wine/winbase16.h"
37 #include "wine/winuser16.h"
42 #include "kernel_private.h"
43 #include "wine/exception.h"
44 #include "wine/server.h"
45 #include "wine/unicode.h"
46 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(process);
49 WINE_DECLARE_DEBUG_CHANNEL(file);
50 WINE_DECLARE_DEBUG_CHANNEL(server);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
61 static UINT process_error_mode;
63 static HANDLE main_exe_file;
64 static DWORD shutdown_flags = 0;
65 static DWORD shutdown_priority = 0x280;
66 static DWORD process_dword;
68 static unsigned int server_startticks;
69 int main_create_flags = 0;
70 HMODULE kernel32_handle = 0;
72 const WCHAR *DIR_Windows = NULL;
73 const WCHAR *DIR_System = NULL;
76 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
77 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
78 #define PDB32_DOS_PROC 0x0010 /* Dos process */
79 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
80 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
81 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
83 static const WCHAR comW[] = {'.','c','o','m',0};
84 static const WCHAR batW[] = {'.','b','a','t',0};
85 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
87 extern void SHELL_LoadRegistry(void);
88 extern void VOLUME_CreateDevices(void);
89 extern void VERSION_Init( const WCHAR *appname );
90 extern void LOCALE_Init(void);
92 /***********************************************************************
95 inline static int contains_path( LPCWSTR name )
97 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
101 /***********************************************************************
104 * Check if an environment variable needs to be handled specially when
105 * passed through the Unix environment (i.e. prefixed with "WINE").
107 inline static int is_special_env_var( const char *var )
109 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
110 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
111 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
112 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
116 /***************************************************************************
119 * Get the path of a builtin module when the native file does not exist.
121 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
124 UINT len = strlenW( DIR_System );
126 if (contains_path( libname ))
128 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
129 filename, &file_part ) > size * sizeof(WCHAR))
130 return FALSE; /* too long */
132 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
134 while (filename[len] == '\\') len++;
135 if (filename + len != file_part) return FALSE;
139 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
140 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
141 file_part = filename + len;
142 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
143 strcpyW( file_part, libname );
145 if (ext && !strchrW( file_part, '.' ))
147 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
148 return FALSE; /* too long */
149 strcatW( file_part, ext );
155 /***********************************************************************
156 * open_builtin_exe_file
158 * Open an exe file for a builtin exe.
160 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
161 int test_only, int *file_exists )
163 char exename[MAX_PATH];
167 if ((p = strrchrW( name, '/' ))) name = p + 1;
168 if ((p = strrchrW( name, '\\' ))) name = p + 1;
170 /* we don't want to depend on the current codepage here */
171 len = strlenW( name ) + 1;
172 if (len >= sizeof(exename)) return NULL;
173 for (i = 0; i < len; i++)
175 if (name[i] > 127) return NULL;
176 exename[i] = (char)name[i];
177 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
179 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
183 /***********************************************************************
186 * Open a specific exe file, taking load order into account.
187 * Returns the file handle or 0 for a builtin exe.
189 static HANDLE open_exe_file( const WCHAR *name )
191 enum loadorder_type loadorder[LOADORDER_NTYPES];
192 WCHAR buffer[MAX_PATH];
196 TRACE("looking for %s\n", debugstr_w(name) );
198 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
199 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
201 /* file doesn't exist, check for builtin */
202 if (!contains_path( name )) goto error;
203 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
207 MODULE_GetLoadOrderW( loadorder, NULL, name );
209 for(i = 0; i < LOADORDER_NTYPES; i++)
211 if (loadorder[i] == LOADORDER_INVALID) break;
215 TRACE( "Trying native exe %s\n", debugstr_w(name) );
216 if (handle != INVALID_HANDLE_VALUE) return handle;
219 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
220 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
223 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
230 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
233 SetLastError( ERROR_FILE_NOT_FOUND );
234 return INVALID_HANDLE_VALUE;
238 /***********************************************************************
241 * Open an exe file, and return the full name and file handle.
242 * Returns FALSE if file could not be found.
243 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
244 * If file is a builtin exe, returns TRUE and sets handle to 0.
246 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
248 static const WCHAR exeW[] = {'.','e','x','e',0};
250 enum loadorder_type loadorder[LOADORDER_NTYPES];
253 TRACE("looking for %s\n", debugstr_w(name) );
255 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
256 !get_builtin_path( name, exeW, buffer, buflen ))
258 /* no builtin found, try native without extension in case it is a Unix app */
260 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
262 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
263 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
264 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
270 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
272 for(i = 0; i < LOADORDER_NTYPES; i++)
274 if (loadorder[i] == LOADORDER_INVALID) break;
278 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
279 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
280 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
282 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
285 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
286 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
297 SetLastError( ERROR_FILE_NOT_FOUND );
302 /**********************************************************************
305 * Load a PE format EXE file.
307 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
310 FILE_FS_DEVICE_INFORMATION device_info;
311 IMAGE_NT_HEADERS *nt;
314 OBJECT_ATTRIBUTES attr;
318 attr.Length = sizeof(attr);
319 attr.RootDirectory = 0;
320 attr.ObjectName = NULL;
322 attr.SecurityDescriptor = NULL;
323 attr.SecurityQualityOfService = NULL;
326 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
327 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
331 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
332 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
338 nt = RtlImageNtHeader( module );
339 if (nt->OptionalHeader.AddressOfEntryPoint)
341 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
342 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
343 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
344 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
347 if (NtQueryVolumeInformationFile( file, &io, &device_info, sizeof(device_info),
348 FileFsDeviceInformation ) == STATUS_SUCCESS)
350 /* don't keep the file handle open on removable media */
351 if (device_info.Characteristics & FILE_REMOVABLE_MEDIA)
353 CloseHandle( main_exe_file );
361 /***********************************************************************
362 * build_initial_environment
364 * Build the Win32 environment from the Unix environment
366 static BOOL build_initial_environment( char **environ )
373 /* Compute the total size of the Unix environment */
374 for (e = environ; *e; e++)
376 if (is_special_env_var( *e )) continue;
377 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
379 size *= sizeof(WCHAR);
381 /* Now allocate the environment */
383 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
384 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
387 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
388 endptr = p + size / sizeof(WCHAR);
390 /* And fill it with the Unix environment */
391 for (e = environ; *e; e++)
395 /* skip Unix special variables and use the Wine variants instead */
396 if (!strncmp( str, "WINE", 4 ))
398 if (is_special_env_var( str + 4 )) str += 4;
399 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
401 else if (is_special_env_var( str )) continue; /* skip it */
403 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
411 /***********************************************************************
412 * set_registry_variables
414 * Set environment variables by enumerating the values of a key;
415 * helper for set_registry_environment().
417 static void set_registry_variables( HKEY hkey )
419 UNICODE_STRING env_name, env_value;
423 char buffer[1024 + sizeof(KEY_VALUE_FULL_INFORMATION)];
424 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
426 for (index = 0; ; index++)
428 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
429 buffer, sizeof(buffer), &size );
430 if (status == STATUS_BUFFER_OVERFLOW) continue;
431 if (status != STATUS_SUCCESS) break;
432 if (info->Type != REG_SZ) continue; /* FIXME: handle REG_EXPAND_SZ */
433 env_name.Buffer = info->Name;
434 env_name.Length = env_name.MaximumLength = info->NameLength;
435 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
436 env_value.Length = env_value.MaximumLength = info->DataLength;
437 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
438 env_value.Length--; /* don't count terminating null if any */
439 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
444 /***********************************************************************
445 * set_registry_environment
447 * Set the environment variables specified in the registry.
449 static void set_registry_environment(void)
451 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
452 'S','y','s','t','e','m','\\',
453 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
454 'C','o','n','t','r','o','l','\\',
455 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
456 'E','n','v','i','r','o','n','m','e','n','t',0};
457 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
459 OBJECT_ATTRIBUTES attr;
460 UNICODE_STRING nameW;
463 attr.Length = sizeof(attr);
464 attr.RootDirectory = 0;
465 attr.ObjectName = &nameW;
467 attr.SecurityDescriptor = NULL;
468 attr.SecurityQualityOfService = NULL;
470 /* first the system environment variables */
471 RtlInitUnicodeString( &nameW, env_keyW );
472 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
474 set_registry_variables( hkey );
478 /* then the ones for the current user */
479 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, (HKEY *)&attr.RootDirectory ) != STATUS_SUCCESS) return;
480 RtlInitUnicodeString( &nameW, envW );
481 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
483 set_registry_variables( hkey );
486 NtClose( attr.RootDirectory );
490 /***********************************************************************
493 * Set the Wine library Unicode argv global variables.
495 static void set_library_wargv( char **argv )
503 for (argc = 0; argv[argc]; argc++)
504 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
506 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
507 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
508 p = (WCHAR *)(wargv + argc + 1);
509 for (argc = 0; argv[argc]; argc++)
511 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
518 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
520 for (argc = 0; wargv[argc]; argc++)
521 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
523 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
524 q = (char *)(argv + argc + 1);
525 for (argc = 0; wargv[argc]; argc++)
527 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
534 __wine_main_argv = argv;
535 __wine_main_wargv = wargv;
539 /***********************************************************************
542 * Build the command line of a process from the argv array.
544 * Note that it does NOT necessarily include the file name.
545 * Sometimes we don't even have any command line options at all.
547 * We must quote and escape characters so that the argv array can be rebuilt
548 * from the command line:
549 * - spaces and tabs must be quoted
551 * - quotes must be escaped
553 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
554 * resulting in an odd number of '\' followed by a '"'
557 * - '\'s that are not followed by a '"' can be left as is
561 static BOOL build_command_line( WCHAR **argv )
566 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
568 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
571 for (arg = argv; *arg; arg++)
573 int has_space,bcount;
579 if( !*a ) has_space=1;
584 if (*a==' ' || *a=='\t') {
586 } else if (*a=='"') {
587 /* doubling of '\' preceeding a '"',
588 * plus escaping of said '"'
596 len+=(a-*arg)+1 /* for the separating space */;
598 len+=2; /* for the quotes */
601 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
604 p = rupp->CommandLine.Buffer;
605 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
606 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
607 for (arg = argv; *arg; arg++)
609 int has_space,has_quote;
612 /* Check for quotes and spaces in this argument */
613 has_space=has_quote=0;
615 if( !*a ) has_space=1;
617 if (*a==' ' || *a=='\t') {
621 } else if (*a=='"') {
629 /* Now transfer it to the command line */
646 /* Double all the '\\' preceeding this '"', plus one */
647 for (i=0;i<=bcount;i++)
659 while ((*p=*x++)) p++;
665 if (p > rupp->CommandLine.Buffer)
666 p--; /* remove last space */
673 /* make sure the unicode string doesn't point beyond the end pointer */
674 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
676 if ((char *)str->Buffer >= end_ptr)
678 str->Length = str->MaximumLength = 0;
682 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
684 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
686 if (str->Length >= str->MaximumLength)
688 if (str->MaximumLength >= sizeof(WCHAR))
689 str->Length = str->MaximumLength - sizeof(WCHAR);
691 str->Length = str->MaximumLength = 0;
695 static void version(void)
697 MESSAGE( "%s\n", PACKAGE_STRING );
701 static void usage(void)
703 MESSAGE( "%s\n", PACKAGE_STRING );
704 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
705 MESSAGE( " wine --help Display this help and exit\n");
706 MESSAGE( " wine --version Output version information and exit\n");
711 /***********************************************************************
712 * init_user_process_params
714 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
716 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
719 DWORD size, env_size;
720 RTL_USER_PROCESS_PARAMETERS *params;
724 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &size,
725 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
728 SERVER_START_REQ( get_startup_info )
730 wine_server_set_reply( req, ptr, info_size );
731 wine_server_call( req );
732 info_size = wine_server_reply_size( reply );
737 params->AllocationSize = size;
738 if (params->Size > info_size) params->Size = info_size;
740 /* make sure the strings are valid */
741 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
742 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
743 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
744 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
745 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
746 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
747 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
748 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
750 /* environment needs to be a separate memory block */
751 env_size = info_size - params->Size;
752 if (!env_size) env_size = 1;
754 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
755 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
757 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
758 params->Environment = ptr;
760 return RtlNormalizeProcessParams( params );
764 /***********************************************************************
765 * init_current_directory
767 * Initialize the current directory from the Unix cwd or the parent info.
769 static void init_current_directory( CURDIR *cur_dir )
771 UNICODE_STRING dir_str;
775 /* if we received a cur dir from the parent, try this first */
777 if (cur_dir->DosPath.Length)
779 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
782 /* now try to get it from the Unix cwd */
784 for (size = 256; ; size *= 2)
786 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
787 if (getcwd( cwd, size )) break;
788 HeapFree( GetProcessHeap(), 0, cwd );
789 if (errno == ERANGE) continue;
797 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
798 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
800 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
801 RtlInitUnicodeString( &dir_str, dirW );
802 RtlSetCurrentDirectory_U( &dir_str );
803 RtlFreeUnicodeString( &dir_str );
807 if (!cur_dir->DosPath.Length) /* still not initialized */
809 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
810 "starting in the Windows directory.\n", cwd ? cwd : "" );
811 RtlInitUnicodeString( &dir_str, DIR_Windows );
812 RtlSetCurrentDirectory_U( &dir_str );
814 if (cwd) HeapFree( GetProcessHeap(), 0, cwd );
817 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
818 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
822 /***********************************************************************
825 * Initialize the windows and system directories from the environment.
827 static void init_windows_dirs(void)
829 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
831 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
832 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
833 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
834 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m',0};
839 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
841 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
842 GetEnvironmentVariableW( windirW, buffer, len );
843 DIR_Windows = buffer;
845 else DIR_Windows = default_windirW;
847 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
849 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
850 GetEnvironmentVariableW( winsysdirW, buffer, len );
855 len = strlenW( DIR_Windows );
856 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
857 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
858 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
862 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
863 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
864 debugstr_w(DIR_Windows) );
865 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
866 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
867 debugstr_w(DIR_System) );
869 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
870 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
872 /* set the directories in ntdll too */
873 __wine_init_windows_dir( DIR_Windows, DIR_System );
877 /***********************************************************************
880 * Main process initialisation code
882 static BOOL process_init(void)
884 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
886 size_t info_size = 0;
887 RTL_USER_PROCESS_PARAMETERS *params;
888 PEB *peb = NtCurrentTeb()->Peb;
889 HANDLE hstdin, hstdout, hstderr;
890 extern void __wine_dbg_kernel32_init(void);
894 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
898 setlocale(LC_CTYPE,"");
900 /* Retrieve startup info from the server */
901 SERVER_START_REQ( init_process )
904 req->ldt_copy = &wine_ldt_copy;
905 if ((ret = !wine_server_call_err( req )))
907 main_exe_file = reply->exe_file;
908 main_create_flags = reply->create_flags;
909 info_size = reply->info_size;
910 server_startticks = reply->server_start;
911 hstdin = reply->hstdin;
912 hstdout = reply->hstdout;
913 hstderr = reply->hstderr;
917 if (!ret) return FALSE;
921 params = peb->ProcessParameters;
923 /* This is wine specific: we have no parent (we're started from unix)
924 * so, create a simple console with bare handles to unix stdio
925 * input & output streams (aka simple console)
927 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, ¶ms->hStdInput );
928 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdOutput );
929 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdError );
931 params->CurrentDirectory.DosPath.Length = 0;
932 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
933 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
937 if (!(params = init_user_process_params( info_size ))) return FALSE;
938 peb->ProcessParameters = params;
940 /* convert value from server:
941 * + 0 => INVALID_HANDLE_VALUE
942 * + console handle need to be mapped
945 hstdin = INVALID_HANDLE_VALUE;
946 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
947 hstdin = console_handle_map(hstdin);
950 hstdout = INVALID_HANDLE_VALUE;
951 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
952 hstdout = console_handle_map(hstdout);
955 hstderr = INVALID_HANDLE_VALUE;
956 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
957 hstderr = console_handle_map(hstderr);
959 params->hStdInput = hstdin;
960 params->hStdOutput = hstdout;
961 params->hStdError = hstderr;
964 kernel32_handle = GetModuleHandleW(kernel32W);
970 /* Copy the parent environment */
971 if (!build_initial_environment( __wine_main_environ )) return FALSE;
973 /* Create device symlinks */
974 VOLUME_CreateDevices();
976 /* registry initialisation */
977 SHELL_LoadRegistry();
979 /* global boot finished, the rest is process-local */
980 SERVER_START_REQ( boot_done )
982 req->debug_level = TRACE_ON(server);
983 wine_server_call( req );
987 set_registry_environment();
991 init_current_directory( ¶ms->CurrentDirectory );
997 /***********************************************************************
1000 * Startup routine of a new process. Runs on the new process stack.
1002 static void start_process( void *arg )
1006 PEB *peb = NtCurrentTeb()->Peb;
1007 IMAGE_NT_HEADERS *nt;
1008 LPTHREAD_START_ROUTINE entry;
1010 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
1012 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1013 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1014 nt->OptionalHeader.AddressOfEntryPoint);
1016 if (TRACE_ON(relay))
1017 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1018 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1020 SetLastError( 0 ); /* clear error code */
1021 if (peb->BeingDebugged) DbgBreakPoint();
1022 ExitProcess( entry( peb ) );
1024 __EXCEPT(UnhandledExceptionFilter)
1026 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1032 /***********************************************************************
1033 * __wine_kernel_init
1035 * Wine initialisation: load and start the main exe file.
1037 void __wine_kernel_init(void)
1039 WCHAR *main_exe_name, *p;
1041 DWORD stack_size = 0;
1043 PEB *peb = NtCurrentTeb()->Peb;
1045 /* Initialize everything */
1046 if (!process_init()) exit(1);
1048 __wine_main_argv++; /* remove argv[0] (wine itself) */
1051 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1053 WCHAR buffer[MAX_PATH];
1054 WCHAR exe_nameW[MAX_PATH];
1056 if (!__wine_main_argv[0]) usage();
1057 if (__wine_main_argc == 1)
1059 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1060 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1063 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1064 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1066 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1069 if (main_exe_file == INVALID_HANDLE_VALUE)
1071 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1074 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1075 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1078 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1079 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1081 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1082 MODULE_get_dll_load_path(NULL) );
1083 VERSION_Init( main_exe_name );
1085 if (!main_exe_file) /* no file handle -> Winelib app */
1087 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1088 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1090 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1091 debugstr_w(main_exe_name), error );
1095 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1098 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1099 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1101 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1104 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1106 case BINARY_UNKNOWN:
1107 /* check for .com extension */
1108 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1110 MESSAGE( "wine: cannot determine executable type for %s\n",
1111 debugstr_w(main_exe_name) );
1118 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1119 CloseHandle( main_exe_file );
1123 __wine_main_argv[0] = "winevdm.exe";
1124 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1126 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1127 debugstr_w(main_exe_name), error );
1129 case BINARY_UNIX_EXE:
1130 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1132 case BINARY_UNIX_LIB:
1136 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1137 CloseHandle( main_exe_file );
1139 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1140 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1142 static const WCHAR soW[] = {'.','s','o',0};
1143 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1146 /* update the unicode string */
1147 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1149 HeapFree( GetProcessHeap(), 0, unix_name );
1152 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1158 /* build command line */
1159 set_library_wargv( __wine_main_argv );
1160 if (!build_command_line( __wine_main_wargv )) goto error;
1162 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1164 /* allocate main thread stack */
1165 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1167 /* switch to the new stack */
1168 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1171 ExitProcess( GetLastError() );
1175 /***********************************************************************
1178 * Build an argv array from a command-line.
1179 * 'reserved' is the number of args to reserve before the first one.
1181 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1185 char *arg,*s,*d,*cmdline;
1186 int in_quotes,bcount,len;
1188 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1189 if (!(cmdline = malloc(len))) return NULL;
1190 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1197 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1200 /* skip the remaining spaces */
1201 while (*s==' ' || *s=='\t') {
1208 } else if (*s=='\\') {
1209 /* '\', count them */
1211 } else if ((*s=='"') && ((bcount & 1)==0)) {
1213 in_quotes=!in_quotes;
1216 /* a regular character */
1221 argv=malloc(argc*sizeof(*argv));
1230 if ((*s==' ' || *s=='\t') && !in_quotes) {
1231 /* Close the argument and copy it */
1235 /* skip the remaining spaces */
1238 } while (*s==' ' || *s=='\t');
1240 /* Start with a new argument */
1243 } else if (*s=='\\') {
1247 } else if (*s=='"') {
1249 if ((bcount & 1)==0) {
1250 /* Preceeded by an even number of '\', this is half that
1251 * number of '\', plus a '"' which we discard.
1255 in_quotes=!in_quotes;
1257 /* Preceeded by an odd number of '\', this is half that
1258 * number of '\' followed by a '"'
1266 /* a regular character */
1281 /***********************************************************************
1284 * Allocate an environment string; helper for build_envp
1286 static char *alloc_env_string( const char *name, const char *value )
1288 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1289 strcpy( ret, name );
1290 strcat( ret, value );
1294 /***********************************************************************
1297 * Build the environment of a new child process.
1299 static char **build_envp( const WCHAR *envW )
1304 int count = 0, length;
1306 for (end = envW; *end; count++) end += strlenW(end) + 1;
1308 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1309 if (!(env = malloc( length ))) return NULL;
1310 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1314 if ((envp = malloc( count * sizeof(*envp) )))
1316 char **envptr = envp;
1318 /* some variables must not be modified, so we get them directly from the unix env */
1319 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1320 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1321 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1322 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1323 /* now put the Windows environment strings */
1324 for (p = env; *p; p += strlen(p) + 1)
1326 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1327 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1328 if (is_special_env_var( p )) /* prefix it with "WINE" */
1329 *envptr++ = alloc_env_string( "WINE", p );
1339 /***********************************************************************
1342 * Fork and exec a new Unix binary, checking for errors.
1344 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1345 const WCHAR *env, const char *newdir )
1350 if (!env) env = GetEnvironmentStringsW();
1354 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1357 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1358 if (!(pid = fork())) /* child */
1360 char **argv = build_argv( cmdline, 0 );
1361 char **envp = build_envp( env );
1364 /* Reset signals that we previously set to SIG_IGN */
1365 signal( SIGPIPE, SIG_DFL );
1366 signal( SIGCHLD, SIG_DFL );
1368 if (newdir) chdir(newdir);
1370 if (argv && envp) execve( filename, argv, envp );
1372 write( fd[1], &err, sizeof(err) );
1376 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1381 if (pid == -1) FILE_SetDosError();
1387 /***********************************************************************
1388 * create_user_params
1390 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1391 LPCWSTR cur_dir, LPWSTR env,
1392 const STARTUPINFOW *startup )
1394 RTL_USER_PROCESS_PARAMETERS *params;
1395 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1397 WCHAR buffer[MAX_PATH];
1399 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1400 lstrcpynW( buffer, filename, MAX_PATH );
1401 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1402 lstrcpynW( buffer, filename, MAX_PATH );
1403 RtlInitUnicodeString( &image_str, buffer );
1405 RtlInitUnicodeString( &cmdline_str, cmdline );
1406 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1407 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1408 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1409 if (startup->lpReserved2 && startup->cbReserved2)
1411 runtime.Length = runtime.MaximumLength = startup->cbReserved2;
1412 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1415 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1416 cur_dir ? &curdir_str : NULL,
1418 startup->lpTitle ? &title : NULL,
1419 startup->lpDesktop ? &desktop : NULL,
1421 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1422 if (status != STATUS_SUCCESS)
1424 SetLastError( RtlNtStatusToDosError(status) );
1428 params->hStdInput = startup->hStdInput;
1429 params->hStdOutput = startup->hStdOutput;
1430 params->hStdError = startup->hStdError;
1431 params->dwX = startup->dwX;
1432 params->dwY = startup->dwY;
1433 params->dwXSize = startup->dwXSize;
1434 params->dwYSize = startup->dwYSize;
1435 params->dwXCountChars = startup->dwXCountChars;
1436 params->dwYCountChars = startup->dwYCountChars;
1437 params->dwFillAttribute = startup->dwFillAttribute;
1438 params->dwFlags = startup->dwFlags;
1439 params->wShowWindow = startup->wShowWindow;
1444 /***********************************************************************
1447 * Create a new process. If hFile is a valid handle we have an exe
1448 * file, otherwise it is a Winelib app.
1450 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1451 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1452 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1453 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1454 void *res_start, void *res_end )
1456 BOOL ret, success = FALSE;
1457 HANDLE process_info;
1459 RTL_USER_PROCESS_PARAMETERS *params;
1465 char preloader_reserve[64];
1467 if (!env) RtlAcquirePebLock();
1469 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, startup )))
1471 if (!env) RtlReleasePebLock();
1474 env_end = params->Environment;
1475 while (*env_end) env_end += strlenW(env_end) + 1;
1478 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1479 (unsigned long)res_start, (unsigned long)res_end, 0 );
1481 /* create the synchronization pipes */
1483 if (pipe( startfd ) == -1)
1485 if (!env) RtlReleasePebLock();
1486 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1487 RtlDestroyProcessParameters( params );
1490 if (pipe( execfd ) == -1)
1492 if (!env) RtlReleasePebLock();
1493 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1494 close( startfd[0] );
1495 close( startfd[1] );
1496 RtlDestroyProcessParameters( params );
1499 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1501 /* create the child process */
1503 if (!(pid = fork())) /* child */
1505 char **argv = build_argv( cmd_line, 1 );
1507 close( startfd[1] );
1510 /* wait for parent to tell us to start */
1511 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1513 close( startfd[0] );
1514 /* Reset signals that we previously set to SIG_IGN */
1515 signal( SIGPIPE, SIG_DFL );
1516 signal( SIGCHLD, SIG_DFL );
1518 putenv( preloader_reserve );
1519 if (unixdir) chdir(unixdir);
1523 /* first, try for a WINELOADER environment variable */
1524 const char *loader = getenv("WINELOADER");
1525 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1526 /* now use the standard search strategy */
1527 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1530 write( execfd[1], &err, sizeof(err) );
1534 /* this is the parent */
1536 close( startfd[0] );
1540 if (!env) RtlReleasePebLock();
1541 close( startfd[1] );
1544 RtlDestroyProcessParameters( params );
1548 /* create the process on the server side */
1550 SERVER_START_REQ( new_process )
1552 req->inherit_all = inherit;
1553 req->create_flags = flags;
1554 req->unix_pid = pid;
1555 req->exe_file = hFile;
1556 if (startup->dwFlags & STARTF_USESTDHANDLES)
1558 req->hstdin = startup->hStdInput;
1559 req->hstdout = startup->hStdOutput;
1560 req->hstderr = startup->hStdError;
1564 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1565 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1566 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1569 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1571 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1572 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1573 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1574 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1578 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1579 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1580 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1583 wine_server_add_data( req, params, params->Size );
1584 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1585 ret = !wine_server_call_err( req );
1586 process_info = reply->info;
1590 if (!env) RtlReleasePebLock();
1591 RtlDestroyProcessParameters( params );
1594 close( startfd[1] );
1599 /* tell child to start and wait for it to exec */
1601 write( startfd[1], &dummy, 1 );
1602 close( startfd[1] );
1604 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1609 CloseHandle( process_info );
1614 /* wait for the new process info to be ready */
1616 WaitForSingleObject( process_info, INFINITE );
1617 SERVER_START_REQ( get_new_process_info )
1619 req->info = process_info;
1620 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1621 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1622 if ((ret = !wine_server_call_err( req )))
1624 info->dwProcessId = (DWORD)reply->pid;
1625 info->dwThreadId = (DWORD)reply->tid;
1626 info->hProcess = reply->phandle;
1627 info->hThread = reply->thandle;
1628 success = reply->success;
1633 if (ret && !success) /* new process failed to start */
1636 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1637 CloseHandle( info->hThread );
1638 CloseHandle( info->hProcess );
1641 CloseHandle( process_info );
1646 /***********************************************************************
1647 * create_vdm_process
1649 * Create a new VDM process for a 16-bit or DOS application.
1651 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1652 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1653 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1654 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1656 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1659 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1660 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1664 SetLastError( ERROR_OUTOFMEMORY );
1667 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1668 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1669 flags, startup, info, unixdir, NULL, NULL );
1670 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1675 /***********************************************************************
1676 * create_cmd_process
1678 * Create a new cmd shell process for a .BAT file.
1680 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1681 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1682 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1683 LPPROCESS_INFORMATION info )
1686 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1687 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1688 WCHAR comspec[MAX_PATH];
1692 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1694 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1695 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1698 strcpyW( newcmdline, comspec );
1699 strcatW( newcmdline, slashcW );
1700 strcatW( newcmdline, cmd_line );
1701 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1702 flags, env, cur_dir, startup, info );
1703 HeapFree( GetProcessHeap(), 0, newcmdline );
1708 /*************************************************************************
1711 * Helper for CreateProcess: retrieve the file name to load from the
1712 * app name and command line. Store the file name in buffer, and
1713 * return a possibly modified command line.
1714 * Also returns a handle to the opened file if it's a Windows binary.
1716 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1717 int buflen, HANDLE *handle )
1719 static const WCHAR quotesW[] = {'"','%','s','"',0};
1721 WCHAR *name, *pos, *ret = NULL;
1724 /* if we have an app name, everything is easy */
1728 /* use the unmodified app name as file name */
1729 lstrcpynW( buffer, appname, buflen );
1730 *handle = open_exe_file( buffer );
1731 if (!(ret = cmdline) || !cmdline[0])
1733 /* no command-line, create one */
1734 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1735 sprintfW( ret, quotesW, appname );
1742 SetLastError( ERROR_INVALID_PARAMETER );
1746 /* first check for a quoted file name */
1748 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1750 int len = p - cmdline - 1;
1751 /* extract the quoted portion as file name */
1752 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1753 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1756 if (find_exe_file( name, buffer, buflen, handle ))
1757 ret = cmdline; /* no change necessary */
1761 /* now try the command-line word by word */
1763 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1770 do *pos++ = *p++; while (*p && *p != ' ');
1772 if (find_exe_file( name, buffer, buflen, handle ))
1779 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1781 /* now build a new command-line with quotes */
1783 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1785 sprintfW( ret, quotesW, name );
1789 HeapFree( GetProcessHeap(), 0, name );
1794 /**********************************************************************
1795 * CreateProcessA (KERNEL32.@)
1797 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1798 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1799 DWORD flags, LPVOID env, LPCSTR cur_dir,
1800 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1803 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1804 UNICODE_STRING desktopW, titleW;
1807 desktopW.Buffer = NULL;
1808 titleW.Buffer = NULL;
1809 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1810 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1811 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1813 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1814 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1816 memcpy( &infoW, startup_info, sizeof(infoW) );
1817 infoW.lpDesktop = desktopW.Buffer;
1818 infoW.lpTitle = titleW.Buffer;
1820 if (startup_info->lpReserved)
1821 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1822 debugstr_a(startup_info->lpReserved));
1824 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1825 inherit, flags, env, cur_dirW, &infoW, info );
1827 if (app_nameW) HeapFree( GetProcessHeap(), 0, app_nameW );
1828 if (cmd_lineW) HeapFree( GetProcessHeap(), 0, cmd_lineW );
1829 if (cur_dirW) HeapFree( GetProcessHeap(), 0, cur_dirW );
1830 RtlFreeUnicodeString( &desktopW );
1831 RtlFreeUnicodeString( &titleW );
1836 /**********************************************************************
1837 * CreateProcessW (KERNEL32.@)
1839 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1840 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1841 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1842 LPPROCESS_INFORMATION info )
1846 char *unixdir = NULL;
1847 WCHAR name[MAX_PATH];
1848 WCHAR *tidy_cmdline, *p, *envW = env;
1849 void *res_start, *res_end;
1851 /* Process the AppName and/or CmdLine to get module name and path */
1853 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1855 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1857 if (hFile == INVALID_HANDLE_VALUE) goto done;
1859 /* Warn if unsupported features are used */
1861 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1862 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1863 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1864 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1865 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1869 unixdir = wine_get_unix_file_name( cur_dir );
1873 WCHAR buf[MAX_PATH];
1874 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1877 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1882 while (*p) p += strlen(p) + 1;
1883 p++; /* final null */
1884 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1885 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1886 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1887 flags |= CREATE_UNICODE_ENVIRONMENT;
1890 info->hThread = info->hProcess = 0;
1891 info->dwProcessId = info->dwThreadId = 0;
1893 /* Determine executable type */
1895 if (!hFile) /* builtin exe */
1897 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1898 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1899 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1903 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1906 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1907 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1908 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1913 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1914 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1915 inherit, flags, startup_info, info, unixdir );
1918 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1919 SetLastError( ERROR_BAD_EXE_FORMAT );
1921 case BINARY_UNIX_LIB:
1922 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1923 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1924 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1926 case BINARY_UNKNOWN:
1927 /* check for .com or .bat extension */
1928 if ((p = strrchrW( name, '.' )))
1930 if (!strcmpiW( p, comW ))
1932 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1933 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1934 inherit, flags, startup_info, info, unixdir );
1937 if (!strcmpiW( p, batW ))
1939 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1940 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1941 inherit, flags, startup_info, info );
1946 case BINARY_UNIX_EXE:
1948 /* unknown file, try as unix executable */
1951 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1953 if ((unix_name = wine_get_unix_file_name( name )))
1955 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1956 HeapFree( GetProcessHeap(), 0, unix_name );
1961 CloseHandle( hFile );
1964 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1965 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1966 if (unixdir) HeapFree( GetProcessHeap(), 0, unixdir );
1971 /***********************************************************************
1974 * Wrapper to call WaitForInputIdle USER function
1976 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1978 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1980 HMODULE mod = GetModuleHandleA( "user32.dll" );
1983 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1984 if (ptr) return ptr( process, timeout );
1990 /***********************************************************************
1991 * WinExec (KERNEL32.@)
1993 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1995 PROCESS_INFORMATION info;
1996 STARTUPINFOA startup;
2000 memset( &startup, 0, sizeof(startup) );
2001 startup.cb = sizeof(startup);
2002 startup.dwFlags = STARTF_USESHOWWINDOW;
2003 startup.wShowWindow = nCmdShow;
2005 /* cmdline needs to be writeable for CreateProcess */
2006 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2007 strcpy( cmdline, lpCmdLine );
2009 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2010 0, NULL, NULL, &startup, &info ))
2012 /* Give 30 seconds to the app to come up */
2013 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2014 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2016 /* Close off the handles */
2017 CloseHandle( info.hThread );
2018 CloseHandle( info.hProcess );
2020 else if ((ret = GetLastError()) >= 32)
2022 FIXME("Strange error set by CreateProcess: %d\n", ret );
2025 HeapFree( GetProcessHeap(), 0, cmdline );
2030 /**********************************************************************
2031 * LoadModule (KERNEL32.@)
2033 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2035 LOADPARMS32 *params = paramBlock;
2036 PROCESS_INFORMATION info;
2037 STARTUPINFOA startup;
2038 HINSTANCE hInstance;
2040 char filename[MAX_PATH];
2043 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2045 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2046 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2047 return (HINSTANCE)GetLastError();
2049 len = (BYTE)params->lpCmdLine[0];
2050 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2051 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2053 strcpy( cmdline, filename );
2054 p = cmdline + strlen(cmdline);
2056 memcpy( p, params->lpCmdLine + 1, len );
2059 memset( &startup, 0, sizeof(startup) );
2060 startup.cb = sizeof(startup);
2061 if (params->lpCmdShow)
2063 startup.dwFlags = STARTF_USESHOWWINDOW;
2064 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2067 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2068 params->lpEnvAddress, NULL, &startup, &info ))
2070 /* Give 30 seconds to the app to come up */
2071 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2072 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2073 hInstance = (HINSTANCE)33;
2074 /* Close off the handles */
2075 CloseHandle( info.hThread );
2076 CloseHandle( info.hProcess );
2078 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2080 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2081 hInstance = (HINSTANCE)11;
2084 HeapFree( GetProcessHeap(), 0, cmdline );
2089 /******************************************************************************
2090 * TerminateProcess (KERNEL32.@)
2092 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2094 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2095 if (status) SetLastError( RtlNtStatusToDosError(status) );
2100 /***********************************************************************
2101 * ExitProcess (KERNEL32.@)
2103 void WINAPI ExitProcess( DWORD status )
2105 LdrShutdownProcess();
2106 SERVER_START_REQ( terminate_process )
2108 /* send the exit code to the server */
2109 req->handle = GetCurrentProcess();
2110 req->exit_code = status;
2111 wine_server_call( req );
2118 /***********************************************************************
2119 * GetExitCodeProcess [KERNEL32.@]
2121 * Gets termination status of specified process
2127 BOOL WINAPI GetExitCodeProcess(
2128 HANDLE hProcess, /* [in] handle to the process */
2129 LPDWORD lpExitCode) /* [out] address to receive termination status */
2132 PROCESS_BASIC_INFORMATION pbi;
2134 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2136 if (status == STATUS_SUCCESS)
2138 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2141 SetLastError( RtlNtStatusToDosError(status) );
2146 /***********************************************************************
2147 * SetErrorMode (KERNEL32.@)
2149 UINT WINAPI SetErrorMode( UINT mode )
2151 UINT old = process_error_mode;
2152 process_error_mode = mode;
2157 /**********************************************************************
2158 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2160 * Allocates a thread local storage index
2163 * Success: TLS Index
2164 * Failure: 0xFFFFFFFF
2166 DWORD WINAPI TlsAlloc( void )
2170 RtlAcquirePebLock();
2171 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
2172 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2173 else SetLastError( ERROR_NO_MORE_ITEMS );
2174 RtlReleasePebLock();
2179 /**********************************************************************
2180 * TlsFree [KERNEL32.@] Releases a TLS index.
2182 * Releases a thread local storage index, making it available for reuse
2188 BOOL WINAPI TlsFree(
2189 DWORD index) /* [in] TLS Index to free */
2193 RtlAcquirePebLock();
2194 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2197 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2198 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2200 else SetLastError( ERROR_INVALID_PARAMETER );
2201 RtlReleasePebLock();
2206 /**********************************************************************
2207 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2210 * Success: Value stored in calling thread's TLS slot for index
2211 * Failure: 0 and GetLastError returns NO_ERROR
2213 LPVOID WINAPI TlsGetValue(
2214 DWORD index) /* [in] TLS index to retrieve value for */
2216 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2218 SetLastError( ERROR_INVALID_PARAMETER );
2221 SetLastError( ERROR_SUCCESS );
2222 return NtCurrentTeb()->TlsSlots[index];
2226 /**********************************************************************
2227 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2233 BOOL WINAPI TlsSetValue(
2234 DWORD index, /* [in] TLS index to set value for */
2235 LPVOID value) /* [in] Value to be stored */
2237 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2239 SetLastError( ERROR_INVALID_PARAMETER );
2242 NtCurrentTeb()->TlsSlots[index] = value;
2247 /***********************************************************************
2248 * GetProcessFlags (KERNEL32.@)
2250 DWORD WINAPI GetProcessFlags( DWORD processid )
2252 IMAGE_NT_HEADERS *nt;
2255 if (processid && processid != GetCurrentProcessId()) return 0;
2257 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2259 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2260 flags |= PDB32_CONSOLE_PROC;
2262 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2263 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2268 /***********************************************************************
2269 * GetProcessDword (KERNEL.485)
2270 * GetProcessDword (KERNEL32.18)
2271 * 'Of course you cannot directly access Windows internal structures'
2273 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2278 TRACE("(%ld, %d)\n", dwProcessID, offset );
2280 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2282 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2288 case GPD_APP_COMPAT_FLAGS:
2289 return GetAppCompatFlags16(0);
2290 case GPD_LOAD_DONE_EVENT:
2292 case GPD_HINSTANCE16:
2293 return GetTaskDS16();
2294 case GPD_WINDOWS_VERSION:
2295 return GetExeVersion16();
2297 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2299 return (DWORD)NtCurrentTeb()->Peb;
2300 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2301 GetStartupInfoW(&siw);
2302 return (DWORD)siw.hStdOutput;
2303 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2304 GetStartupInfoW(&siw);
2305 return (DWORD)siw.hStdInput;
2306 case GPD_STARTF_SHOWWINDOW:
2307 GetStartupInfoW(&siw);
2308 return siw.wShowWindow;
2309 case GPD_STARTF_SIZE:
2310 GetStartupInfoW(&siw);
2312 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2314 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2315 return MAKELONG( x, y );
2316 case GPD_STARTF_POSITION:
2317 GetStartupInfoW(&siw);
2319 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2321 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2322 return MAKELONG( x, y );
2323 case GPD_STARTF_FLAGS:
2324 GetStartupInfoW(&siw);
2329 return GetProcessFlags(0);
2331 return process_dword;
2333 ERR("Unknown offset %d\n", offset );
2338 /***********************************************************************
2339 * SetProcessDword (KERNEL.484)
2340 * 'Of course you cannot directly access Windows internal structures'
2342 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2344 TRACE("(%ld, %d)\n", dwProcessID, offset );
2346 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2348 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2354 case GPD_APP_COMPAT_FLAGS:
2355 case GPD_LOAD_DONE_EVENT:
2356 case GPD_HINSTANCE16:
2357 case GPD_WINDOWS_VERSION:
2360 case GPD_STARTF_SHELLDATA:
2361 case GPD_STARTF_HOTKEY:
2362 case GPD_STARTF_SHOWWINDOW:
2363 case GPD_STARTF_SIZE:
2364 case GPD_STARTF_POSITION:
2365 case GPD_STARTF_FLAGS:
2368 ERR("Not allowed to modify offset %d\n", offset );
2371 process_dword = value;
2374 ERR("Unknown offset %d\n", offset );
2380 /***********************************************************************
2381 * ExitProcess (KERNEL.466)
2383 void WINAPI ExitProcess16( WORD status )
2386 ReleaseThunkLock( &count );
2387 ExitProcess( status );
2391 /*********************************************************************
2392 * OpenProcess (KERNEL32.@)
2394 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2397 SERVER_START_REQ( open_process )
2400 req->access = access;
2401 req->inherit = inherit;
2402 if (!wine_server_call_err( req )) ret = reply->handle;
2409 /*********************************************************************
2410 * MapProcessHandle (KERNEL.483)
2411 * GetProcessId (KERNEL32.@)
2413 DWORD WINAPI GetProcessId( HANDLE hProcess )
2416 PROCESS_BASIC_INFORMATION pbi;
2418 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2420 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2421 SetLastError( RtlNtStatusToDosError(status) );
2426 /*********************************************************************
2427 * CloseW32Handle (KERNEL.474)
2428 * CloseHandle (KERNEL32.@)
2430 BOOL WINAPI CloseHandle( HANDLE handle )
2434 /* stdio handles need special treatment */
2435 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2436 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2437 (handle == (HANDLE)STD_ERROR_HANDLE))
2438 handle = GetStdHandle( (DWORD)handle );
2440 if (is_console_handle(handle))
2441 return CloseConsoleHandle(handle);
2443 status = NtClose( handle );
2444 if (status) SetLastError( RtlNtStatusToDosError(status) );
2449 /*********************************************************************
2450 * GetHandleInformation (KERNEL32.@)
2452 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2455 SERVER_START_REQ( set_handle_info )
2457 req->handle = handle;
2461 ret = !wine_server_call_err( req );
2462 if (ret && flags) *flags = reply->old_flags;
2469 /*********************************************************************
2470 * SetHandleInformation (KERNEL32.@)
2472 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2475 SERVER_START_REQ( set_handle_info )
2477 req->handle = handle;
2481 ret = !wine_server_call_err( req );
2488 /*********************************************************************
2489 * DuplicateHandle (KERNEL32.@)
2491 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2492 HANDLE dest_process, HANDLE *dest,
2493 DWORD access, BOOL inherit, DWORD options )
2497 if (is_console_handle(source))
2499 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2500 if (source_process != dest_process ||
2501 source_process != GetCurrentProcess())
2503 SetLastError(ERROR_INVALID_PARAMETER);
2506 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2507 return (*dest != INVALID_HANDLE_VALUE);
2509 status = NtDuplicateObject( source_process, source, dest_process, dest,
2510 access, inherit ? OBJ_INHERIT : 0, options );
2511 if (status) SetLastError( RtlNtStatusToDosError(status) );
2516 /***********************************************************************
2517 * ConvertToGlobalHandle (KERNEL.476)
2518 * ConvertToGlobalHandle (KERNEL32.@)
2520 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2522 HANDLE ret = INVALID_HANDLE_VALUE;
2523 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2524 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2529 /***********************************************************************
2530 * SetHandleContext (KERNEL32.@)
2532 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2534 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2535 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2536 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2541 /***********************************************************************
2542 * GetHandleContext (KERNEL32.@)
2544 DWORD WINAPI GetHandleContext(HANDLE hnd)
2546 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2547 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2548 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2553 /***********************************************************************
2554 * CreateSocketHandle (KERNEL32.@)
2556 HANDLE WINAPI CreateSocketHandle(void)
2558 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2559 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2560 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2561 return INVALID_HANDLE_VALUE;
2565 /***********************************************************************
2566 * SetPriorityClass (KERNEL32.@)
2568 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2571 SERVER_START_REQ( set_process_info )
2573 req->handle = hprocess;
2574 req->priority = priorityclass;
2575 req->mask = SET_PROCESS_INFO_PRIORITY;
2576 ret = !wine_server_call_err( req );
2583 /***********************************************************************
2584 * GetPriorityClass (KERNEL32.@)
2586 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2589 PROCESS_BASIC_INFORMATION pbi;
2591 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2593 if (status == STATUS_SUCCESS) return pbi.BasePriority;
2594 SetLastError( RtlNtStatusToDosError(status) );
2599 /***********************************************************************
2600 * SetProcessAffinityMask (KERNEL32.@)
2602 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2605 SERVER_START_REQ( set_process_info )
2607 req->handle = hProcess;
2608 req->affinity = affmask;
2609 req->mask = SET_PROCESS_INFO_AFFINITY;
2610 ret = !wine_server_call_err( req );
2617 /**********************************************************************
2618 * GetProcessAffinityMask (KERNEL32.@)
2620 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2621 LPDWORD lpProcessAffinityMask,
2622 LPDWORD lpSystemAffinityMask )
2625 SERVER_START_REQ( get_process_info )
2627 req->handle = hProcess;
2628 if (!wine_server_call_err( req ))
2630 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2631 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2640 /***********************************************************************
2641 * GetProcessVersion (KERNEL32.@)
2643 DWORD WINAPI GetProcessVersion( DWORD processid )
2645 IMAGE_NT_HEADERS *nt;
2647 if (processid && processid != GetCurrentProcessId())
2649 FIXME("should use ReadProcessMemory\n");
2652 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2653 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2654 nt->OptionalHeader.MinorSubsystemVersion);
2659 /***********************************************************************
2660 * SetProcessWorkingSetSize [KERNEL32.@]
2661 * Sets the min/max working set sizes for a specified process.
2664 * hProcess [I] Handle to the process of interest
2665 * minset [I] Specifies minimum working set size
2666 * maxset [I] Specifies maximum working set size
2670 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2673 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2674 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2675 /* Trim the working set to zero */
2676 /* Swap the process out of physical RAM */
2681 /***********************************************************************
2682 * GetProcessWorkingSetSize (KERNEL32.@)
2684 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2687 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2688 /* 32 MB working set size */
2689 if (minset) *minset = 32*1024*1024;
2690 if (maxset) *maxset = 32*1024*1024;
2695 /***********************************************************************
2696 * SetProcessShutdownParameters (KERNEL32.@)
2698 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2700 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2701 shutdown_flags = flags;
2702 shutdown_priority = level;
2707 /***********************************************************************
2708 * GetProcessShutdownParameters (KERNEL32.@)
2711 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2713 *lpdwLevel = shutdown_priority;
2714 *lpdwFlags = shutdown_flags;
2719 /***********************************************************************
2720 * GetProcessPriorityBoost (KERNEL32.@)
2722 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2724 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2726 /* Report that no boost is present.. */
2727 *pDisablePriorityBoost = FALSE;
2732 /***********************************************************************
2733 * SetProcessPriorityBoost (KERNEL32.@)
2735 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2737 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2738 /* Say we can do it. I doubt the program will notice that we don't. */
2743 /***********************************************************************
2744 * ReadProcessMemory (KERNEL32.@)
2746 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2747 SIZE_T *bytes_read )
2749 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2750 if (status) SetLastError( RtlNtStatusToDosError(status) );
2755 /***********************************************************************
2756 * WriteProcessMemory (KERNEL32.@)
2758 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2759 SIZE_T *bytes_written )
2761 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2762 if (status) SetLastError( RtlNtStatusToDosError(status) );
2767 /****************************************************************************
2768 * FlushInstructionCache (KERNEL32.@)
2770 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2773 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2774 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2775 if (status) SetLastError( RtlNtStatusToDosError(status) );
2780 /******************************************************************
2781 * GetProcessIoCounters (KERNEL32.@)
2783 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2787 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2788 ioc, sizeof(*ioc), NULL);
2789 if (status) SetLastError( RtlNtStatusToDosError(status) );
2793 /***********************************************************************
2794 * ProcessIdToSessionId (KERNEL32.@)
2795 * This function is available on Terminal Server 4SP4 and Windows 2000
2797 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2799 /* According to MSDN, if the calling process is not in a terminal
2800 * services environment, then the sessionid returned is zero.
2807 /***********************************************************************
2808 * RegisterServiceProcess (KERNEL.491)
2809 * RegisterServiceProcess (KERNEL32.@)
2811 * A service process calls this function to ensure that it continues to run
2812 * even after a user logged off.
2814 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2816 /* I don't think that Wine needs to do anything in that function */
2817 return 1; /* success */
2821 /***********************************************************************
2822 * GetSystemMSecCount (SYSTEM.6)
2823 * GetTickCount (KERNEL32.@)
2825 * Returns the number of milliseconds, modulo 2^32, since the start
2826 * of the wineserver.
2828 DWORD WINAPI GetTickCount(void)
2831 gettimeofday( &t, NULL );
2832 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2836 /***********************************************************************
2837 * GetCurrentProcess (KERNEL32.@)
2839 #undef GetCurrentProcess
2840 HANDLE WINAPI GetCurrentProcess(void)
2842 return (HANDLE)0xffffffff;