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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
30 #ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
39 #ifdef HAVE_SYS_PRCTL_H
40 # include <sys/prctl.h>
42 #include <sys/types.h>
45 #define WIN32_NO_STATUS
46 #include "wine/winbase16.h"
47 #include "wine/winuser16.h"
49 #include "kernel_private.h"
50 #include "wine/exception.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(process);
56 WINE_DECLARE_DEBUG_CHANNEL(file);
57 WINE_DECLARE_DEBUG_CHANNEL(relay);
60 extern char **__wine_get_main_environment(void);
62 extern char **__wine_main_environ;
63 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
74 static UINT process_error_mode;
76 static DWORD shutdown_flags = 0;
77 static DWORD shutdown_priority = 0x280;
78 static DWORD process_dword;
80 HMODULE kernel32_handle = 0;
82 const WCHAR *DIR_Windows = NULL;
83 const WCHAR *DIR_System = NULL;
86 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
87 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
88 #define PDB32_DOS_PROC 0x0010 /* Dos process */
89 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
90 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
91 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
93 static const WCHAR comW[] = {'.','c','o','m',0};
94 static const WCHAR batW[] = {'.','b','a','t',0};
95 static const WCHAR cmdW[] = {'.','c','m','d',0};
96 static const WCHAR pifW[] = {'.','p','i','f',0};
97 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
99 static void exec_process( LPCWSTR name );
101 extern void SHELL_LoadRegistry(void);
104 /***********************************************************************
107 static inline int contains_path( LPCWSTR name )
109 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
113 /***********************************************************************
116 * Check if an environment variable needs to be handled specially when
117 * passed through the Unix environment (i.e. prefixed with "WINE").
119 static inline int is_special_env_var( const char *var )
121 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
122 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
123 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
124 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
128 /***************************************************************************
131 * Get the path of a builtin module when the native file does not exist.
133 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
136 UINT len = strlenW( DIR_System );
138 if (contains_path( libname ))
140 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
141 filename, &file_part ) > size * sizeof(WCHAR))
142 return FALSE; /* too long */
144 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
146 while (filename[len] == '\\') len++;
147 if (filename + len != file_part) return FALSE;
151 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
152 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
153 file_part = filename + len;
154 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
155 strcpyW( file_part, libname );
157 if (ext && !strchrW( file_part, '.' ))
159 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
160 return FALSE; /* too long */
161 strcatW( file_part, ext );
167 /***********************************************************************
168 * open_builtin_exe_file
170 * Open an exe file for a builtin exe.
172 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
173 int test_only, int *file_exists )
175 char exename[MAX_PATH];
180 if ((p = strrchrW( name, '/' ))) name = p + 1;
181 if ((p = strrchrW( name, '\\' ))) name = p + 1;
183 /* we don't want to depend on the current codepage here */
184 len = strlenW( name ) + 1;
185 if (len >= sizeof(exename)) return NULL;
186 for (i = 0; i < len; i++)
188 if (name[i] > 127) return NULL;
189 exename[i] = (char)name[i];
190 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
192 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
196 /***********************************************************************
199 * Open a specific exe file, taking load order into account.
200 * Returns the file handle or 0 for a builtin exe.
202 static HANDLE open_exe_file( const WCHAR *name )
206 TRACE("looking for %s\n", debugstr_w(name) );
208 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
209 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
211 WCHAR buffer[MAX_PATH];
212 /* file doesn't exist, check for builtin */
213 if (!contains_path( name )) goto error;
214 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
220 SetLastError( ERROR_FILE_NOT_FOUND );
221 return INVALID_HANDLE_VALUE;
225 /***********************************************************************
228 * Open an exe file, and return the full name and file handle.
229 * Returns FALSE if file could not be found.
230 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
231 * If file is a builtin exe, returns TRUE and sets handle to 0.
233 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
235 static const WCHAR exeW[] = {'.','e','x','e',0};
238 TRACE("looking for %s\n", debugstr_w(name) );
240 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
241 !get_builtin_path( name, exeW, buffer, buflen ))
243 /* no builtin found, try native without extension in case it is a Unix app */
245 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
247 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
248 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
249 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
255 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
256 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
257 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
260 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
261 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
272 /***********************************************************************
273 * build_initial_environment
275 * Build the Win32 environment from the Unix environment
277 static BOOL build_initial_environment(void)
283 char **env = __wine_get_main_environment();
285 /* Compute the total size of the Unix environment */
286 for (e = env; *e; e++)
288 if (is_special_env_var( *e )) continue;
289 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
291 size *= sizeof(WCHAR);
293 /* Now allocate the environment */
295 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
296 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
299 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
300 endptr = p + size / sizeof(WCHAR);
302 /* And fill it with the Unix environment */
303 for (e = env; *e; e++)
307 /* skip Unix special variables and use the Wine variants instead */
308 if (!strncmp( str, "WINE", 4 ))
310 if (is_special_env_var( str + 4 )) str += 4;
311 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
313 else if (is_special_env_var( str )) continue; /* skip it */
315 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
323 /***********************************************************************
324 * set_registry_variables
326 * Set environment variables by enumerating the values of a key;
327 * helper for set_registry_environment().
328 * Note that Windows happily truncates the value if it's too big.
330 static void set_registry_variables( HANDLE hkey, ULONG type )
332 UNICODE_STRING env_name, env_value;
336 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
337 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
339 for (index = 0; ; index++)
341 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
342 buffer, sizeof(buffer), &size );
343 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
345 if (info->Type != type)
347 env_name.Buffer = info->Name;
348 env_name.Length = env_name.MaximumLength = info->NameLength;
349 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
350 env_value.Length = env_value.MaximumLength = info->DataLength;
351 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
352 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
353 if (info->Type == REG_EXPAND_SZ)
355 WCHAR buf_expanded[1024];
356 UNICODE_STRING env_expanded;
357 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
358 env_expanded.Buffer=buf_expanded;
359 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
360 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
361 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
365 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
371 /***********************************************************************
372 * set_registry_environment
374 * Set the environment variables specified in the registry.
376 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
377 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
378 * on the order in which the variables are processed. But on Windows it
379 * does not really matter since they only use %SystemDrive% and
380 * %SystemRoot% which are predefined. But Wine defines these in the
381 * registry, so we need two passes.
383 static BOOL set_registry_environment(void)
385 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
386 'S','y','s','t','e','m','\\',
387 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
388 'C','o','n','t','r','o','l','\\',
389 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
390 'E','n','v','i','r','o','n','m','e','n','t',0};
391 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
393 OBJECT_ATTRIBUTES attr;
394 UNICODE_STRING nameW;
398 attr.Length = sizeof(attr);
399 attr.RootDirectory = 0;
400 attr.ObjectName = &nameW;
402 attr.SecurityDescriptor = NULL;
403 attr.SecurityQualityOfService = NULL;
405 /* first the system environment variables */
406 RtlInitUnicodeString( &nameW, env_keyW );
407 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
409 set_registry_variables( hkey, REG_SZ );
410 set_registry_variables( hkey, REG_EXPAND_SZ );
415 /* then the ones for the current user */
416 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
417 RtlInitUnicodeString( &nameW, envW );
418 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
420 set_registry_variables( hkey, REG_SZ );
421 set_registry_variables( hkey, REG_EXPAND_SZ );
424 NtClose( attr.RootDirectory );
429 /***********************************************************************
432 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
434 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
435 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
436 DWORD len, size = sizeof(buffer);
438 UNICODE_STRING nameW;
440 RtlInitUnicodeString( &nameW, name );
441 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
444 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
445 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
447 if (info->Type == REG_EXPAND_SZ)
449 UNICODE_STRING value, expanded;
451 value.MaximumLength = len * sizeof(WCHAR);
452 value.Buffer = (WCHAR *)info->Data;
453 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
454 value.Length = len * sizeof(WCHAR);
455 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
456 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
457 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
458 else RtlFreeUnicodeString( &expanded );
460 else if (info->Type == REG_SZ)
462 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
464 memcpy( ret, info->Data, len * sizeof(WCHAR) );
472 /***********************************************************************
473 * set_additional_environment
475 * Set some additional environment variables not specified in the registry.
477 static void set_additional_environment(void)
479 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
480 'S','o','f','t','w','a','r','e','\\',
481 'M','i','c','r','o','s','o','f','t','\\',
482 'W','i','n','d','o','w','s',' ','N','T','\\',
483 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
484 'P','r','o','f','i','l','e','L','i','s','t',0};
485 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
486 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
487 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
488 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
489 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
490 OBJECT_ATTRIBUTES attr;
491 UNICODE_STRING nameW;
492 WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
494 const char *name = wine_get_user_name();
497 /* set the USERNAME variable */
499 len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
502 user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
503 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
504 SetEnvironmentVariableW( usernameW, user_name );
506 else WARN( "user name %s not convertible.\n", debugstr_a(name) );
508 /* set the USERPROFILE and ALLUSERSPROFILE variables */
510 attr.Length = sizeof(attr);
511 attr.RootDirectory = 0;
512 attr.ObjectName = &nameW;
514 attr.SecurityDescriptor = NULL;
515 attr.SecurityQualityOfService = NULL;
516 RtlInitUnicodeString( &nameW, profile_keyW );
517 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
519 profile_dir = get_reg_value( hkey, profiles_valueW );
520 all_users_dir = get_reg_value( hkey, all_users_valueW );
528 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
529 len += strlenW(profile_dir) + 1;
530 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
531 strcpyW( value, profile_dir );
532 p = value + strlenW(value);
533 if (p > value && p[-1] != '\\') *p++ = '\\';
535 strcpyW( p, user_name );
536 SetEnvironmentVariableW( userprofileW, value );
540 strcpyW( p, all_users_dir );
541 SetEnvironmentVariableW( allusersW, value );
543 HeapFree( GetProcessHeap(), 0, value );
546 HeapFree( GetProcessHeap(), 0, all_users_dir );
547 HeapFree( GetProcessHeap(), 0, profile_dir );
548 HeapFree( GetProcessHeap(), 0, user_name );
551 /***********************************************************************
554 * Set the Wine library Unicode argv global variables.
556 static void set_library_wargv( char **argv )
564 for (argc = 0; argv[argc]; argc++)
565 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
567 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
568 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
569 p = (WCHAR *)(wargv + argc + 1);
570 for (argc = 0; argv[argc]; argc++)
572 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
579 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
581 for (argc = 0; wargv[argc]; argc++)
582 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
584 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
585 q = (char *)(argv + argc + 1);
586 for (argc = 0; wargv[argc]; argc++)
588 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
595 __wine_main_argc = argc;
596 __wine_main_argv = argv;
597 __wine_main_wargv = wargv;
601 /***********************************************************************
602 * update_library_argv0
604 * Update the argv[0] global variable with the binary we have found.
606 static void update_library_argv0( const WCHAR *argv0 )
608 DWORD len = strlenW( argv0 );
610 if (len > strlenW( __wine_main_wargv[0] ))
612 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
614 strcpyW( __wine_main_wargv[0], argv0 );
616 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
617 if (len > strlen( __wine_main_argv[0] ) + 1)
619 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
621 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
625 /***********************************************************************
628 * Build the command line of a process from the argv array.
630 * Note that it does NOT necessarily include the file name.
631 * Sometimes we don't even have any command line options at all.
633 * We must quote and escape characters so that the argv array can be rebuilt
634 * from the command line:
635 * - spaces and tabs must be quoted
637 * - quotes must be escaped
639 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
640 * resulting in an odd number of '\' followed by a '"'
643 * - '\'s that are not followed by a '"' can be left as is
647 static BOOL build_command_line( WCHAR **argv )
652 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
654 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
657 for (arg = argv; *arg; arg++)
659 int has_space,bcount;
665 if( !*a ) has_space=1;
670 if (*a==' ' || *a=='\t') {
672 } else if (*a=='"') {
673 /* doubling of '\' preceding a '"',
674 * plus escaping of said '"'
682 len+=(a-*arg)+1 /* for the separating space */;
684 len+=2; /* for the quotes */
687 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
690 p = rupp->CommandLine.Buffer;
691 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
692 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
693 for (arg = argv; *arg; arg++)
695 int has_space,has_quote;
698 /* Check for quotes and spaces in this argument */
699 has_space=has_quote=0;
701 if( !*a ) has_space=1;
703 if (*a==' ' || *a=='\t') {
707 } else if (*a=='"') {
715 /* Now transfer it to the command line */
732 /* Double all the '\\' preceding this '"', plus one */
733 for (i=0;i<=bcount;i++)
745 while ((*p=*x++)) p++;
751 if (p > rupp->CommandLine.Buffer)
752 p--; /* remove last space */
759 /***********************************************************************
760 * init_current_directory
762 * Initialize the current directory from the Unix cwd or the parent info.
764 static void init_current_directory( CURDIR *cur_dir )
766 UNICODE_STRING dir_str;
770 /* if we received a cur dir from the parent, try this first */
772 if (cur_dir->DosPath.Length)
774 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
777 /* now try to get it from the Unix cwd */
779 for (size = 256; ; size *= 2)
781 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
782 if (getcwd( cwd, size )) break;
783 HeapFree( GetProcessHeap(), 0, cwd );
784 if (errno == ERANGE) continue;
792 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
793 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
795 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
796 RtlInitUnicodeString( &dir_str, dirW );
797 RtlSetCurrentDirectory_U( &dir_str );
798 RtlFreeUnicodeString( &dir_str );
802 if (!cur_dir->DosPath.Length) /* still not initialized */
804 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
805 "starting in the Windows directory.\n", cwd ? cwd : "" );
806 RtlInitUnicodeString( &dir_str, DIR_Windows );
807 RtlSetCurrentDirectory_U( &dir_str );
809 HeapFree( GetProcessHeap(), 0, cwd );
812 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
813 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
817 /***********************************************************************
820 * Initialize the windows and system directories from the environment.
822 static void init_windows_dirs(void)
824 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
826 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
827 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
828 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
829 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
834 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
836 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
837 GetEnvironmentVariableW( windirW, buffer, len );
838 DIR_Windows = buffer;
840 else DIR_Windows = default_windirW;
842 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
844 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
845 GetEnvironmentVariableW( winsysdirW, buffer, len );
850 len = strlenW( DIR_Windows );
851 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
852 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
853 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
857 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
858 ERR( "directory %s could not be created, error %u\n",
859 debugstr_w(DIR_Windows), GetLastError() );
860 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
861 ERR( "directory %s could not be created, error %u\n",
862 debugstr_w(DIR_System), GetLastError() );
864 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
865 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
867 /* set the directories in ntdll too */
868 __wine_init_windows_dir( DIR_Windows, DIR_System );
872 /***********************************************************************
875 * Start the wineboot process if necessary. Return the event to wait on.
877 static HANDLE start_wineboot(void)
879 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
882 if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
884 ERR( "failed to create wineboot event, expect trouble\n" );
887 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
889 static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
891 PROCESS_INFORMATION pi;
892 WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];
894 memset( &si, 0, sizeof(si) );
896 si.dwFlags = STARTF_USESTDHANDLES;
899 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
901 GetSystemDirectoryW( cmdline, MAX_PATH );
902 lstrcatW( cmdline, command_line );
903 if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
905 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
906 CloseHandle( pi.hThread );
907 CloseHandle( pi.hProcess );
910 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
916 /***********************************************************************
919 * Startup routine of a new process. Runs on the new process stack.
921 static void start_process( void *arg )
925 PEB *peb = NtCurrentTeb()->Peb;
926 IMAGE_NT_HEADERS *nt;
927 LPTHREAD_START_ROUTINE entry;
929 nt = RtlImageNtHeader( peb->ImageBaseAddress );
930 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
931 nt->OptionalHeader.AddressOfEntryPoint);
933 if (!nt->OptionalHeader.AddressOfEntryPoint)
935 ERR( "%s doesn't have an entry point, it cannot be executed\n",
936 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
941 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
942 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
944 SetLastError( 0 ); /* clear error code */
945 if (peb->BeingDebugged) DbgBreakPoint();
946 ExitThread( entry( peb ) );
948 __EXCEPT(UnhandledExceptionFilter)
950 TerminateThread( GetCurrentThread(), GetExceptionCode() );
956 /***********************************************************************
959 * Change the process name in the ps output.
961 static void set_process_name( int argc, char *argv[] )
963 #ifdef HAVE_SETPROCTITLE
964 setproctitle("-%s", argv[1]);
969 char *p, *prctl_name = argv[1];
970 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
973 # define PR_SET_NAME 15
976 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
977 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
979 if (prctl( PR_SET_NAME, prctl_name ) != -1)
981 offset = argv[1] - argv[0];
982 memmove( argv[1] - offset, argv[1], end - argv[1] );
983 memset( end - offset, 0, offset );
984 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
988 #endif /* HAVE_PRCTL */
991 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
996 /***********************************************************************
999 * Wine initialisation: load and start the main exe file.
1001 void CDECL __wine_kernel_init(void)
1003 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1004 static const WCHAR dotW[] = {'.',0};
1005 static const WCHAR exeW[] = {'.','e','x','e',0};
1007 WCHAR *p, main_exe_name[MAX_PATH+1];
1008 PEB *peb = NtCurrentTeb()->Peb;
1009 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1010 HANDLE boot_event = 0;
1011 BOOL got_environment = TRUE;
1013 /* Initialize everything */
1015 setbuf(stdout,NULL);
1016 setbuf(stderr,NULL);
1017 kernel32_handle = GetModuleHandleW(kernel32W);
1021 if (!params->Environment)
1023 /* Copy the parent environment */
1024 if (!build_initial_environment()) exit(1);
1026 /* convert old configuration to new format */
1027 convert_old_config();
1029 got_environment = set_registry_environment();
1030 set_additional_environment();
1033 init_windows_dirs();
1034 init_current_directory( ¶ms->CurrentDirectory );
1036 set_process_name( __wine_main_argc, __wine_main_argv );
1037 set_library_wargv( __wine_main_argv );
1039 if (peb->ProcessParameters->ImagePathName.Buffer)
1041 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1045 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1046 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1048 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1049 ExitProcess( GetLastError() );
1051 update_library_argv0( main_exe_name );
1052 if (!build_command_line( __wine_main_wargv )) goto error;
1053 boot_event = start_wineboot();
1056 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1057 p = strrchrW( main_exe_name, '.' );
1058 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1060 TRACE( "starting process name=%s argv[0]=%s\n",
1061 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1063 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1064 MODULE_get_dll_load_path(main_exe_name) );
1068 if (WaitForSingleObject( boot_event, 30000 )) ERR( "boot event wait timed out\n" );
1069 CloseHandle( boot_event );
1070 /* if we didn't find environment section, try again now that wineboot has run */
1071 if (!got_environment)
1073 set_registry_environment();
1074 set_additional_environment();
1078 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1081 DWORD error = GetLastError();
1083 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1084 if (error == ERROR_BAD_EXE_FORMAT ||
1085 error == ERROR_INVALID_ADDRESS ||
1086 error == ERROR_NOT_ENOUGH_MEMORY)
1088 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1089 /* if we get back here, it failed */
1091 else if (error == ERROR_MOD_NOT_FOUND)
1093 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1094 else p = main_exe_name;
1095 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1097 /* args 1 and 2 are --app-name full_path */
1098 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1099 debugstr_w(__wine_main_wargv[3]) );
1100 ExitProcess( ERROR_BAD_EXE_FORMAT );
1103 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1104 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1105 ExitProcess( error );
1108 LdrInitializeThunk( 0, 0, 0, 0 );
1109 /* switch to the new stack */
1110 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1113 ExitProcess( GetLastError() );
1117 /***********************************************************************
1120 * Build an argv array from a command-line.
1121 * 'reserved' is the number of args to reserve before the first one.
1123 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1127 char *arg,*s,*d,*cmdline;
1128 int in_quotes,bcount,len;
1130 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1131 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1132 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1139 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1142 /* skip the remaining spaces */
1143 while (*s==' ' || *s=='\t') {
1150 } else if (*s=='\\') {
1151 /* '\', count them */
1153 } else if ((*s=='"') && ((bcount & 1)==0)) {
1155 in_quotes=!in_quotes;
1158 /* a regular character */
1163 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1165 HeapFree( GetProcessHeap(), 0, cmdline );
1169 arg = d = s = (char *)(argv + argc);
1170 memcpy( d, cmdline, len );
1175 if ((*s==' ' || *s=='\t') && !in_quotes) {
1176 /* Close the argument and copy it */
1180 /* skip the remaining spaces */
1183 } while (*s==' ' || *s=='\t');
1185 /* Start with a new argument */
1188 } else if (*s=='\\') {
1192 } else if (*s=='"') {
1194 if ((bcount & 1)==0) {
1195 /* Preceded by an even number of '\', this is half that
1196 * number of '\', plus a '"' which we discard.
1200 in_quotes=!in_quotes;
1202 /* Preceded by an odd number of '\', this is half that
1203 * number of '\' followed by a '"'
1211 /* a regular character */
1222 HeapFree( GetProcessHeap(), 0, cmdline );
1227 /***********************************************************************
1230 * Build the environment of a new child process.
1232 static char **build_envp( const WCHAR *envW )
1234 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1239 int count = 1, length;
1242 for (end = envW; *end; count++) end += strlenW(end) + 1;
1244 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1245 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1246 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1248 for (p = env; *p; p += strlen(p) + 1)
1249 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1251 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1253 if (!(p = getenv(unix_vars[i]))) continue;
1254 length += strlen(unix_vars[i]) + strlen(p) + 2;
1258 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1260 char **envptr = envp;
1261 char *dst = (char *)(envp + count);
1263 /* some variables must not be modified, so we get them directly from the unix env */
1264 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1266 if (!(p = getenv(unix_vars[i]))) continue;
1267 *envptr++ = strcpy( dst, unix_vars[i] );
1270 dst += strlen(dst) + 1;
1273 /* now put the Windows environment strings */
1274 for (p = env; *p; p += strlen(p) + 1)
1276 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1277 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1278 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1279 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1280 if (is_special_env_var( p )) /* prefix it with "WINE" */
1282 *envptr++ = strcpy( dst, "WINE" );
1287 *envptr++ = strcpy( dst, p );
1289 dst += strlen(dst) + 1;
1293 HeapFree( GetProcessHeap(), 0, env );
1298 /***********************************************************************
1301 * Fork and exec a new Unix binary, checking for errors.
1303 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1304 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1306 int fd[2], stdin_fd = -1, stdout_fd = -1;
1308 char **argv, **envp;
1310 if (!env) env = GetEnvironmentStringsW();
1314 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1317 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1319 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1321 HANDLE hstdin, hstdout;
1323 if (startup->dwFlags & STARTF_USESTDHANDLES)
1325 hstdin = startup->hStdInput;
1326 hstdout = startup->hStdOutput;
1330 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1331 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1334 if (is_console_handle( hstdin ))
1335 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1336 if (is_console_handle( hstdout ))
1337 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1338 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1339 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1342 argv = build_argv( cmdline, 0 );
1343 envp = build_envp( env );
1345 if (!(pid = fork())) /* child */
1349 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1352 if (!(pid = fork()))
1354 int fd = open( "/dev/null", O_RDWR );
1356 /* close stdin and stdout */
1364 else if (pid != -1) _exit(0); /* parent */
1370 dup2( stdin_fd, 0 );
1373 if (stdout_fd != -1)
1375 dup2( stdout_fd, 1 );
1380 /* Reset signals that we previously set to SIG_IGN */
1381 signal( SIGPIPE, SIG_DFL );
1382 signal( SIGCHLD, SIG_DFL );
1384 if (newdir) chdir(newdir);
1386 if (argv && envp) execve( filename, argv, envp );
1388 write( fd[1], &err, sizeof(err) );
1391 HeapFree( GetProcessHeap(), 0, argv );
1392 HeapFree( GetProcessHeap(), 0, envp );
1393 if (stdin_fd != -1) close( stdin_fd );
1394 if (stdout_fd != -1) close( stdout_fd );
1396 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1401 if (pid == -1) FILE_SetDosError();
1407 /***********************************************************************
1408 * create_user_params
1410 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1411 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1412 const STARTUPINFOW *startup )
1414 RTL_USER_PROCESS_PARAMETERS *params;
1415 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1417 WCHAR buffer[MAX_PATH];
1419 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1420 lstrcpynW( buffer, filename, MAX_PATH );
1421 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1422 lstrcpynW( buffer, filename, MAX_PATH );
1423 RtlInitUnicodeString( &image_str, buffer );
1425 RtlInitUnicodeString( &cmdline_str, cmdline );
1426 newdir.Buffer = NULL;
1429 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1431 /* skip \??\ prefix */
1432 curdir_str.Buffer = newdir.Buffer + 4;
1433 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1434 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1436 else cur_dir = NULL;
1438 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1439 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1440 if (startup->lpReserved2 && startup->cbReserved2)
1443 runtime.MaximumLength = startup->cbReserved2;
1444 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1447 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1448 cur_dir ? &curdir_str : NULL,
1450 startup->lpTitle ? &title : NULL,
1451 startup->lpDesktop ? &desktop : NULL,
1453 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1454 RtlFreeUnicodeString( &newdir );
1455 if (status != STATUS_SUCCESS)
1457 SetLastError( RtlNtStatusToDosError(status) );
1461 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1462 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1464 if (startup->dwFlags & STARTF_USESTDHANDLES)
1466 params->hStdInput = startup->hStdInput;
1467 params->hStdOutput = startup->hStdOutput;
1468 params->hStdError = startup->hStdError;
1472 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1473 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1474 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1476 params->dwX = startup->dwX;
1477 params->dwY = startup->dwY;
1478 params->dwXSize = startup->dwXSize;
1479 params->dwYSize = startup->dwYSize;
1480 params->dwXCountChars = startup->dwXCountChars;
1481 params->dwYCountChars = startup->dwYCountChars;
1482 params->dwFillAttribute = startup->dwFillAttribute;
1483 params->dwFlags = startup->dwFlags;
1484 params->wShowWindow = startup->wShowWindow;
1489 /***********************************************************************
1492 * Create a new process. If hFile is a valid handle we have an exe
1493 * file, otherwise it is a Winelib app.
1495 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1496 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1497 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1498 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1499 void *res_start, void *res_end, int exec_only )
1501 BOOL ret, success = FALSE;
1502 HANDLE process_info, hstdin, hstdout;
1504 char *winedebug = NULL;
1506 RTL_USER_PROCESS_PARAMETERS *params;
1507 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1511 if (!env) RtlAcquirePebLock();
1513 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1515 if (!env) RtlReleasePebLock();
1518 env_end = params->Environment;
1521 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1522 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1524 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1525 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1526 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1528 env_end += strlenW(env_end) + 1;
1532 /* create the socket for the new process */
1534 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1536 if (!env) RtlReleasePebLock();
1537 HeapFree( GetProcessHeap(), 0, winedebug );
1538 RtlDestroyProcessParameters( params );
1539 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1542 wine_server_send_fd( socketfd[1] );
1543 close( socketfd[1] );
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->socket_fd = socketfd[1];
1552 req->exe_file = wine_server_obj_handle( hFile );
1553 req->process_access = PROCESS_ALL_ACCESS;
1554 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1555 req->thread_access = THREAD_ALL_ACCESS;
1556 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1557 req->hstdin = wine_server_obj_handle( params->hStdInput );
1558 req->hstdout = wine_server_obj_handle( params->hStdOutput );
1559 req->hstderr = wine_server_obj_handle( params->hStdError );
1561 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1563 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1564 if (is_console_handle(params->hStdInput)) req->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1565 if (is_console_handle(params->hStdOutput)) req->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1566 if (is_console_handle(params->hStdError)) req->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1567 hstdin = hstdout = 0;
1571 if (is_console_handle(params->hStdInput)) req->hstdin = console_handle_unmap(params->hStdInput);
1572 if (is_console_handle(params->hStdOutput)) req->hstdout = console_handle_unmap(params->hStdOutput);
1573 if (is_console_handle(params->hStdError)) req->hstderr = console_handle_unmap(params->hStdError);
1574 hstdin = wine_server_ptr_handle( req->hstdin );
1575 hstdout = wine_server_ptr_handle( req->hstdout );
1578 wine_server_add_data( req, params, params->Size );
1579 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1580 if ((ret = !wine_server_call_err( req )))
1582 info->dwProcessId = (DWORD)reply->pid;
1583 info->dwThreadId = (DWORD)reply->tid;
1584 info->hProcess = wine_server_ptr_handle( reply->phandle );
1585 info->hThread = wine_server_ptr_handle( reply->thandle );
1587 process_info = wine_server_ptr_handle( reply->info );
1591 if (!env) RtlReleasePebLock();
1592 RtlDestroyProcessParameters( params );
1595 close( socketfd[0] );
1596 HeapFree( GetProcessHeap(), 0, winedebug );
1600 if (hstdin) wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1601 if (hstdout) wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1603 /* create the child process */
1604 argv = build_argv( cmd_line, 1 );
1606 if (exec_only || !(pid = fork())) /* child */
1608 char preloader_reserve[64], socket_env[64];
1610 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1612 if (!(pid = fork()))
1614 int fd = open( "/dev/null", O_RDWR );
1616 /* close stdin and stdout */
1624 else if (pid != -1) _exit(0); /* parent */
1628 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1629 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1632 if (stdin_fd != -1) close( stdin_fd );
1633 if (stdout_fd != -1) close( stdout_fd );
1635 /* Reset signals that we previously set to SIG_IGN */
1636 signal( SIGPIPE, SIG_DFL );
1637 signal( SIGCHLD, SIG_DFL );
1639 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1640 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1641 (unsigned long)res_start, (unsigned long)res_end );
1643 putenv( preloader_reserve );
1644 putenv( socket_env );
1645 if (winedebug) putenv( winedebug );
1646 if (unixdir) chdir(unixdir);
1648 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1652 /* this is the parent */
1654 if (stdin_fd != -1) close( stdin_fd );
1655 if (stdout_fd != -1) close( stdout_fd );
1656 close( socketfd[0] );
1657 HeapFree( GetProcessHeap(), 0, argv );
1658 HeapFree( GetProcessHeap(), 0, winedebug );
1665 /* wait for the new process info to be ready */
1667 WaitForSingleObject( process_info, INFINITE );
1668 SERVER_START_REQ( get_new_process_info )
1670 req->info = wine_server_obj_handle( process_info );
1671 wine_server_call( req );
1672 success = reply->success;
1673 err = reply->exit_code;
1679 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1682 CloseHandle( process_info );
1686 CloseHandle( process_info );
1687 CloseHandle( info->hProcess );
1688 CloseHandle( info->hThread );
1689 info->hProcess = info->hThread = 0;
1690 info->dwProcessId = info->dwThreadId = 0;
1695 /***********************************************************************
1696 * create_vdm_process
1698 * Create a new VDM process for a 16-bit or DOS application.
1700 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1701 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1702 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1703 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1705 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1708 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1709 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1713 SetLastError( ERROR_OUTOFMEMORY );
1716 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1717 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1718 flags, startup, info, unixdir, NULL, NULL, exec_only );
1719 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1724 /***********************************************************************
1725 * create_cmd_process
1727 * Create a new cmd shell process for a .BAT file.
1729 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1730 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1731 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1732 LPPROCESS_INFORMATION info )
1735 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1736 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1737 WCHAR comspec[MAX_PATH];
1741 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1743 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1744 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1747 strcpyW( newcmdline, comspec );
1748 strcatW( newcmdline, slashcW );
1749 strcatW( newcmdline, cmd_line );
1750 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1751 flags, env, cur_dir, startup, info );
1752 HeapFree( GetProcessHeap(), 0, newcmdline );
1757 /*************************************************************************
1760 * Helper for CreateProcess: retrieve the file name to load from the
1761 * app name and command line. Store the file name in buffer, and
1762 * return a possibly modified command line.
1763 * Also returns a handle to the opened file if it's a Windows binary.
1765 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1766 int buflen, HANDLE *handle )
1768 static const WCHAR quotesW[] = {'"','%','s','"',0};
1770 WCHAR *name, *pos, *ret = NULL;
1774 /* if we have an app name, everything is easy */
1778 /* use the unmodified app name as file name */
1779 lstrcpynW( buffer, appname, buflen );
1780 *handle = open_exe_file( buffer );
1781 if (!(ret = cmdline) || !cmdline[0])
1783 /* no command-line, create one */
1784 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1785 sprintfW( ret, quotesW, appname );
1792 SetLastError( ERROR_INVALID_PARAMETER );
1796 /* first check for a quoted file name */
1798 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1800 int len = p - cmdline - 1;
1801 /* extract the quoted portion as file name */
1802 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1803 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1806 if (find_exe_file( name, buffer, buflen, handle ))
1807 ret = cmdline; /* no change necessary */
1811 /* now try the command-line word by word */
1813 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1821 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1823 if (find_exe_file( name, buffer, buflen, handle ))
1828 if (*p) got_space = TRUE;
1831 if (ret && got_space) /* now build a new command-line with quotes */
1833 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1835 sprintfW( ret, quotesW, name );
1840 HeapFree( GetProcessHeap(), 0, name );
1845 /**********************************************************************
1846 * CreateProcessA (KERNEL32.@)
1848 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1849 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1850 DWORD flags, LPVOID env, LPCSTR cur_dir,
1851 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1854 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1855 UNICODE_STRING desktopW, titleW;
1858 desktopW.Buffer = NULL;
1859 titleW.Buffer = NULL;
1860 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1861 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1862 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1864 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1865 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1867 memcpy( &infoW, startup_info, sizeof(infoW) );
1868 infoW.lpDesktop = desktopW.Buffer;
1869 infoW.lpTitle = titleW.Buffer;
1871 if (startup_info->lpReserved)
1872 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1873 debugstr_a(startup_info->lpReserved));
1875 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1876 inherit, flags, env, cur_dirW, &infoW, info );
1878 HeapFree( GetProcessHeap(), 0, app_nameW );
1879 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1880 HeapFree( GetProcessHeap(), 0, cur_dirW );
1881 RtlFreeUnicodeString( &desktopW );
1882 RtlFreeUnicodeString( &titleW );
1887 /**********************************************************************
1888 * CreateProcessW (KERNEL32.@)
1890 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1891 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1892 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1893 LPPROCESS_INFORMATION info )
1897 char *unixdir = NULL;
1898 WCHAR name[MAX_PATH];
1899 WCHAR *tidy_cmdline, *p, *envW = env;
1900 void *res_start, *res_end;
1902 /* Process the AppName and/or CmdLine to get module name and path */
1904 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1906 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1908 if (hFile == INVALID_HANDLE_VALUE) goto done;
1910 /* Warn if unsupported features are used */
1912 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1913 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1914 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1915 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1916 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1920 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1922 SetLastError(ERROR_DIRECTORY);
1928 WCHAR buf[MAX_PATH];
1929 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1932 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1937 while (*p) p += strlen(p) + 1;
1938 p++; /* final null */
1939 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1940 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1941 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1942 flags |= CREATE_UNICODE_ENVIRONMENT;
1945 info->hThread = info->hProcess = 0;
1946 info->dwProcessId = info->dwThreadId = 0;
1948 /* Determine executable type */
1950 if (!hFile) /* builtin exe */
1952 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1953 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1954 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1958 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1961 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1962 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1963 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1968 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1969 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1970 inherit, flags, startup_info, info, unixdir, FALSE );
1973 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1974 SetLastError( ERROR_BAD_EXE_FORMAT );
1976 case BINARY_UNIX_LIB:
1977 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1978 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1979 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1981 case BINARY_UNKNOWN:
1982 /* check for .com or .bat extension */
1983 if ((p = strrchrW( name, '.' )))
1985 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1987 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1988 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1989 inherit, flags, startup_info, info, unixdir, FALSE );
1992 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1994 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1995 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1996 inherit, flags, startup_info, info );
2001 case BINARY_UNIX_EXE:
2003 /* unknown file, try as unix executable */
2006 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2008 if ((unix_name = wine_get_unix_file_name( name )))
2010 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2011 HeapFree( GetProcessHeap(), 0, unix_name );
2016 CloseHandle( hFile );
2019 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2020 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2021 HeapFree( GetProcessHeap(), 0, unixdir );
2023 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2028 /**********************************************************************
2031 static void exec_process( LPCWSTR name )
2035 void *res_start, *res_end;
2036 STARTUPINFOW startup_info;
2037 PROCESS_INFORMATION info;
2039 hFile = open_exe_file( name );
2040 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2042 memset( &startup_info, 0, sizeof(startup_info) );
2043 startup_info.cb = sizeof(startup_info);
2045 /* Determine executable type */
2047 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
2050 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
2051 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2052 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
2054 case BINARY_UNIX_LIB:
2055 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2056 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2057 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
2059 case BINARY_UNKNOWN:
2060 /* check for .com or .pif extension */
2061 if (!(p = strrchrW( name, '.' ))) break;
2062 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2067 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2068 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2069 FALSE, 0, &startup_info, &info, NULL, TRUE );
2074 CloseHandle( hFile );
2078 /***********************************************************************
2081 * Wrapper to call WaitForInputIdle USER function
2083 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2085 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2087 HMODULE mod = GetModuleHandleA( "user32.dll" );
2090 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2091 if (ptr) return ptr( process, timeout );
2097 /***********************************************************************
2098 * WinExec (KERNEL32.@)
2100 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2102 PROCESS_INFORMATION info;
2103 STARTUPINFOA startup;
2107 memset( &startup, 0, sizeof(startup) );
2108 startup.cb = sizeof(startup);
2109 startup.dwFlags = STARTF_USESHOWWINDOW;
2110 startup.wShowWindow = nCmdShow;
2112 /* cmdline needs to be writable for CreateProcess */
2113 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2114 strcpy( cmdline, lpCmdLine );
2116 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2117 0, NULL, NULL, &startup, &info ))
2119 /* Give 30 seconds to the app to come up */
2120 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2121 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2123 /* Close off the handles */
2124 CloseHandle( info.hThread );
2125 CloseHandle( info.hProcess );
2127 else if ((ret = GetLastError()) >= 32)
2129 FIXME("Strange error set by CreateProcess: %d\n", ret );
2132 HeapFree( GetProcessHeap(), 0, cmdline );
2137 /**********************************************************************
2138 * LoadModule (KERNEL32.@)
2140 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2142 LOADPARMS32 *params = paramBlock;
2143 PROCESS_INFORMATION info;
2144 STARTUPINFOA startup;
2145 HINSTANCE hInstance;
2147 char filename[MAX_PATH];
2150 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2152 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2153 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2154 return ULongToHandle(GetLastError());
2156 len = (BYTE)params->lpCmdLine[0];
2157 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2158 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2160 strcpy( cmdline, filename );
2161 p = cmdline + strlen(cmdline);
2163 memcpy( p, params->lpCmdLine + 1, len );
2166 memset( &startup, 0, sizeof(startup) );
2167 startup.cb = sizeof(startup);
2168 if (params->lpCmdShow)
2170 startup.dwFlags = STARTF_USESHOWWINDOW;
2171 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2174 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2175 params->lpEnvAddress, NULL, &startup, &info ))
2177 /* Give 30 seconds to the app to come up */
2178 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2179 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2180 hInstance = (HINSTANCE)33;
2181 /* Close off the handles */
2182 CloseHandle( info.hThread );
2183 CloseHandle( info.hProcess );
2185 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2187 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2188 hInstance = (HINSTANCE)11;
2191 HeapFree( GetProcessHeap(), 0, cmdline );
2196 /******************************************************************************
2197 * TerminateProcess (KERNEL32.@)
2199 * Terminates a process.
2202 * handle [I] Process to terminate.
2203 * exit_code [I] Exit code.
2207 * Failure: FALSE, check GetLastError().
2209 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2211 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2212 if (status) SetLastError( RtlNtStatusToDosError(status) );
2216 /***********************************************************************
2217 * ExitProcess (KERNEL32.@)
2219 * Exits the current process.
2222 * status [I] Status code to exit with.
2228 __ASM_GLOBAL_FUNC( ExitProcess, /* Shrinker depend on this particular ExitProcess implementation */
2230 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2231 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2232 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2234 "call " __ASM_NAME("process_ExitProcess") "\n\t"
2238 void WINAPI process_ExitProcess( DWORD status )
2240 LdrShutdownProcess();
2241 NtTerminateProcess(GetCurrentProcess(), status);
2247 void WINAPI ExitProcess( DWORD status )
2249 LdrShutdownProcess();
2250 NtTerminateProcess(GetCurrentProcess(), status);
2256 /***********************************************************************
2257 * GetExitCodeProcess [KERNEL32.@]
2259 * Gets termination status of specified process.
2262 * hProcess [in] Handle to the process.
2263 * lpExitCode [out] Address to receive termination status.
2269 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2272 PROCESS_BASIC_INFORMATION pbi;
2274 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2276 if (status == STATUS_SUCCESS)
2278 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2281 SetLastError( RtlNtStatusToDosError(status) );
2286 /***********************************************************************
2287 * SetErrorMode (KERNEL32.@)
2289 UINT WINAPI SetErrorMode( UINT mode )
2291 UINT old = process_error_mode;
2292 process_error_mode = mode;
2296 /***********************************************************************
2297 * GetErrorMode (KERNEL32.@)
2299 UINT WINAPI GetErrorMode( void )
2301 return process_error_mode;
2304 /**********************************************************************
2305 * TlsAlloc [KERNEL32.@]
2307 * Allocates a thread local storage index.
2310 * Success: TLS index.
2311 * Failure: 0xFFFFFFFF
2313 DWORD WINAPI TlsAlloc( void )
2316 PEB * const peb = NtCurrentTeb()->Peb;
2318 RtlAcquirePebLock();
2319 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2320 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2323 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2326 if (!NtCurrentTeb()->TlsExpansionSlots &&
2327 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2328 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2330 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2332 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2336 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2337 index += TLS_MINIMUM_AVAILABLE;
2340 else SetLastError( ERROR_NO_MORE_ITEMS );
2342 RtlReleasePebLock();
2347 /**********************************************************************
2348 * TlsFree [KERNEL32.@]
2350 * Releases a thread local storage index, making it available for reuse.
2353 * index [in] TLS index to free.
2359 BOOL WINAPI TlsFree( DWORD index )
2363 RtlAcquirePebLock();
2364 if (index >= TLS_MINIMUM_AVAILABLE)
2366 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2367 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2371 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2372 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2374 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2375 else SetLastError( ERROR_INVALID_PARAMETER );
2376 RtlReleasePebLock();
2381 /**********************************************************************
2382 * TlsGetValue [KERNEL32.@]
2384 * Gets value in a thread's TLS slot.
2387 * index [in] TLS index to retrieve value for.
2390 * Success: Value stored in calling thread's TLS slot for index.
2391 * Failure: 0 and GetLastError() returns NO_ERROR.
2393 LPVOID WINAPI TlsGetValue( DWORD index )
2397 if (index < TLS_MINIMUM_AVAILABLE)
2399 ret = NtCurrentTeb()->TlsSlots[index];
2403 index -= TLS_MINIMUM_AVAILABLE;
2404 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2406 SetLastError( ERROR_INVALID_PARAMETER );
2409 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2410 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2412 SetLastError( ERROR_SUCCESS );
2417 /**********************************************************************
2418 * TlsSetValue [KERNEL32.@]
2420 * Stores a value in the thread's TLS slot.
2423 * index [in] TLS index to set value for.
2424 * value [in] Value to be stored.
2430 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2432 if (index < TLS_MINIMUM_AVAILABLE)
2434 NtCurrentTeb()->TlsSlots[index] = value;
2438 index -= TLS_MINIMUM_AVAILABLE;
2439 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2441 SetLastError( ERROR_INVALID_PARAMETER );
2444 if (!NtCurrentTeb()->TlsExpansionSlots &&
2445 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2446 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2448 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2451 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2457 /***********************************************************************
2458 * GetProcessFlags (KERNEL32.@)
2460 DWORD WINAPI GetProcessFlags( DWORD processid )
2462 IMAGE_NT_HEADERS *nt;
2465 if (processid && processid != GetCurrentProcessId()) return 0;
2467 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2469 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2470 flags |= PDB32_CONSOLE_PROC;
2472 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2473 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2478 /***********************************************************************
2479 * GetProcessDword (KERNEL.485)
2480 * GetProcessDword (KERNEL32.18)
2481 * 'Of course you cannot directly access Windows internal structures'
2483 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2488 TRACE("(%d, %d)\n", dwProcessID, offset );
2490 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2492 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2498 case GPD_APP_COMPAT_FLAGS:
2499 return GetAppCompatFlags16(0);
2500 case GPD_LOAD_DONE_EVENT:
2502 case GPD_HINSTANCE16:
2503 return GetTaskDS16();
2504 case GPD_WINDOWS_VERSION:
2505 return GetExeVersion16();
2507 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2509 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2510 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2511 GetStartupInfoW(&siw);
2512 return HandleToULong(siw.hStdOutput);
2513 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2514 GetStartupInfoW(&siw);
2515 return HandleToULong(siw.hStdInput);
2516 case GPD_STARTF_SHOWWINDOW:
2517 GetStartupInfoW(&siw);
2518 return siw.wShowWindow;
2519 case GPD_STARTF_SIZE:
2520 GetStartupInfoW(&siw);
2522 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2524 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2525 return MAKELONG( x, y );
2526 case GPD_STARTF_POSITION:
2527 GetStartupInfoW(&siw);
2529 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2531 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2532 return MAKELONG( x, y );
2533 case GPD_STARTF_FLAGS:
2534 GetStartupInfoW(&siw);
2539 return GetProcessFlags(0);
2541 return process_dword;
2543 ERR("Unknown offset %d\n", offset );
2548 /***********************************************************************
2549 * SetProcessDword (KERNEL.484)
2550 * 'Of course you cannot directly access Windows internal structures'
2552 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2554 TRACE("(%d, %d)\n", dwProcessID, offset );
2556 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2558 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2564 case GPD_APP_COMPAT_FLAGS:
2565 case GPD_LOAD_DONE_EVENT:
2566 case GPD_HINSTANCE16:
2567 case GPD_WINDOWS_VERSION:
2570 case GPD_STARTF_SHELLDATA:
2571 case GPD_STARTF_HOTKEY:
2572 case GPD_STARTF_SHOWWINDOW:
2573 case GPD_STARTF_SIZE:
2574 case GPD_STARTF_POSITION:
2575 case GPD_STARTF_FLAGS:
2578 ERR("Not allowed to modify offset %d\n", offset );
2581 process_dword = value;
2584 ERR("Unknown offset %d\n", offset );
2590 /***********************************************************************
2591 * ExitProcess (KERNEL.466)
2593 void WINAPI ExitProcess16( WORD status )
2596 ReleaseThunkLock( &count );
2597 ExitProcess( status );
2601 /*********************************************************************
2602 * OpenProcess (KERNEL32.@)
2604 * Opens a handle to a process.
2607 * access [I] Desired access rights assigned to the returned handle.
2608 * inherit [I] Determines whether or not child processes will inherit the handle.
2609 * id [I] Process identifier of the process to get a handle to.
2612 * Success: Valid handle to the specified process.
2613 * Failure: NULL, check GetLastError().
2615 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2619 OBJECT_ATTRIBUTES attr;
2622 cid.UniqueProcess = ULongToHandle(id);
2623 cid.UniqueThread = 0; /* FIXME ? */
2625 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2626 attr.RootDirectory = NULL;
2627 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2628 attr.SecurityDescriptor = NULL;
2629 attr.SecurityQualityOfService = NULL;
2630 attr.ObjectName = NULL;
2632 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2634 status = NtOpenProcess(&handle, access, &attr, &cid);
2635 if (status != STATUS_SUCCESS)
2637 SetLastError( RtlNtStatusToDosError(status) );
2644 /*********************************************************************
2645 * MapProcessHandle (KERNEL.483)
2646 * GetProcessId (KERNEL32.@)
2648 * Gets the a unique identifier of a process.
2651 * hProcess [I] Handle to the process.
2655 * Failure: FALSE, check GetLastError().
2659 * The identifier is unique only on the machine and only until the process
2660 * exits (including system shutdown).
2662 DWORD WINAPI GetProcessId( HANDLE hProcess )
2665 PROCESS_BASIC_INFORMATION pbi;
2667 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2669 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2670 SetLastError( RtlNtStatusToDosError(status) );
2675 /*********************************************************************
2676 * CloseW32Handle (KERNEL.474)
2677 * CloseHandle (KERNEL32.@)
2682 * handle [I] Handle to close.
2686 * Failure: FALSE, check GetLastError().
2688 BOOL WINAPI CloseHandle( HANDLE handle )
2692 /* stdio handles need special treatment */
2693 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2694 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2695 (handle == (HANDLE)STD_ERROR_HANDLE))
2696 handle = GetStdHandle( HandleToULong(handle) );
2698 if (is_console_handle(handle))
2699 return CloseConsoleHandle(handle);
2701 status = NtClose( handle );
2702 if (status) SetLastError( RtlNtStatusToDosError(status) );
2707 /*********************************************************************
2708 * GetHandleInformation (KERNEL32.@)
2710 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2712 OBJECT_DATA_INFORMATION info;
2713 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2715 if (status) SetLastError( RtlNtStatusToDosError(status) );
2719 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2720 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2726 /*********************************************************************
2727 * SetHandleInformation (KERNEL32.@)
2729 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2731 OBJECT_DATA_INFORMATION info;
2734 /* if not setting both fields, retrieve current value first */
2735 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2736 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2738 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2740 SetLastError( RtlNtStatusToDosError(status) );
2744 if (mask & HANDLE_FLAG_INHERIT)
2745 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2746 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2747 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2749 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2750 if (status) SetLastError( RtlNtStatusToDosError(status) );
2755 /*********************************************************************
2756 * DuplicateHandle (KERNEL32.@)
2758 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2759 HANDLE dest_process, HANDLE *dest,
2760 DWORD access, BOOL inherit, DWORD options )
2764 if (is_console_handle(source))
2766 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2767 if (source_process != dest_process ||
2768 source_process != GetCurrentProcess())
2770 SetLastError(ERROR_INVALID_PARAMETER);
2773 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2774 return (*dest != INVALID_HANDLE_VALUE);
2776 status = NtDuplicateObject( source_process, source, dest_process, dest,
2777 access, inherit ? OBJ_INHERIT : 0, options );
2778 if (status) SetLastError( RtlNtStatusToDosError(status) );
2783 /***********************************************************************
2784 * ConvertToGlobalHandle (KERNEL.476)
2785 * ConvertToGlobalHandle (KERNEL32.@)
2787 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2789 HANDLE ret = INVALID_HANDLE_VALUE;
2790 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2791 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2796 /***********************************************************************
2797 * SetHandleContext (KERNEL32.@)
2799 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2801 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2802 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2803 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2808 /***********************************************************************
2809 * GetHandleContext (KERNEL32.@)
2811 DWORD WINAPI GetHandleContext(HANDLE hnd)
2813 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2814 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2815 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2820 /***********************************************************************
2821 * CreateSocketHandle (KERNEL32.@)
2823 HANDLE WINAPI CreateSocketHandle(void)
2825 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2826 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2827 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2828 return INVALID_HANDLE_VALUE;
2832 /***********************************************************************
2833 * SetPriorityClass (KERNEL32.@)
2835 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2838 PROCESS_PRIORITY_CLASS ppc;
2840 ppc.Foreground = FALSE;
2841 switch (priorityclass)
2843 case IDLE_PRIORITY_CLASS:
2844 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2845 case BELOW_NORMAL_PRIORITY_CLASS:
2846 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2847 case NORMAL_PRIORITY_CLASS:
2848 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2849 case ABOVE_NORMAL_PRIORITY_CLASS:
2850 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2851 case HIGH_PRIORITY_CLASS:
2852 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2853 case REALTIME_PRIORITY_CLASS:
2854 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2856 SetLastError(ERROR_INVALID_PARAMETER);
2860 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2863 if (status != STATUS_SUCCESS)
2865 SetLastError( RtlNtStatusToDosError(status) );
2872 /***********************************************************************
2873 * GetPriorityClass (KERNEL32.@)
2875 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2878 PROCESS_BASIC_INFORMATION pbi;
2880 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2882 if (status != STATUS_SUCCESS)
2884 SetLastError( RtlNtStatusToDosError(status) );
2887 switch (pbi.BasePriority)
2889 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2890 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2891 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2892 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2893 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2894 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2896 SetLastError( ERROR_INVALID_PARAMETER );
2901 /***********************************************************************
2902 * SetProcessAffinityMask (KERNEL32.@)
2904 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2908 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2909 &affmask, sizeof(DWORD_PTR));
2912 SetLastError( RtlNtStatusToDosError(status) );
2919 /**********************************************************************
2920 * GetProcessAffinityMask (KERNEL32.@)
2922 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2923 PDWORD_PTR lpProcessAffinityMask,
2924 PDWORD_PTR lpSystemAffinityMask )
2926 PROCESS_BASIC_INFORMATION pbi;
2929 status = NtQueryInformationProcess(hProcess,
2930 ProcessBasicInformation,
2931 &pbi, sizeof(pbi), NULL);
2934 SetLastError( RtlNtStatusToDosError(status) );
2937 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2938 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2943 /***********************************************************************
2944 * GetProcessVersion (KERNEL32.@)
2946 DWORD WINAPI GetProcessVersion( DWORD pid )
2950 PROCESS_BASIC_INFORMATION pbi;
2953 IMAGE_DOS_HEADER dos;
2954 IMAGE_NT_HEADERS nt;
2957 if (!pid || pid == GetCurrentProcessId())
2959 IMAGE_NT_HEADERS *nt;
2961 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2962 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2963 nt->OptionalHeader.MinorSubsystemVersion);
2967 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2968 if (!process) return 0;
2970 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2971 if (status) goto err;
2973 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2974 if (status || count != sizeof(peb)) goto err;
2976 memset(&dos, 0, sizeof(dos));
2977 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2978 if (status || count != sizeof(dos)) goto err;
2979 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2981 memset(&nt, 0, sizeof(nt));
2982 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2983 if (status || count != sizeof(nt)) goto err;
2984 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2986 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2989 CloseHandle(process);
2991 if (status != STATUS_SUCCESS)
2992 SetLastError(RtlNtStatusToDosError(status));
2998 /***********************************************************************
2999 * SetProcessWorkingSetSize [KERNEL32.@]
3000 * Sets the min/max working set sizes for a specified process.
3003 * hProcess [I] Handle to the process of interest
3004 * minset [I] Specifies minimum working set size
3005 * maxset [I] Specifies maximum working set size
3011 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3014 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3015 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3016 /* Trim the working set to zero */
3017 /* Swap the process out of physical RAM */
3022 /***********************************************************************
3023 * GetProcessWorkingSetSize (KERNEL32.@)
3025 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3028 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3029 /* 32 MB working set size */
3030 if (minset) *minset = 32*1024*1024;
3031 if (maxset) *maxset = 32*1024*1024;
3036 /***********************************************************************
3037 * SetProcessShutdownParameters (KERNEL32.@)
3039 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3041 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3042 shutdown_flags = flags;
3043 shutdown_priority = level;
3048 /***********************************************************************
3049 * GetProcessShutdownParameters (KERNEL32.@)
3052 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3054 *lpdwLevel = shutdown_priority;
3055 *lpdwFlags = shutdown_flags;
3060 /***********************************************************************
3061 * GetProcessPriorityBoost (KERNEL32.@)
3063 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3065 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3067 /* Report that no boost is present.. */
3068 *pDisablePriorityBoost = FALSE;
3073 /***********************************************************************
3074 * SetProcessPriorityBoost (KERNEL32.@)
3076 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3078 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3079 /* Say we can do it. I doubt the program will notice that we don't. */
3084 /***********************************************************************
3085 * ReadProcessMemory (KERNEL32.@)
3087 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3088 SIZE_T *bytes_read )
3090 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3091 if (status) SetLastError( RtlNtStatusToDosError(status) );
3096 /***********************************************************************
3097 * WriteProcessMemory (KERNEL32.@)
3099 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3100 SIZE_T *bytes_written )
3102 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3103 if (status) SetLastError( RtlNtStatusToDosError(status) );
3108 /****************************************************************************
3109 * FlushInstructionCache (KERNEL32.@)
3111 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3114 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3115 if (status) SetLastError( RtlNtStatusToDosError(status) );
3120 /******************************************************************
3121 * GetProcessIoCounters (KERNEL32.@)
3123 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3127 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3128 ioc, sizeof(*ioc), NULL);
3129 if (status) SetLastError( RtlNtStatusToDosError(status) );
3133 /******************************************************************
3134 * GetProcessHandleCount (KERNEL32.@)
3136 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3140 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3141 cnt, sizeof(*cnt), NULL);
3142 if (status) SetLastError( RtlNtStatusToDosError(status) );
3146 /******************************************************************
3147 * QueryFullProcessImageNameW (KERNEL32.@)
3149 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3151 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3152 UNICODE_STRING *dynamic_buffer = NULL;
3153 UNICODE_STRING nt_path;
3154 UNICODE_STRING *result = NULL;
3158 RtlInitUnicodeStringEx(&nt_path, NULL);
3159 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3160 * as this is on Wine. */
3161 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3162 sizeof(buffer) - sizeof(WCHAR), &needed);
3163 if (status == STATUS_INFO_LENGTH_MISMATCH)
3165 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3166 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3167 result = dynamic_buffer;
3170 result = (PUNICODE_STRING)buffer;
3172 if (status) goto cleanup;
3174 if (dwFlags & PROCESS_NAME_NATIVE)
3176 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3177 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3179 status = STATUS_OBJECT_PATH_NOT_FOUND;
3185 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3187 status = STATUS_BUFFER_TOO_SMALL;
3191 *pdwSize = result->Length/sizeof(WCHAR);
3192 memcpy( lpExeName, result->Buffer, result->Length );
3193 lpExeName[*pdwSize] = 0;
3196 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3197 RtlFreeUnicodeString(&nt_path);
3198 if (status) SetLastError( RtlNtStatusToDosError(status) );
3202 /***********************************************************************
3203 * ProcessIdToSessionId (KERNEL32.@)
3204 * This function is available on Terminal Server 4SP4 and Windows 2000
3206 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3208 /* According to MSDN, if the calling process is not in a terminal
3209 * services environment, then the sessionid returned is zero.
3216 /***********************************************************************
3217 * RegisterServiceProcess (KERNEL.491)
3218 * RegisterServiceProcess (KERNEL32.@)
3220 * A service process calls this function to ensure that it continues to run
3221 * even after a user logged off.
3223 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3225 /* I don't think that Wine needs to do anything in this function */
3226 return 1; /* success */
3230 /**********************************************************************
3231 * IsWow64Process (KERNEL32.@)
3233 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3238 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3240 if (status != STATUS_SUCCESS)
3242 SetLastError( RtlNtStatusToDosError( status ) );
3245 *Wow64Process = (pbi != 0);
3250 /***********************************************************************
3251 * GetCurrentProcess (KERNEL32.@)
3253 * Get a handle to the current process.
3259 * A handle representing the current process.
3261 #undef GetCurrentProcess
3262 HANDLE WINAPI GetCurrentProcess(void)
3264 return (HANDLE)~(ULONG_PTR)0;
3267 /***********************************************************************
3268 * CmdBatNotification (KERNEL32.@)
3270 * Notifies the system that a batch file has started or finished.
3273 * bBatchRunning [I] TRUE if a batch file has started or
3274 * FALSE if a batch file has finished executing.
3279 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3281 FIXME("%d\n", bBatchRunning);
3286 /***********************************************************************
3287 * RegisterApplicationRestart (KERNEL32.@)
3289 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3291 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);