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 */
382 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
383 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
386 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
387 endptr = p + size / sizeof(WCHAR);
389 /* And fill it with the Unix environment */
390 for (e = environ; *e; e++)
394 /* skip Unix special variables and use the Wine variants instead */
395 if (!strncmp( str, "WINE", 4 ))
397 if (is_special_env_var( str + 4 )) str += 4;
398 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
400 else if (is_special_env_var( str )) continue; /* skip it */
402 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
410 /***********************************************************************
411 * set_registry_variables
413 * Set environment variables by enumerating the values of a key;
414 * helper for set_registry_environment().
416 static void set_registry_variables( HKEY hkey )
418 UNICODE_STRING env_name, env_value;
422 char buffer[1024 + sizeof(KEY_VALUE_FULL_INFORMATION)];
423 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
425 for (index = 0; ; index++)
427 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
428 buffer, sizeof(buffer), &size );
429 if (status == STATUS_BUFFER_OVERFLOW) continue;
430 if (status != STATUS_SUCCESS) break;
431 if (info->Type != REG_SZ) continue; /* FIXME: handle REG_EXPAND_SZ */
432 env_name.Buffer = info->Name;
433 env_name.Length = env_name.MaximumLength = info->NameLength;
434 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
435 env_value.Length = env_value.MaximumLength = info->DataLength;
436 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
437 env_value.Length--; /* don't count terminating null if any */
438 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
443 /***********************************************************************
444 * set_registry_environment
446 * Set the environment variables specified in the registry.
448 static void set_registry_environment(void)
450 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
451 'S','y','s','t','e','m','\\',
452 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
453 'C','o','n','t','r','o','l','\\',
454 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
455 'E','n','v','i','r','o','n','m','e','n','t',0};
456 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
458 OBJECT_ATTRIBUTES attr;
459 UNICODE_STRING nameW;
462 attr.Length = sizeof(attr);
463 attr.RootDirectory = 0;
464 attr.ObjectName = &nameW;
466 attr.SecurityDescriptor = NULL;
467 attr.SecurityQualityOfService = NULL;
469 /* first the system environment variables */
470 RtlInitUnicodeString( &nameW, env_keyW );
471 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
473 set_registry_variables( hkey );
477 /* then the ones for the current user */
478 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, (HKEY *)&attr.RootDirectory ) != STATUS_SUCCESS) return;
479 RtlInitUnicodeString( &nameW, envW );
480 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
482 set_registry_variables( hkey );
485 NtClose( attr.RootDirectory );
489 /***********************************************************************
492 * Set the Wine library Unicode argv global variables.
494 static void set_library_wargv( char **argv )
502 for (argc = 0; argv[argc]; argc++)
503 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
505 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
506 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
507 p = (WCHAR *)(wargv + argc + 1);
508 for (argc = 0; argv[argc]; argc++)
510 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
517 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
519 for (argc = 0; wargv[argc]; argc++)
520 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
522 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
523 q = (char *)(argv + argc + 1);
524 for (argc = 0; wargv[argc]; argc++)
526 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
533 __wine_main_argv = argv;
534 __wine_main_wargv = wargv;
538 /***********************************************************************
541 * Build the command line of a process from the argv array.
543 * Note that it does NOT necessarily include the file name.
544 * Sometimes we don't even have any command line options at all.
546 * We must quote and escape characters so that the argv array can be rebuilt
547 * from the command line:
548 * - spaces and tabs must be quoted
550 * - quotes must be escaped
552 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
553 * resulting in an odd number of '\' followed by a '"'
556 * - '\'s that are not followed by a '"' can be left as is
560 static BOOL build_command_line( WCHAR **argv )
565 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
567 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
570 for (arg = argv; *arg; arg++)
572 int has_space,bcount;
578 if( !*a ) has_space=1;
583 if (*a==' ' || *a=='\t') {
585 } else if (*a=='"') {
586 /* doubling of '\' preceeding a '"',
587 * plus escaping of said '"'
595 len+=(a-*arg)+1 /* for the separating space */;
597 len+=2; /* for the quotes */
600 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
603 p = rupp->CommandLine.Buffer;
604 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
605 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
606 for (arg = argv; *arg; arg++)
608 int has_space,has_quote;
611 /* Check for quotes and spaces in this argument */
612 has_space=has_quote=0;
614 if( !*a ) has_space=1;
616 if (*a==' ' || *a=='\t') {
620 } else if (*a=='"') {
628 /* Now transfer it to the command line */
645 /* Double all the '\\' preceeding this '"', plus one */
646 for (i=0;i<=bcount;i++)
658 while ((*p=*x++)) p++;
664 if (p > rupp->CommandLine.Buffer)
665 p--; /* remove last space */
672 /* make sure the unicode string doesn't point beyond the end pointer */
673 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
675 if ((char *)str->Buffer >= end_ptr)
677 str->Length = str->MaximumLength = 0;
681 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
683 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
685 if (str->Length >= str->MaximumLength)
687 if (str->MaximumLength >= sizeof(WCHAR))
688 str->Length = str->MaximumLength - sizeof(WCHAR);
690 str->Length = str->MaximumLength = 0;
694 static void version(void)
696 MESSAGE( "%s\n", PACKAGE_STRING );
700 static void usage(void)
702 MESSAGE( "%s\n", PACKAGE_STRING );
703 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
704 MESSAGE( " wine --help Display this help and exit\n");
705 MESSAGE( " wine --version Output version information and exit\n");
710 /***********************************************************************
711 * init_user_process_params
713 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
715 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
718 DWORD size, env_size;
719 RTL_USER_PROCESS_PARAMETERS *params;
722 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
723 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
726 SERVER_START_REQ( get_startup_info )
728 wine_server_set_reply( req, ptr, info_size );
729 wine_server_call( req );
730 info_size = wine_server_reply_size( reply );
735 params->AllocationSize = size;
736 if (params->Size > info_size) params->Size = info_size;
738 /* make sure the strings are valid */
739 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
740 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
741 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
742 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
743 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
744 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
745 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
746 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
748 /* environment needs to be a separate memory block */
749 env_size = info_size - params->Size;
750 if (!env_size) env_size = 1;
751 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &env_size,
752 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
754 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
755 params->Environment = ptr;
757 return RtlNormalizeProcessParams( params );
761 /***********************************************************************
762 * init_current_directory
764 * Initialize the current directory from the Unix cwd or the parent info.
766 static void init_current_directory( CURDIR *cur_dir )
768 UNICODE_STRING dir_str;
772 /* if we received a cur dir from the parent, try this first */
774 if (cur_dir->DosPath.Length)
776 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
779 /* now try to get it from the Unix cwd */
781 for (size = 256; ; size *= 2)
783 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
784 if (getcwd( cwd, size )) break;
785 HeapFree( GetProcessHeap(), 0, cwd );
786 if (errno == ERANGE) continue;
794 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
795 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
797 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
798 RtlInitUnicodeString( &dir_str, dirW );
799 RtlSetCurrentDirectory_U( &dir_str );
800 RtlFreeUnicodeString( &dir_str );
804 if (!cur_dir->DosPath.Length) /* still not initialized */
806 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
807 "starting in the Windows directory.\n", cwd ? cwd : "" );
808 RtlInitUnicodeString( &dir_str, DIR_Windows );
809 RtlSetCurrentDirectory_U( &dir_str );
811 if (cwd) HeapFree( GetProcessHeap(), 0, cwd );
814 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
815 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
819 /***********************************************************************
822 * Initialize the windows and system directories from the environment.
824 static void init_windows_dirs(void)
826 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
828 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
829 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
830 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
831 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m',0};
836 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
838 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
839 GetEnvironmentVariableW( windirW, buffer, len );
840 DIR_Windows = buffer;
842 else DIR_Windows = default_windirW;
844 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
846 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
847 GetEnvironmentVariableW( winsysdirW, buffer, len );
852 len = strlenW( DIR_Windows );
853 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
854 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
855 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
859 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
860 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
861 debugstr_w(DIR_Windows) );
862 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
863 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
864 debugstr_w(DIR_System) );
866 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
867 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
869 /* set the directories in ntdll too */
870 __wine_init_windows_dir( DIR_Windows, DIR_System );
874 /***********************************************************************
877 * Main process initialisation code
879 static BOOL process_init(void)
881 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
883 size_t info_size = 0;
884 RTL_USER_PROCESS_PARAMETERS *params;
885 PEB *peb = NtCurrentTeb()->Peb;
886 HANDLE hstdin, hstdout, hstderr;
887 extern void __wine_dbg_kernel32_init(void);
891 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
895 setlocale(LC_CTYPE,"");
897 /* Retrieve startup info from the server */
898 SERVER_START_REQ( init_process )
901 req->ldt_copy = &wine_ldt_copy;
902 if ((ret = !wine_server_call_err( req )))
904 main_exe_file = reply->exe_file;
905 main_create_flags = reply->create_flags;
906 info_size = reply->info_size;
907 server_startticks = reply->server_start;
908 hstdin = reply->hstdin;
909 hstdout = reply->hstdout;
910 hstderr = reply->hstderr;
914 if (!ret) return FALSE;
918 params = peb->ProcessParameters;
920 /* This is wine specific: we have no parent (we're started from unix)
921 * so, create a simple console with bare handles to unix stdio
922 * input & output streams (aka simple console)
924 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, ¶ms->hStdInput );
925 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdOutput );
926 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdError );
928 params->CurrentDirectory.DosPath.Length = 0;
929 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
930 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
934 if (!(params = init_user_process_params( info_size ))) return FALSE;
935 peb->ProcessParameters = params;
937 /* convert value from server:
938 * + 0 => INVALID_HANDLE_VALUE
939 * + console handle need to be mapped
942 hstdin = INVALID_HANDLE_VALUE;
943 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
944 hstdin = console_handle_map(hstdin);
947 hstdout = INVALID_HANDLE_VALUE;
948 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
949 hstdout = console_handle_map(hstdout);
952 hstderr = INVALID_HANDLE_VALUE;
953 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
954 hstderr = console_handle_map(hstderr);
956 params->hStdInput = hstdin;
957 params->hStdOutput = hstdout;
958 params->hStdError = hstderr;
961 kernel32_handle = GetModuleHandleW(kernel32W);
967 /* Copy the parent environment */
968 if (!build_initial_environment( __wine_main_environ )) return FALSE;
970 /* Create device symlinks */
971 VOLUME_CreateDevices();
973 /* registry initialisation */
974 SHELL_LoadRegistry();
976 /* global boot finished, the rest is process-local */
977 SERVER_START_REQ( boot_done )
979 req->debug_level = TRACE_ON(server);
980 wine_server_call( req );
984 set_registry_environment();
988 init_current_directory( ¶ms->CurrentDirectory );
994 /***********************************************************************
997 * Startup routine of a new process. Runs on the new process stack.
999 static void start_process( void *arg )
1003 PEB *peb = NtCurrentTeb()->Peb;
1004 IMAGE_NT_HEADERS *nt;
1005 LPTHREAD_START_ROUTINE entry;
1007 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
1009 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1010 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1011 nt->OptionalHeader.AddressOfEntryPoint);
1013 if (TRACE_ON(relay))
1014 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1015 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1017 SetLastError( 0 ); /* clear error code */
1018 if (peb->BeingDebugged) DbgBreakPoint();
1019 ExitProcess( entry( peb ) );
1021 __EXCEPT(UnhandledExceptionFilter)
1023 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1029 /***********************************************************************
1030 * __wine_kernel_init
1032 * Wine initialisation: load and start the main exe file.
1034 void __wine_kernel_init(void)
1036 WCHAR *main_exe_name, *p;
1038 DWORD stack_size = 0;
1040 PEB *peb = NtCurrentTeb()->Peb;
1042 /* Initialize everything */
1043 if (!process_init()) exit(1);
1045 __wine_main_argv++; /* remove argv[0] (wine itself) */
1048 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1050 WCHAR buffer[MAX_PATH];
1051 WCHAR exe_nameW[MAX_PATH];
1053 if (!__wine_main_argv[0]) usage();
1054 if (__wine_main_argc == 1)
1056 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1057 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1060 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1061 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1063 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1066 if (main_exe_file == INVALID_HANDLE_VALUE)
1068 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1071 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1072 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1075 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1076 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1078 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1079 MODULE_get_dll_load_path(NULL) );
1080 VERSION_Init( main_exe_name );
1082 if (!main_exe_file) /* no file handle -> Winelib app */
1084 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1085 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1087 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1088 debugstr_w(main_exe_name), error );
1092 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1095 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1096 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1098 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1101 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1103 case BINARY_UNKNOWN:
1104 /* check for .com extension */
1105 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1107 MESSAGE( "wine: cannot determine executable type for %s\n",
1108 debugstr_w(main_exe_name) );
1115 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1116 CloseHandle( main_exe_file );
1120 __wine_main_argv[0] = "winevdm.exe";
1121 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1123 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1124 debugstr_w(main_exe_name), error );
1126 case BINARY_UNIX_EXE:
1127 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1129 case BINARY_UNIX_LIB:
1133 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1134 CloseHandle( main_exe_file );
1136 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1137 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1139 static const WCHAR soW[] = {'.','s','o',0};
1140 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1143 /* update the unicode string */
1144 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1146 HeapFree( GetProcessHeap(), 0, unix_name );
1149 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1155 /* build command line */
1156 set_library_wargv( __wine_main_argv );
1157 if (!build_command_line( __wine_main_wargv )) goto error;
1159 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1161 /* allocate main thread stack */
1162 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1164 /* switch to the new stack */
1165 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1168 ExitProcess( GetLastError() );
1172 /***********************************************************************
1175 * Build an argv array from a command-line.
1176 * 'reserved' is the number of args to reserve before the first one.
1178 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1182 char *arg,*s,*d,*cmdline;
1183 int in_quotes,bcount,len;
1185 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1186 if (!(cmdline = malloc(len))) return NULL;
1187 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1194 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1197 /* skip the remaining spaces */
1198 while (*s==' ' || *s=='\t') {
1205 } else if (*s=='\\') {
1206 /* '\', count them */
1208 } else if ((*s=='"') && ((bcount & 1)==0)) {
1210 in_quotes=!in_quotes;
1213 /* a regular character */
1218 argv=malloc(argc*sizeof(*argv));
1227 if ((*s==' ' || *s=='\t') && !in_quotes) {
1228 /* Close the argument and copy it */
1232 /* skip the remaining spaces */
1235 } while (*s==' ' || *s=='\t');
1237 /* Start with a new argument */
1240 } else if (*s=='\\') {
1244 } else if (*s=='"') {
1246 if ((bcount & 1)==0) {
1247 /* Preceeded by an even number of '\', this is half that
1248 * number of '\', plus a '"' which we discard.
1252 in_quotes=!in_quotes;
1254 /* Preceeded by an odd number of '\', this is half that
1255 * number of '\' followed by a '"'
1263 /* a regular character */
1278 /***********************************************************************
1281 * Allocate an environment string; helper for build_envp
1283 static char *alloc_env_string( const char *name, const char *value )
1285 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1286 strcpy( ret, name );
1287 strcat( ret, value );
1291 /***********************************************************************
1294 * Build the environment of a new child process.
1296 static char **build_envp( const WCHAR *envW )
1301 int count = 0, length;
1303 for (end = envW; *end; count++) end += strlenW(end) + 1;
1305 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1306 if (!(env = malloc( length ))) return NULL;
1307 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1311 if ((envp = malloc( count * sizeof(*envp) )))
1313 char **envptr = envp;
1315 /* some variables must not be modified, so we get them directly from the unix env */
1316 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1317 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1318 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1319 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1320 /* now put the Windows environment strings */
1321 for (p = env; *p; p += strlen(p) + 1)
1323 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1324 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1325 if (is_special_env_var( p )) /* prefix it with "WINE" */
1326 *envptr++ = alloc_env_string( "WINE", p );
1336 /***********************************************************************
1339 * Fork and exec a new Unix binary, checking for errors.
1341 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1342 const WCHAR *env, const char *newdir )
1347 if (!env) env = GetEnvironmentStringsW();
1351 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1354 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1355 if (!(pid = fork())) /* child */
1357 char **argv = build_argv( cmdline, 0 );
1358 char **envp = build_envp( env );
1361 /* Reset signals that we previously set to SIG_IGN */
1362 signal( SIGPIPE, SIG_DFL );
1363 signal( SIGCHLD, SIG_DFL );
1365 if (newdir) chdir(newdir);
1367 if (argv && envp) execve( filename, argv, envp );
1369 write( fd[1], &err, sizeof(err) );
1373 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1378 if (pid == -1) FILE_SetDosError();
1384 /***********************************************************************
1385 * create_user_params
1387 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1388 LPCWSTR cur_dir, LPWSTR env,
1389 const STARTUPINFOW *startup )
1391 RTL_USER_PROCESS_PARAMETERS *params;
1392 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1394 WCHAR buffer[MAX_PATH];
1396 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1397 lstrcpynW( buffer, filename, MAX_PATH );
1398 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1399 lstrcpynW( buffer, filename, MAX_PATH );
1400 RtlInitUnicodeString( &image_str, buffer );
1402 RtlInitUnicodeString( &cmdline_str, cmdline );
1403 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1404 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1405 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1406 if (startup->lpReserved2 && startup->cbReserved2)
1408 runtime.Length = runtime.MaximumLength = startup->cbReserved2;
1409 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1412 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1413 cur_dir ? &curdir_str : NULL,
1415 startup->lpTitle ? &title : NULL,
1416 startup->lpDesktop ? &desktop : NULL,
1418 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1419 if (status != STATUS_SUCCESS)
1421 SetLastError( RtlNtStatusToDosError(status) );
1425 params->hStdInput = startup->hStdInput;
1426 params->hStdOutput = startup->hStdOutput;
1427 params->hStdError = startup->hStdError;
1428 params->dwX = startup->dwX;
1429 params->dwY = startup->dwY;
1430 params->dwXSize = startup->dwXSize;
1431 params->dwYSize = startup->dwYSize;
1432 params->dwXCountChars = startup->dwXCountChars;
1433 params->dwYCountChars = startup->dwYCountChars;
1434 params->dwFillAttribute = startup->dwFillAttribute;
1435 params->dwFlags = startup->dwFlags;
1436 params->wShowWindow = startup->wShowWindow;
1441 /***********************************************************************
1444 * Create a new process. If hFile is a valid handle we have an exe
1445 * file, otherwise it is a Winelib app.
1447 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1448 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1449 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1450 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1451 void *res_start, void *res_end )
1453 BOOL ret, success = FALSE;
1454 HANDLE process_info;
1456 RTL_USER_PROCESS_PARAMETERS *params;
1462 char preloader_reserve[64];
1464 if (!env) RtlAcquirePebLock();
1466 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, startup )))
1468 if (!env) RtlReleasePebLock();
1471 env_end = params->Environment;
1472 while (*env_end) env_end += strlenW(env_end) + 1;
1475 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1476 (unsigned long)res_start, (unsigned long)res_end, 0 );
1478 /* create the synchronization pipes */
1480 if (pipe( startfd ) == -1)
1482 if (!env) RtlReleasePebLock();
1483 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1484 RtlDestroyProcessParameters( params );
1487 if (pipe( execfd ) == -1)
1489 if (!env) RtlReleasePebLock();
1490 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1491 close( startfd[0] );
1492 close( startfd[1] );
1493 RtlDestroyProcessParameters( params );
1496 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1498 /* create the child process */
1500 if (!(pid = fork())) /* child */
1502 char **argv = build_argv( cmd_line, 1 );
1504 close( startfd[1] );
1507 /* wait for parent to tell us to start */
1508 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1510 close( startfd[0] );
1511 /* Reset signals that we previously set to SIG_IGN */
1512 signal( SIGPIPE, SIG_DFL );
1513 signal( SIGCHLD, SIG_DFL );
1515 putenv( preloader_reserve );
1516 if (unixdir) chdir(unixdir);
1520 /* first, try for a WINELOADER environment variable */
1521 const char *loader = getenv("WINELOADER");
1522 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1523 /* now use the standard search strategy */
1524 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1527 write( execfd[1], &err, sizeof(err) );
1531 /* this is the parent */
1533 close( startfd[0] );
1537 if (!env) RtlReleasePebLock();
1538 close( startfd[1] );
1541 RtlDestroyProcessParameters( params );
1545 /* create the process on the server side */
1547 SERVER_START_REQ( new_process )
1549 req->inherit_all = inherit;
1550 req->create_flags = flags;
1551 req->unix_pid = pid;
1552 req->exe_file = hFile;
1553 if (startup->dwFlags & STARTF_USESTDHANDLES)
1555 req->hstdin = startup->hStdInput;
1556 req->hstdout = startup->hStdOutput;
1557 req->hstderr = startup->hStdError;
1561 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1562 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1563 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1566 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1568 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1569 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1570 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1571 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1575 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1576 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1577 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1580 wine_server_add_data( req, params, params->Size );
1581 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1582 ret = !wine_server_call_err( req );
1583 process_info = reply->info;
1587 if (!env) RtlReleasePebLock();
1588 RtlDestroyProcessParameters( params );
1591 close( startfd[1] );
1596 /* tell child to start and wait for it to exec */
1598 write( startfd[1], &dummy, 1 );
1599 close( startfd[1] );
1601 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1606 CloseHandle( process_info );
1611 /* wait for the new process info to be ready */
1613 WaitForSingleObject( process_info, INFINITE );
1614 SERVER_START_REQ( get_new_process_info )
1616 req->info = process_info;
1617 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1618 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1619 if ((ret = !wine_server_call_err( req )))
1621 info->dwProcessId = (DWORD)reply->pid;
1622 info->dwThreadId = (DWORD)reply->tid;
1623 info->hProcess = reply->phandle;
1624 info->hThread = reply->thandle;
1625 success = reply->success;
1630 if (ret && !success) /* new process failed to start */
1633 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1634 CloseHandle( info->hThread );
1635 CloseHandle( info->hProcess );
1638 CloseHandle( process_info );
1643 /***********************************************************************
1644 * create_vdm_process
1646 * Create a new VDM process for a 16-bit or DOS application.
1648 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1649 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1650 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1651 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1653 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1656 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1657 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1661 SetLastError( ERROR_OUTOFMEMORY );
1664 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1665 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1666 flags, startup, info, unixdir, NULL, NULL );
1667 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1672 /***********************************************************************
1673 * create_cmd_process
1675 * Create a new cmd shell process for a .BAT file.
1677 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1678 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1679 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1680 LPPROCESS_INFORMATION info )
1683 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1684 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1685 WCHAR comspec[MAX_PATH];
1689 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1691 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1692 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1695 strcpyW( newcmdline, comspec );
1696 strcatW( newcmdline, slashcW );
1697 strcatW( newcmdline, cmd_line );
1698 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1699 flags, env, cur_dir, startup, info );
1700 HeapFree( GetProcessHeap(), 0, newcmdline );
1705 /*************************************************************************
1708 * Helper for CreateProcess: retrieve the file name to load from the
1709 * app name and command line. Store the file name in buffer, and
1710 * return a possibly modified command line.
1711 * Also returns a handle to the opened file if it's a Windows binary.
1713 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1714 int buflen, HANDLE *handle )
1716 static const WCHAR quotesW[] = {'"','%','s','"',0};
1718 WCHAR *name, *pos, *ret = NULL;
1721 /* if we have an app name, everything is easy */
1725 /* use the unmodified app name as file name */
1726 lstrcpynW( buffer, appname, buflen );
1727 *handle = open_exe_file( buffer );
1728 if (!(ret = cmdline) || !cmdline[0])
1730 /* no command-line, create one */
1731 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1732 sprintfW( ret, quotesW, appname );
1739 SetLastError( ERROR_INVALID_PARAMETER );
1743 /* first check for a quoted file name */
1745 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1747 int len = p - cmdline - 1;
1748 /* extract the quoted portion as file name */
1749 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1750 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1753 if (find_exe_file( name, buffer, buflen, handle ))
1754 ret = cmdline; /* no change necessary */
1758 /* now try the command-line word by word */
1760 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1767 do *pos++ = *p++; while (*p && *p != ' ');
1769 if (find_exe_file( name, buffer, buflen, handle ))
1776 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1778 /* now build a new command-line with quotes */
1780 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1782 sprintfW( ret, quotesW, name );
1786 HeapFree( GetProcessHeap(), 0, name );
1791 /**********************************************************************
1792 * CreateProcessA (KERNEL32.@)
1794 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1795 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1796 DWORD flags, LPVOID env, LPCSTR cur_dir,
1797 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1800 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1801 UNICODE_STRING desktopW, titleW;
1804 desktopW.Buffer = NULL;
1805 titleW.Buffer = NULL;
1806 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1807 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1808 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1810 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1811 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1813 memcpy( &infoW, startup_info, sizeof(infoW) );
1814 infoW.lpDesktop = desktopW.Buffer;
1815 infoW.lpTitle = titleW.Buffer;
1817 if (startup_info->lpReserved)
1818 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1819 debugstr_a(startup_info->lpReserved));
1821 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1822 inherit, flags, env, cur_dirW, &infoW, info );
1824 if (app_nameW) HeapFree( GetProcessHeap(), 0, app_nameW );
1825 if (cmd_lineW) HeapFree( GetProcessHeap(), 0, cmd_lineW );
1826 if (cur_dirW) HeapFree( GetProcessHeap(), 0, cur_dirW );
1827 RtlFreeUnicodeString( &desktopW );
1828 RtlFreeUnicodeString( &titleW );
1833 /**********************************************************************
1834 * CreateProcessW (KERNEL32.@)
1836 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1837 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1838 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1839 LPPROCESS_INFORMATION info )
1843 char *unixdir = NULL;
1844 WCHAR name[MAX_PATH];
1845 WCHAR *tidy_cmdline, *p, *envW = env;
1846 void *res_start, *res_end;
1848 /* Process the AppName and/or CmdLine to get module name and path */
1850 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1852 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1854 if (hFile == INVALID_HANDLE_VALUE) goto done;
1856 /* Warn if unsupported features are used */
1858 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1859 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1860 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1861 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1862 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1866 unixdir = wine_get_unix_file_name( cur_dir );
1870 WCHAR buf[MAX_PATH];
1871 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1874 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1879 while (*p) p += strlen(p) + 1;
1880 p++; /* final null */
1881 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1882 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1883 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1884 flags |= CREATE_UNICODE_ENVIRONMENT;
1887 info->hThread = info->hProcess = 0;
1888 info->dwProcessId = info->dwThreadId = 0;
1890 /* Determine executable type */
1892 if (!hFile) /* builtin exe */
1894 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1895 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1896 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1900 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1903 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1904 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1905 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1910 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1911 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1912 inherit, flags, startup_info, info, unixdir );
1915 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1916 SetLastError( ERROR_BAD_EXE_FORMAT );
1918 case BINARY_UNIX_LIB:
1919 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1920 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1921 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1923 case BINARY_UNKNOWN:
1924 /* check for .com or .bat extension */
1925 if ((p = strrchrW( name, '.' )))
1927 if (!strcmpiW( p, comW ))
1929 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1930 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1931 inherit, flags, startup_info, info, unixdir );
1934 if (!strcmpiW( p, batW ))
1936 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1937 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1938 inherit, flags, startup_info, info );
1943 case BINARY_UNIX_EXE:
1945 /* unknown file, try as unix executable */
1948 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1950 if ((unix_name = wine_get_unix_file_name( name )))
1952 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1953 HeapFree( GetProcessHeap(), 0, unix_name );
1958 CloseHandle( hFile );
1961 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1962 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1963 if (unixdir) HeapFree( GetProcessHeap(), 0, unixdir );
1968 /***********************************************************************
1971 * Wrapper to call WaitForInputIdle USER function
1973 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1975 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1977 HMODULE mod = GetModuleHandleA( "user32.dll" );
1980 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1981 if (ptr) return ptr( process, timeout );
1987 /***********************************************************************
1988 * WinExec (KERNEL32.@)
1990 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1992 PROCESS_INFORMATION info;
1993 STARTUPINFOA startup;
1997 memset( &startup, 0, sizeof(startup) );
1998 startup.cb = sizeof(startup);
1999 startup.dwFlags = STARTF_USESHOWWINDOW;
2000 startup.wShowWindow = nCmdShow;
2002 /* cmdline needs to be writeable for CreateProcess */
2003 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2004 strcpy( cmdline, lpCmdLine );
2006 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2007 0, NULL, NULL, &startup, &info ))
2009 /* Give 30 seconds to the app to come up */
2010 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2011 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2013 /* Close off the handles */
2014 CloseHandle( info.hThread );
2015 CloseHandle( info.hProcess );
2017 else if ((ret = GetLastError()) >= 32)
2019 FIXME("Strange error set by CreateProcess: %d\n", ret );
2022 HeapFree( GetProcessHeap(), 0, cmdline );
2027 /**********************************************************************
2028 * LoadModule (KERNEL32.@)
2030 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2032 LOADPARMS32 *params = paramBlock;
2033 PROCESS_INFORMATION info;
2034 STARTUPINFOA startup;
2035 HINSTANCE hInstance;
2037 char filename[MAX_PATH];
2040 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2042 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2043 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2044 return (HINSTANCE)GetLastError();
2046 len = (BYTE)params->lpCmdLine[0];
2047 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2048 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2050 strcpy( cmdline, filename );
2051 p = cmdline + strlen(cmdline);
2053 memcpy( p, params->lpCmdLine + 1, len );
2056 memset( &startup, 0, sizeof(startup) );
2057 startup.cb = sizeof(startup);
2058 if (params->lpCmdShow)
2060 startup.dwFlags = STARTF_USESHOWWINDOW;
2061 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2064 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2065 params->lpEnvAddress, NULL, &startup, &info ))
2067 /* Give 30 seconds to the app to come up */
2068 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2069 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2070 hInstance = (HINSTANCE)33;
2071 /* Close off the handles */
2072 CloseHandle( info.hThread );
2073 CloseHandle( info.hProcess );
2075 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2077 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2078 hInstance = (HINSTANCE)11;
2081 HeapFree( GetProcessHeap(), 0, cmdline );
2086 /******************************************************************************
2087 * TerminateProcess (KERNEL32.@)
2089 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2091 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2092 if (status) SetLastError( RtlNtStatusToDosError(status) );
2097 /***********************************************************************
2098 * ExitProcess (KERNEL32.@)
2100 void WINAPI ExitProcess( DWORD status )
2102 LdrShutdownProcess();
2103 SERVER_START_REQ( terminate_process )
2105 /* send the exit code to the server */
2106 req->handle = GetCurrentProcess();
2107 req->exit_code = status;
2108 wine_server_call( req );
2115 /***********************************************************************
2116 * GetExitCodeProcess [KERNEL32.@]
2118 * Gets termination status of specified process
2124 BOOL WINAPI GetExitCodeProcess(
2125 HANDLE hProcess, /* [in] handle to the process */
2126 LPDWORD lpExitCode) /* [out] address to receive termination status */
2129 PROCESS_BASIC_INFORMATION pbi;
2131 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2133 if (status == STATUS_SUCCESS)
2135 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2138 SetLastError( RtlNtStatusToDosError(status) );
2143 /***********************************************************************
2144 * SetErrorMode (KERNEL32.@)
2146 UINT WINAPI SetErrorMode( UINT mode )
2148 UINT old = process_error_mode;
2149 process_error_mode = mode;
2154 /**********************************************************************
2155 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2157 * Allocates a thread local storage index
2160 * Success: TLS Index
2161 * Failure: 0xFFFFFFFF
2163 DWORD WINAPI TlsAlloc( void )
2167 RtlAcquirePebLock();
2168 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
2169 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2170 else SetLastError( ERROR_NO_MORE_ITEMS );
2171 RtlReleasePebLock();
2176 /**********************************************************************
2177 * TlsFree [KERNEL32.@] Releases a TLS index.
2179 * Releases a thread local storage index, making it available for reuse
2185 BOOL WINAPI TlsFree(
2186 DWORD index) /* [in] TLS Index to free */
2190 RtlAcquirePebLock();
2191 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2194 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2195 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2197 else SetLastError( ERROR_INVALID_PARAMETER );
2198 RtlReleasePebLock();
2203 /**********************************************************************
2204 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2207 * Success: Value stored in calling thread's TLS slot for index
2208 * Failure: 0 and GetLastError returns NO_ERROR
2210 LPVOID WINAPI TlsGetValue(
2211 DWORD index) /* [in] TLS index to retrieve value for */
2213 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2215 SetLastError( ERROR_INVALID_PARAMETER );
2218 SetLastError( ERROR_SUCCESS );
2219 return NtCurrentTeb()->TlsSlots[index];
2223 /**********************************************************************
2224 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2230 BOOL WINAPI TlsSetValue(
2231 DWORD index, /* [in] TLS index to set value for */
2232 LPVOID value) /* [in] Value to be stored */
2234 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2236 SetLastError( ERROR_INVALID_PARAMETER );
2239 NtCurrentTeb()->TlsSlots[index] = value;
2244 /***********************************************************************
2245 * GetProcessFlags (KERNEL32.@)
2247 DWORD WINAPI GetProcessFlags( DWORD processid )
2249 IMAGE_NT_HEADERS *nt;
2252 if (processid && processid != GetCurrentProcessId()) return 0;
2254 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2256 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2257 flags |= PDB32_CONSOLE_PROC;
2259 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2260 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2265 /***********************************************************************
2266 * GetProcessDword (KERNEL.485)
2267 * GetProcessDword (KERNEL32.18)
2268 * 'Of course you cannot directly access Windows internal structures'
2270 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2275 TRACE("(%ld, %d)\n", dwProcessID, offset );
2277 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2279 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2285 case GPD_APP_COMPAT_FLAGS:
2286 return GetAppCompatFlags16(0);
2287 case GPD_LOAD_DONE_EVENT:
2289 case GPD_HINSTANCE16:
2290 return GetTaskDS16();
2291 case GPD_WINDOWS_VERSION:
2292 return GetExeVersion16();
2294 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2296 return (DWORD)NtCurrentTeb()->Peb;
2297 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2298 GetStartupInfoW(&siw);
2299 return (DWORD)siw.hStdOutput;
2300 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2301 GetStartupInfoW(&siw);
2302 return (DWORD)siw.hStdInput;
2303 case GPD_STARTF_SHOWWINDOW:
2304 GetStartupInfoW(&siw);
2305 return siw.wShowWindow;
2306 case GPD_STARTF_SIZE:
2307 GetStartupInfoW(&siw);
2309 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2311 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2312 return MAKELONG( x, y );
2313 case GPD_STARTF_POSITION:
2314 GetStartupInfoW(&siw);
2316 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2318 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2319 return MAKELONG( x, y );
2320 case GPD_STARTF_FLAGS:
2321 GetStartupInfoW(&siw);
2326 return GetProcessFlags(0);
2328 return process_dword;
2330 ERR("Unknown offset %d\n", offset );
2335 /***********************************************************************
2336 * SetProcessDword (KERNEL.484)
2337 * 'Of course you cannot directly access Windows internal structures'
2339 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2341 TRACE("(%ld, %d)\n", dwProcessID, offset );
2343 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2345 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2351 case GPD_APP_COMPAT_FLAGS:
2352 case GPD_LOAD_DONE_EVENT:
2353 case GPD_HINSTANCE16:
2354 case GPD_WINDOWS_VERSION:
2357 case GPD_STARTF_SHELLDATA:
2358 case GPD_STARTF_HOTKEY:
2359 case GPD_STARTF_SHOWWINDOW:
2360 case GPD_STARTF_SIZE:
2361 case GPD_STARTF_POSITION:
2362 case GPD_STARTF_FLAGS:
2365 ERR("Not allowed to modify offset %d\n", offset );
2368 process_dword = value;
2371 ERR("Unknown offset %d\n", offset );
2377 /***********************************************************************
2378 * ExitProcess (KERNEL.466)
2380 void WINAPI ExitProcess16( WORD status )
2383 ReleaseThunkLock( &count );
2384 ExitProcess( status );
2388 /*********************************************************************
2389 * OpenProcess (KERNEL32.@)
2391 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2394 SERVER_START_REQ( open_process )
2397 req->access = access;
2398 req->inherit = inherit;
2399 if (!wine_server_call_err( req )) ret = reply->handle;
2406 /*********************************************************************
2407 * MapProcessHandle (KERNEL.483)
2408 * GetProcessId (KERNEL32.@)
2410 DWORD WINAPI GetProcessId( HANDLE hProcess )
2413 PROCESS_BASIC_INFORMATION pbi;
2415 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2417 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2418 SetLastError( RtlNtStatusToDosError(status) );
2423 /*********************************************************************
2424 * CloseW32Handle (KERNEL.474)
2425 * CloseHandle (KERNEL32.@)
2427 BOOL WINAPI CloseHandle( HANDLE handle )
2431 /* stdio handles need special treatment */
2432 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2433 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2434 (handle == (HANDLE)STD_ERROR_HANDLE))
2435 handle = GetStdHandle( (DWORD)handle );
2437 if (is_console_handle(handle))
2438 return CloseConsoleHandle(handle);
2440 status = NtClose( handle );
2441 if (status) SetLastError( RtlNtStatusToDosError(status) );
2446 /*********************************************************************
2447 * GetHandleInformation (KERNEL32.@)
2449 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2452 SERVER_START_REQ( set_handle_info )
2454 req->handle = handle;
2458 ret = !wine_server_call_err( req );
2459 if (ret && flags) *flags = reply->old_flags;
2466 /*********************************************************************
2467 * SetHandleInformation (KERNEL32.@)
2469 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2472 SERVER_START_REQ( set_handle_info )
2474 req->handle = handle;
2478 ret = !wine_server_call_err( req );
2485 /*********************************************************************
2486 * DuplicateHandle (KERNEL32.@)
2488 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2489 HANDLE dest_process, HANDLE *dest,
2490 DWORD access, BOOL inherit, DWORD options )
2494 if (is_console_handle(source))
2496 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2497 if (source_process != dest_process ||
2498 source_process != GetCurrentProcess())
2500 SetLastError(ERROR_INVALID_PARAMETER);
2503 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2504 return (*dest != INVALID_HANDLE_VALUE);
2506 status = NtDuplicateObject( source_process, source, dest_process, dest,
2507 access, inherit ? OBJ_INHERIT : 0, options );
2508 if (status) SetLastError( RtlNtStatusToDosError(status) );
2513 /***********************************************************************
2514 * ConvertToGlobalHandle (KERNEL.476)
2515 * ConvertToGlobalHandle (KERNEL32.@)
2517 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2519 HANDLE ret = INVALID_HANDLE_VALUE;
2520 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2521 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2526 /***********************************************************************
2527 * SetHandleContext (KERNEL32.@)
2529 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2531 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2532 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2533 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2538 /***********************************************************************
2539 * GetHandleContext (KERNEL32.@)
2541 DWORD WINAPI GetHandleContext(HANDLE hnd)
2543 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2544 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2545 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2550 /***********************************************************************
2551 * CreateSocketHandle (KERNEL32.@)
2553 HANDLE WINAPI CreateSocketHandle(void)
2555 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2556 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2557 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2558 return INVALID_HANDLE_VALUE;
2562 /***********************************************************************
2563 * SetPriorityClass (KERNEL32.@)
2565 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2568 SERVER_START_REQ( set_process_info )
2570 req->handle = hprocess;
2571 req->priority = priorityclass;
2572 req->mask = SET_PROCESS_INFO_PRIORITY;
2573 ret = !wine_server_call_err( req );
2580 /***********************************************************************
2581 * GetPriorityClass (KERNEL32.@)
2583 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2586 PROCESS_BASIC_INFORMATION pbi;
2588 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2590 if (status == STATUS_SUCCESS) return pbi.BasePriority;
2591 SetLastError( RtlNtStatusToDosError(status) );
2596 /***********************************************************************
2597 * SetProcessAffinityMask (KERNEL32.@)
2599 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2602 SERVER_START_REQ( set_process_info )
2604 req->handle = hProcess;
2605 req->affinity = affmask;
2606 req->mask = SET_PROCESS_INFO_AFFINITY;
2607 ret = !wine_server_call_err( req );
2614 /**********************************************************************
2615 * GetProcessAffinityMask (KERNEL32.@)
2617 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2618 LPDWORD lpProcessAffinityMask,
2619 LPDWORD lpSystemAffinityMask )
2622 SERVER_START_REQ( get_process_info )
2624 req->handle = hProcess;
2625 if (!wine_server_call_err( req ))
2627 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2628 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2637 /***********************************************************************
2638 * GetProcessVersion (KERNEL32.@)
2640 DWORD WINAPI GetProcessVersion( DWORD processid )
2642 IMAGE_NT_HEADERS *nt;
2644 if (processid && processid != GetCurrentProcessId())
2646 FIXME("should use ReadProcessMemory\n");
2649 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2650 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2651 nt->OptionalHeader.MinorSubsystemVersion);
2656 /***********************************************************************
2657 * SetProcessWorkingSetSize [KERNEL32.@]
2658 * Sets the min/max working set sizes for a specified process.
2661 * hProcess [I] Handle to the process of interest
2662 * minset [I] Specifies minimum working set size
2663 * maxset [I] Specifies maximum working set size
2667 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2670 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2671 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2672 /* Trim the working set to zero */
2673 /* Swap the process out of physical RAM */
2678 /***********************************************************************
2679 * GetProcessWorkingSetSize (KERNEL32.@)
2681 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2684 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2685 /* 32 MB working set size */
2686 if (minset) *minset = 32*1024*1024;
2687 if (maxset) *maxset = 32*1024*1024;
2692 /***********************************************************************
2693 * SetProcessShutdownParameters (KERNEL32.@)
2695 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2697 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2698 shutdown_flags = flags;
2699 shutdown_priority = level;
2704 /***********************************************************************
2705 * GetProcessShutdownParameters (KERNEL32.@)
2708 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2710 *lpdwLevel = shutdown_priority;
2711 *lpdwFlags = shutdown_flags;
2716 /***********************************************************************
2717 * GetProcessPriorityBoost (KERNEL32.@)
2719 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2721 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2723 /* Report that no boost is present.. */
2724 *pDisablePriorityBoost = FALSE;
2729 /***********************************************************************
2730 * SetProcessPriorityBoost (KERNEL32.@)
2732 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2734 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2735 /* Say we can do it. I doubt the program will notice that we don't. */
2740 /***********************************************************************
2741 * ReadProcessMemory (KERNEL32.@)
2743 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2744 SIZE_T *bytes_read )
2746 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2747 if (status) SetLastError( RtlNtStatusToDosError(status) );
2752 /***********************************************************************
2753 * WriteProcessMemory (KERNEL32.@)
2755 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2756 SIZE_T *bytes_written )
2758 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2759 if (status) SetLastError( RtlNtStatusToDosError(status) );
2764 /****************************************************************************
2765 * FlushInstructionCache (KERNEL32.@)
2767 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2770 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2771 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2772 if (status) SetLastError( RtlNtStatusToDosError(status) );
2777 /******************************************************************
2778 * GetProcessIoCounters (KERNEL32.@)
2780 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2784 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2785 ioc, sizeof(*ioc), NULL);
2786 if (status) SetLastError( RtlNtStatusToDosError(status) );
2790 /***********************************************************************
2791 * ProcessIdToSessionId (KERNEL32.@)
2792 * This function is available on Terminal Server 4SP4 and Windows 2000
2794 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2796 /* According to MSDN, if the calling process is not in a terminal
2797 * services environment, then the sessionid returned is zero.
2804 /***********************************************************************
2805 * RegisterServiceProcess (KERNEL.491)
2806 * RegisterServiceProcess (KERNEL32.@)
2808 * A service process calls this function to ensure that it continues to run
2809 * even after a user logged off.
2811 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2813 /* I don't think that Wine needs to do anything in that function */
2814 return 1; /* success */
2818 /***********************************************************************
2819 * GetSystemMSecCount (SYSTEM.6)
2820 * GetTickCount (KERNEL32.@)
2822 * Returns the number of milliseconds, modulo 2^32, since the start
2823 * of the wineserver.
2825 DWORD WINAPI GetTickCount(void)
2828 gettimeofday( &t, NULL );
2829 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2833 /***********************************************************************
2834 * GetCurrentProcess (KERNEL32.@)
2836 #undef GetCurrentProcess
2837 HANDLE WINAPI GetCurrentProcess(void)
2839 return (HANDLE)0xffffffff;