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;
81 HMODULE kernel32_handle = 0;
83 const WCHAR *DIR_Windows = NULL;
84 const WCHAR *DIR_System = NULL;
85 const WCHAR *DIR_SysWow64 = NULL;
88 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
89 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
90 #define PDB32_DOS_PROC 0x0010 /* Dos process */
91 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
92 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
93 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
95 static const WCHAR comW[] = {'.','c','o','m',0};
96 static const WCHAR batW[] = {'.','b','a','t',0};
97 static const WCHAR cmdW[] = {'.','c','m','d',0};
98 static const WCHAR pifW[] = {'.','p','i','f',0};
99 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
101 static void exec_process( LPCWSTR name );
103 extern void SHELL_LoadRegistry(void);
106 /***********************************************************************
109 static inline int contains_path( LPCWSTR name )
111 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
115 /***********************************************************************
118 * Check if an environment variable needs to be handled specially when
119 * passed through the Unix environment (i.e. prefixed with "WINE").
121 static inline int is_special_env_var( const char *var )
123 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
124 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
125 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
126 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
130 /***************************************************************************
133 * Get the path of a builtin module when the native file does not exist.
135 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
138 UINT len = strlenW( DIR_System );
140 if (contains_path( libname ))
142 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
143 filename, &file_part ) > size * sizeof(WCHAR))
144 return FALSE; /* too long */
146 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
148 while (filename[len] == '\\') len++;
149 if (filename + len != file_part) return FALSE;
153 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
154 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
155 file_part = filename + len;
156 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
157 strcpyW( file_part, libname );
159 if (ext && !strchrW( file_part, '.' ))
161 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
162 return FALSE; /* too long */
163 strcatW( file_part, ext );
169 /***********************************************************************
170 * open_builtin_exe_file
172 * Open an exe file for a builtin exe.
174 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
175 int test_only, int *file_exists )
177 char exename[MAX_PATH];
182 if ((p = strrchrW( name, '/' ))) name = p + 1;
183 if ((p = strrchrW( name, '\\' ))) name = p + 1;
185 /* we don't want to depend on the current codepage here */
186 len = strlenW( name ) + 1;
187 if (len >= sizeof(exename)) return NULL;
188 for (i = 0; i < len; i++)
190 if (name[i] > 127) return NULL;
191 exename[i] = (char)name[i];
192 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
194 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
198 /***********************************************************************
201 * Open a specific exe file, taking load order into account.
202 * Returns the file handle or 0 for a builtin exe.
204 static HANDLE open_exe_file( const WCHAR *name )
208 TRACE("looking for %s\n", debugstr_w(name) );
210 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
211 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
213 WCHAR buffer[MAX_PATH];
214 /* file doesn't exist, check for builtin */
215 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer) ))
222 /***********************************************************************
225 * Open an exe file, and return the full name and file handle.
226 * Returns FALSE if file could not be found.
227 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
228 * If file is a builtin exe, returns TRUE and sets handle to 0.
230 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
232 static const WCHAR exeW[] = {'.','e','x','e',0};
235 TRACE("looking for %s\n", debugstr_w(name) );
237 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
238 !get_builtin_path( name, exeW, buffer, buflen ))
240 /* no builtin found, try native without extension in case it is a Unix app */
242 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
244 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
245 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
246 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
252 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
253 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
254 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
257 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
258 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
269 /***********************************************************************
270 * build_initial_environment
272 * Build the Win32 environment from the Unix environment
274 static BOOL build_initial_environment(void)
280 char **env = __wine_get_main_environment();
282 /* Compute the total size of the Unix environment */
283 for (e = env; *e; e++)
285 if (is_special_env_var( *e )) continue;
286 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
288 size *= sizeof(WCHAR);
290 /* Now allocate the environment */
292 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
293 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
296 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
297 endptr = p + size / sizeof(WCHAR);
299 /* And fill it with the Unix environment */
300 for (e = env; *e; e++)
304 /* skip Unix special variables and use the Wine variants instead */
305 if (!strncmp( str, "WINE", 4 ))
307 if (is_special_env_var( str + 4 )) str += 4;
308 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
310 else if (is_special_env_var( str )) continue; /* skip it */
312 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
320 /***********************************************************************
321 * set_registry_variables
323 * Set environment variables by enumerating the values of a key;
324 * helper for set_registry_environment().
325 * Note that Windows happily truncates the value if it's too big.
327 static void set_registry_variables( HANDLE hkey, ULONG type )
329 UNICODE_STRING env_name, env_value;
333 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
334 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
336 for (index = 0; ; index++)
338 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
339 buffer, sizeof(buffer), &size );
340 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
342 if (info->Type != type)
344 env_name.Buffer = info->Name;
345 env_name.Length = env_name.MaximumLength = info->NameLength;
346 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
347 env_value.Length = env_value.MaximumLength = info->DataLength;
348 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
349 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
350 if (info->Type == REG_EXPAND_SZ)
352 WCHAR buf_expanded[1024];
353 UNICODE_STRING env_expanded;
354 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
355 env_expanded.Buffer=buf_expanded;
356 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
357 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
358 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
362 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
368 /***********************************************************************
369 * set_registry_environment
371 * Set the environment variables specified in the registry.
373 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
374 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
375 * on the order in which the variables are processed. But on Windows it
376 * does not really matter since they only use %SystemDrive% and
377 * %SystemRoot% which are predefined. But Wine defines these in the
378 * registry, so we need two passes.
380 static BOOL set_registry_environment(void)
382 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
383 'S','y','s','t','e','m','\\',
384 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
385 'C','o','n','t','r','o','l','\\',
386 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
387 'E','n','v','i','r','o','n','m','e','n','t',0};
388 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
390 OBJECT_ATTRIBUTES attr;
391 UNICODE_STRING nameW;
395 attr.Length = sizeof(attr);
396 attr.RootDirectory = 0;
397 attr.ObjectName = &nameW;
399 attr.SecurityDescriptor = NULL;
400 attr.SecurityQualityOfService = NULL;
402 /* first the system environment variables */
403 RtlInitUnicodeString( &nameW, env_keyW );
404 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
406 set_registry_variables( hkey, REG_SZ );
407 set_registry_variables( hkey, REG_EXPAND_SZ );
412 /* then the ones for the current user */
413 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
414 RtlInitUnicodeString( &nameW, envW );
415 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
417 set_registry_variables( hkey, REG_SZ );
418 set_registry_variables( hkey, REG_EXPAND_SZ );
421 NtClose( attr.RootDirectory );
426 /***********************************************************************
429 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
431 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
432 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
433 DWORD len, size = sizeof(buffer);
435 UNICODE_STRING nameW;
437 RtlInitUnicodeString( &nameW, name );
438 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
441 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
442 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
444 if (info->Type == REG_EXPAND_SZ)
446 UNICODE_STRING value, expanded;
448 value.MaximumLength = len * sizeof(WCHAR);
449 value.Buffer = (WCHAR *)info->Data;
450 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
451 value.Length = len * sizeof(WCHAR);
452 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
453 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
454 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
455 else RtlFreeUnicodeString( &expanded );
457 else if (info->Type == REG_SZ)
459 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
461 memcpy( ret, info->Data, len * sizeof(WCHAR) );
469 /***********************************************************************
470 * set_additional_environment
472 * Set some additional environment variables not specified in the registry.
474 static void set_additional_environment(void)
476 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
477 'S','o','f','t','w','a','r','e','\\',
478 'M','i','c','r','o','s','o','f','t','\\',
479 'W','i','n','d','o','w','s',' ','N','T','\\',
480 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
481 'P','r','o','f','i','l','e','L','i','s','t',0};
482 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
483 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
484 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
485 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
486 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
487 OBJECT_ATTRIBUTES attr;
488 UNICODE_STRING nameW;
489 WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
491 const char *name = wine_get_user_name();
494 /* set the USERNAME variable */
496 len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
499 user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
500 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
501 SetEnvironmentVariableW( usernameW, user_name );
503 else WARN( "user name %s not convertible.\n", debugstr_a(name) );
505 /* set the USERPROFILE and ALLUSERSPROFILE variables */
507 attr.Length = sizeof(attr);
508 attr.RootDirectory = 0;
509 attr.ObjectName = &nameW;
511 attr.SecurityDescriptor = NULL;
512 attr.SecurityQualityOfService = NULL;
513 RtlInitUnicodeString( &nameW, profile_keyW );
514 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
516 profile_dir = get_reg_value( hkey, profiles_valueW );
517 all_users_dir = get_reg_value( hkey, all_users_valueW );
525 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
526 len += strlenW(profile_dir) + 1;
527 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
528 strcpyW( value, profile_dir );
529 p = value + strlenW(value);
530 if (p > value && p[-1] != '\\') *p++ = '\\';
532 strcpyW( p, user_name );
533 SetEnvironmentVariableW( userprofileW, value );
537 strcpyW( p, all_users_dir );
538 SetEnvironmentVariableW( allusersW, value );
540 HeapFree( GetProcessHeap(), 0, value );
543 HeapFree( GetProcessHeap(), 0, all_users_dir );
544 HeapFree( GetProcessHeap(), 0, profile_dir );
545 HeapFree( GetProcessHeap(), 0, user_name );
548 /***********************************************************************
551 * Set the Wine library Unicode argv global variables.
553 static void set_library_wargv( char **argv )
561 for (argc = 0; argv[argc]; argc++)
562 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
564 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
565 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
566 p = (WCHAR *)(wargv + argc + 1);
567 for (argc = 0; argv[argc]; argc++)
569 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
576 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
578 for (argc = 0; wargv[argc]; argc++)
579 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
581 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
582 q = (char *)(argv + argc + 1);
583 for (argc = 0; wargv[argc]; argc++)
585 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
592 __wine_main_argc = argc;
593 __wine_main_argv = argv;
594 __wine_main_wargv = wargv;
598 /***********************************************************************
599 * update_library_argv0
601 * Update the argv[0] global variable with the binary we have found.
603 static void update_library_argv0( const WCHAR *argv0 )
605 DWORD len = strlenW( argv0 );
607 if (len > strlenW( __wine_main_wargv[0] ))
609 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
611 strcpyW( __wine_main_wargv[0], argv0 );
613 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
614 if (len > strlen( __wine_main_argv[0] ) + 1)
616 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
618 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
622 /***********************************************************************
625 * Build the command line of a process from the argv array.
627 * Note that it does NOT necessarily include the file name.
628 * Sometimes we don't even have any command line options at all.
630 * We must quote and escape characters so that the argv array can be rebuilt
631 * from the command line:
632 * - spaces and tabs must be quoted
634 * - quotes must be escaped
636 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
637 * resulting in an odd number of '\' followed by a '"'
640 * - '\'s that are not followed by a '"' can be left as is
644 static BOOL build_command_line( WCHAR **argv )
649 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
651 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
654 for (arg = argv; *arg; arg++)
656 int has_space,bcount;
662 if( !*a ) has_space=1;
667 if (*a==' ' || *a=='\t') {
669 } else if (*a=='"') {
670 /* doubling of '\' preceding a '"',
671 * plus escaping of said '"'
679 len+=(a-*arg)+1 /* for the separating space */;
681 len+=2; /* for the quotes */
684 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
687 p = rupp->CommandLine.Buffer;
688 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
689 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
690 for (arg = argv; *arg; arg++)
692 int has_space,has_quote;
695 /* Check for quotes and spaces in this argument */
696 has_space=has_quote=0;
698 if( !*a ) has_space=1;
700 if (*a==' ' || *a=='\t') {
704 } else if (*a=='"') {
712 /* Now transfer it to the command line */
729 /* Double all the '\\' preceding this '"', plus one */
730 for (i=0;i<=bcount;i++)
742 while ((*p=*x++)) p++;
748 if (p > rupp->CommandLine.Buffer)
749 p--; /* remove last space */
756 /***********************************************************************
757 * init_current_directory
759 * Initialize the current directory from the Unix cwd or the parent info.
761 static void init_current_directory( CURDIR *cur_dir )
763 UNICODE_STRING dir_str;
767 /* if we received a cur dir from the parent, try this first */
769 if (cur_dir->DosPath.Length)
771 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
774 /* now try to get it from the Unix cwd */
776 for (size = 256; ; size *= 2)
778 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
779 if (getcwd( cwd, size )) break;
780 HeapFree( GetProcessHeap(), 0, cwd );
781 if (errno == ERANGE) continue;
789 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
790 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
792 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
793 RtlInitUnicodeString( &dir_str, dirW );
794 RtlSetCurrentDirectory_U( &dir_str );
795 RtlFreeUnicodeString( &dir_str );
799 if (!cur_dir->DosPath.Length) /* still not initialized */
801 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
802 "starting in the Windows directory.\n", cwd ? cwd : "" );
803 RtlInitUnicodeString( &dir_str, DIR_Windows );
804 RtlSetCurrentDirectory_U( &dir_str );
806 HeapFree( GetProcessHeap(), 0, cwd );
809 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
810 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
814 /***********************************************************************
817 * Initialize the windows and system directories from the environment.
819 static void init_windows_dirs(void)
821 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
823 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
824 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
825 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
826 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
827 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
832 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
834 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
835 GetEnvironmentVariableW( windirW, buffer, len );
836 DIR_Windows = buffer;
838 else DIR_Windows = default_windirW;
840 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
842 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
843 GetEnvironmentVariableW( winsysdirW, buffer, len );
848 len = strlenW( DIR_Windows );
849 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
850 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
851 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
855 #ifndef _WIN64 /* SysWow64 is always defined on 64-bit */
859 len = strlenW( DIR_Windows );
860 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
861 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
862 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
863 DIR_SysWow64 = buffer;
866 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
867 ERR( "directory %s could not be created, error %u\n",
868 debugstr_w(DIR_Windows), GetLastError() );
869 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
870 ERR( "directory %s could not be created, error %u\n",
871 debugstr_w(DIR_System), GetLastError() );
873 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
874 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
876 /* set the directories in ntdll too */
877 __wine_init_windows_dir( DIR_Windows, DIR_System );
881 /***********************************************************************
884 * Start the wineboot process if necessary. Return the event to wait on.
886 static HANDLE start_wineboot(void)
888 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
891 if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
893 ERR( "failed to create wineboot event, expect trouble\n" );
896 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
898 static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
900 PROCESS_INFORMATION pi;
901 WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];
903 memset( &si, 0, sizeof(si) );
905 si.dwFlags = STARTF_USESTDHANDLES;
908 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
910 GetSystemDirectoryW( cmdline, MAX_PATH );
911 lstrcatW( cmdline, command_line );
912 if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
914 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
915 CloseHandle( pi.hThread );
916 CloseHandle( pi.hProcess );
919 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
925 /***********************************************************************
928 * Startup routine of a new process. Runs on the new process stack.
930 static void start_process( void *arg )
934 PEB *peb = NtCurrentTeb()->Peb;
935 IMAGE_NT_HEADERS *nt;
936 LPTHREAD_START_ROUTINE entry;
938 nt = RtlImageNtHeader( peb->ImageBaseAddress );
939 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
940 nt->OptionalHeader.AddressOfEntryPoint);
942 if (!nt->OptionalHeader.AddressOfEntryPoint)
944 ERR( "%s doesn't have an entry point, it cannot be executed\n",
945 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
950 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
951 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
953 SetLastError( 0 ); /* clear error code */
954 if (peb->BeingDebugged) DbgBreakPoint();
955 ExitThread( entry( peb ) );
957 __EXCEPT(UnhandledExceptionFilter)
959 TerminateThread( GetCurrentThread(), GetExceptionCode() );
965 /***********************************************************************
968 * Change the process name in the ps output.
970 static void set_process_name( int argc, char *argv[] )
972 #ifdef HAVE_SETPROCTITLE
973 setproctitle("-%s", argv[1]);
978 char *p, *prctl_name = argv[1];
979 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
982 # define PR_SET_NAME 15
985 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
986 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
988 if (prctl( PR_SET_NAME, prctl_name ) != -1)
990 offset = argv[1] - argv[0];
991 memmove( argv[1] - offset, argv[1], end - argv[1] );
992 memset( end - offset, 0, offset );
993 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
997 #endif /* HAVE_PRCTL */
1000 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1005 /***********************************************************************
1006 * __wine_kernel_init
1008 * Wine initialisation: load and start the main exe file.
1010 void CDECL __wine_kernel_init(void)
1012 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1013 static const WCHAR dotW[] = {'.',0};
1014 static const WCHAR exeW[] = {'.','e','x','e',0};
1016 WCHAR *p, main_exe_name[MAX_PATH+1];
1017 PEB *peb = NtCurrentTeb()->Peb;
1018 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1019 HANDLE boot_event = 0;
1020 BOOL got_environment = TRUE;
1022 /* Initialize everything */
1024 setbuf(stdout,NULL);
1025 setbuf(stderr,NULL);
1026 kernel32_handle = GetModuleHandleW(kernel32W);
1027 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1031 if (!params->Environment)
1033 /* Copy the parent environment */
1034 if (!build_initial_environment()) exit(1);
1036 /* convert old configuration to new format */
1037 convert_old_config();
1039 got_environment = set_registry_environment();
1040 set_additional_environment();
1043 init_windows_dirs();
1044 init_current_directory( ¶ms->CurrentDirectory );
1046 set_process_name( __wine_main_argc, __wine_main_argv );
1047 set_library_wargv( __wine_main_argv );
1049 if (peb->ProcessParameters->ImagePathName.Buffer)
1051 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1055 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1056 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1058 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1059 ExitProcess( GetLastError() );
1061 update_library_argv0( main_exe_name );
1062 if (!build_command_line( __wine_main_wargv )) goto error;
1063 boot_event = start_wineboot();
1066 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1067 p = strrchrW( main_exe_name, '.' );
1068 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1070 TRACE( "starting process name=%s argv[0]=%s\n",
1071 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1073 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1074 MODULE_get_dll_load_path(main_exe_name) );
1078 if (WaitForSingleObject( boot_event, 30000 )) ERR( "boot event wait timed out\n" );
1079 CloseHandle( boot_event );
1080 /* if we didn't find environment section, try again now that wineboot has run */
1081 if (!got_environment)
1083 set_registry_environment();
1084 set_additional_environment();
1088 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1091 DWORD error = GetLastError();
1093 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1094 if (error == ERROR_BAD_EXE_FORMAT ||
1095 error == ERROR_INVALID_ADDRESS ||
1096 error == ERROR_NOT_ENOUGH_MEMORY)
1098 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1099 /* if we get back here, it failed */
1101 else if (error == ERROR_MOD_NOT_FOUND)
1103 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1104 else p = main_exe_name;
1105 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1107 /* args 1 and 2 are --app-name full_path */
1108 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1109 debugstr_w(__wine_main_wargv[3]) );
1110 ExitProcess( ERROR_BAD_EXE_FORMAT );
1113 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1114 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1115 ExitProcess( error );
1118 LdrInitializeThunk( 0, 0, 0, 0 );
1119 /* switch to the new stack */
1120 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1123 ExitProcess( GetLastError() );
1127 /***********************************************************************
1130 * Build an argv array from a command-line.
1131 * 'reserved' is the number of args to reserve before the first one.
1133 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1137 char *arg,*s,*d,*cmdline;
1138 int in_quotes,bcount,len;
1140 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1141 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1142 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1149 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1152 /* skip the remaining spaces */
1153 while (*s==' ' || *s=='\t') {
1160 } else if (*s=='\\') {
1161 /* '\', count them */
1163 } else if ((*s=='"') && ((bcount & 1)==0)) {
1165 in_quotes=!in_quotes;
1168 /* a regular character */
1173 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1175 HeapFree( GetProcessHeap(), 0, cmdline );
1179 arg = d = s = (char *)(argv + argc);
1180 memcpy( d, cmdline, len );
1185 if ((*s==' ' || *s=='\t') && !in_quotes) {
1186 /* Close the argument and copy it */
1190 /* skip the remaining spaces */
1193 } while (*s==' ' || *s=='\t');
1195 /* Start with a new argument */
1198 } else if (*s=='\\') {
1202 } else if (*s=='"') {
1204 if ((bcount & 1)==0) {
1205 /* Preceded by an even number of '\', this is half that
1206 * number of '\', plus a '"' which we discard.
1210 in_quotes=!in_quotes;
1212 /* Preceded by an odd number of '\', this is half that
1213 * number of '\' followed by a '"'
1221 /* a regular character */
1232 HeapFree( GetProcessHeap(), 0, cmdline );
1237 /***********************************************************************
1240 * Build the environment of a new child process.
1242 static char **build_envp( const WCHAR *envW )
1244 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1249 int count = 1, length;
1252 for (end = envW; *end; count++) end += strlenW(end) + 1;
1254 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1255 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1256 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1258 for (p = env; *p; p += strlen(p) + 1)
1259 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1261 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1263 if (!(p = getenv(unix_vars[i]))) continue;
1264 length += strlen(unix_vars[i]) + strlen(p) + 2;
1268 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1270 char **envptr = envp;
1271 char *dst = (char *)(envp + count);
1273 /* some variables must not be modified, so we get them directly from the unix env */
1274 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1276 if (!(p = getenv(unix_vars[i]))) continue;
1277 *envptr++ = strcpy( dst, unix_vars[i] );
1280 dst += strlen(dst) + 1;
1283 /* now put the Windows environment strings */
1284 for (p = env; *p; p += strlen(p) + 1)
1286 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1287 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1288 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1289 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1290 if (is_special_env_var( p )) /* prefix it with "WINE" */
1292 *envptr++ = strcpy( dst, "WINE" );
1297 *envptr++ = strcpy( dst, p );
1299 dst += strlen(dst) + 1;
1303 HeapFree( GetProcessHeap(), 0, env );
1308 /***********************************************************************
1311 * Fork and exec a new Unix binary, checking for errors.
1313 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1314 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1316 int fd[2], stdin_fd = -1, stdout_fd = -1;
1318 char **argv, **envp;
1320 if (!env) env = GetEnvironmentStringsW();
1323 if (pipe2( fd, O_CLOEXEC ) == -1)
1328 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1331 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1332 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1335 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1337 HANDLE hstdin, hstdout;
1339 if (startup->dwFlags & STARTF_USESTDHANDLES)
1341 hstdin = startup->hStdInput;
1342 hstdout = startup->hStdOutput;
1346 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1347 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1350 if (is_console_handle( hstdin ))
1351 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1352 if (is_console_handle( hstdout ))
1353 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1354 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1355 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1358 argv = build_argv( cmdline, 0 );
1359 envp = build_envp( env );
1361 if (!(pid = fork())) /* child */
1365 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1368 if (!(pid = fork()))
1370 int fd = open( "/dev/null", O_RDWR );
1372 /* close stdin and stdout */
1380 else if (pid != -1) _exit(0); /* parent */
1386 dup2( stdin_fd, 0 );
1389 if (stdout_fd != -1)
1391 dup2( stdout_fd, 1 );
1396 /* Reset signals that we previously set to SIG_IGN */
1397 signal( SIGPIPE, SIG_DFL );
1398 signal( SIGCHLD, SIG_DFL );
1400 if (newdir) chdir(newdir);
1402 if (argv && envp) execve( filename, argv, envp );
1404 write( fd[1], &err, sizeof(err) );
1407 HeapFree( GetProcessHeap(), 0, argv );
1408 HeapFree( GetProcessHeap(), 0, envp );
1409 if (stdin_fd != -1) close( stdin_fd );
1410 if (stdout_fd != -1) close( stdout_fd );
1412 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1417 if (pid == -1) FILE_SetDosError();
1423 /***********************************************************************
1424 * create_user_params
1426 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1427 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1428 const STARTUPINFOW *startup )
1430 RTL_USER_PROCESS_PARAMETERS *params;
1431 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1433 WCHAR buffer[MAX_PATH];
1435 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1436 lstrcpynW( buffer, filename, MAX_PATH );
1437 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1438 lstrcpynW( buffer, filename, MAX_PATH );
1439 RtlInitUnicodeString( &image_str, buffer );
1441 RtlInitUnicodeString( &cmdline_str, cmdline );
1442 newdir.Buffer = NULL;
1445 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1447 /* skip \??\ prefix */
1448 curdir_str.Buffer = newdir.Buffer + 4;
1449 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1450 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1452 else cur_dir = NULL;
1454 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1455 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1456 if (startup->lpReserved2 && startup->cbReserved2)
1459 runtime.MaximumLength = startup->cbReserved2;
1460 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1463 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1464 cur_dir ? &curdir_str : NULL,
1466 startup->lpTitle ? &title : NULL,
1467 startup->lpDesktop ? &desktop : NULL,
1469 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1470 RtlFreeUnicodeString( &newdir );
1471 if (status != STATUS_SUCCESS)
1473 SetLastError( RtlNtStatusToDosError(status) );
1477 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1478 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1480 if (startup->dwFlags & STARTF_USESTDHANDLES)
1482 params->hStdInput = startup->hStdInput;
1483 params->hStdOutput = startup->hStdOutput;
1484 params->hStdError = startup->hStdError;
1488 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1489 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1490 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1492 params->dwX = startup->dwX;
1493 params->dwY = startup->dwY;
1494 params->dwXSize = startup->dwXSize;
1495 params->dwYSize = startup->dwYSize;
1496 params->dwXCountChars = startup->dwXCountChars;
1497 params->dwYCountChars = startup->dwYCountChars;
1498 params->dwFillAttribute = startup->dwFillAttribute;
1499 params->dwFlags = startup->dwFlags;
1500 params->wShowWindow = startup->wShowWindow;
1505 /***********************************************************************
1508 * Create a new process. If hFile is a valid handle we have an exe
1509 * file, otherwise it is a Winelib app.
1511 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1512 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1513 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1514 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1515 void *res_start, void *res_end, DWORD binary_type, int exec_only )
1517 BOOL ret, success = FALSE;
1518 HANDLE process_info, hstdin, hstdout;
1520 char *winedebug = NULL;
1522 RTL_USER_PROCESS_PARAMETERS *params;
1523 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1527 if (sizeof(void *) == sizeof(int) && !is_wow64 && (binary_type & BINARY_FLAG_64BIT))
1529 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename) );
1530 SetLastError( ERROR_BAD_EXE_FORMAT );
1534 if (!env) RtlAcquirePebLock();
1536 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1538 if (!env) RtlReleasePebLock();
1541 env_end = params->Environment;
1544 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1545 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1547 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1548 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1549 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1551 env_end += strlenW(env_end) + 1;
1555 /* create the socket for the new process */
1557 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1559 if (!env) RtlReleasePebLock();
1560 HeapFree( GetProcessHeap(), 0, winedebug );
1561 RtlDestroyProcessParameters( params );
1562 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1565 wine_server_send_fd( socketfd[1] );
1566 close( socketfd[1] );
1568 /* create the process on the server side */
1570 SERVER_START_REQ( new_process )
1572 req->inherit_all = inherit;
1573 req->create_flags = flags;
1574 req->socket_fd = socketfd[1];
1575 req->exe_file = wine_server_obj_handle( hFile );
1576 req->process_access = PROCESS_ALL_ACCESS;
1577 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1578 req->thread_access = THREAD_ALL_ACCESS;
1579 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1580 req->hstdin = wine_server_obj_handle( params->hStdInput );
1581 req->hstdout = wine_server_obj_handle( params->hStdOutput );
1582 req->hstderr = wine_server_obj_handle( params->hStdError );
1584 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1586 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1587 if (is_console_handle(params->hStdInput)) req->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1588 if (is_console_handle(params->hStdOutput)) req->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1589 if (is_console_handle(params->hStdError)) req->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1590 hstdin = hstdout = 0;
1594 if (is_console_handle(params->hStdInput)) req->hstdin = console_handle_unmap(params->hStdInput);
1595 if (is_console_handle(params->hStdOutput)) req->hstdout = console_handle_unmap(params->hStdOutput);
1596 if (is_console_handle(params->hStdError)) req->hstderr = console_handle_unmap(params->hStdError);
1597 hstdin = wine_server_ptr_handle( req->hstdin );
1598 hstdout = wine_server_ptr_handle( req->hstdout );
1601 wine_server_add_data( req, params, params->Size );
1602 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1603 if ((ret = !wine_server_call_err( req )))
1605 info->dwProcessId = (DWORD)reply->pid;
1606 info->dwThreadId = (DWORD)reply->tid;
1607 info->hProcess = wine_server_ptr_handle( reply->phandle );
1608 info->hThread = wine_server_ptr_handle( reply->thandle );
1610 process_info = wine_server_ptr_handle( reply->info );
1614 if (!env) RtlReleasePebLock();
1615 RtlDestroyProcessParameters( params );
1618 close( socketfd[0] );
1619 HeapFree( GetProcessHeap(), 0, winedebug );
1623 if (hstdin) wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1624 if (hstdout) wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1626 /* create the child process */
1627 argv = build_argv( cmd_line, 1 );
1629 if (exec_only || !(pid = fork())) /* child */
1631 char preloader_reserve[64], socket_env[64];
1633 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1635 if (!(pid = fork()))
1637 int fd = open( "/dev/null", O_RDWR );
1639 /* close stdin and stdout */
1647 else if (pid != -1) _exit(0); /* parent */
1651 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1652 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1655 if (stdin_fd != -1) close( stdin_fd );
1656 if (stdout_fd != -1) close( stdout_fd );
1658 /* Reset signals that we previously set to SIG_IGN */
1659 signal( SIGPIPE, SIG_DFL );
1660 signal( SIGCHLD, SIG_DFL );
1662 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1663 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1664 (unsigned long)res_start, (unsigned long)res_end );
1666 putenv( preloader_reserve );
1667 putenv( socket_env );
1668 if (winedebug) putenv( winedebug );
1669 if (unixdir) chdir(unixdir);
1671 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1675 /* this is the parent */
1677 if (stdin_fd != -1) close( stdin_fd );
1678 if (stdout_fd != -1) close( stdout_fd );
1679 close( socketfd[0] );
1680 HeapFree( GetProcessHeap(), 0, argv );
1681 HeapFree( GetProcessHeap(), 0, winedebug );
1688 /* wait for the new process info to be ready */
1690 WaitForSingleObject( process_info, INFINITE );
1691 SERVER_START_REQ( get_new_process_info )
1693 req->info = wine_server_obj_handle( process_info );
1694 wine_server_call( req );
1695 success = reply->success;
1696 err = reply->exit_code;
1702 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1705 CloseHandle( process_info );
1709 CloseHandle( process_info );
1710 CloseHandle( info->hProcess );
1711 CloseHandle( info->hThread );
1712 info->hProcess = info->hThread = 0;
1713 info->dwProcessId = info->dwThreadId = 0;
1718 /***********************************************************************
1719 * create_vdm_process
1721 * Create a new VDM process for a 16-bit or DOS application.
1723 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1724 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1725 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1726 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1727 DWORD binary_type, int exec_only )
1729 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1732 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1733 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1737 SetLastError( ERROR_OUTOFMEMORY );
1740 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1741 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1742 flags, startup, info, unixdir, NULL, NULL, binary_type, exec_only );
1743 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1748 /***********************************************************************
1749 * create_cmd_process
1751 * Create a new cmd shell process for a .BAT file.
1753 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1754 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1755 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1756 LPPROCESS_INFORMATION info )
1759 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1760 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1761 WCHAR comspec[MAX_PATH];
1765 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1767 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1768 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1771 strcpyW( newcmdline, comspec );
1772 strcatW( newcmdline, slashcW );
1773 strcatW( newcmdline, cmd_line );
1774 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1775 flags, env, cur_dir, startup, info );
1776 HeapFree( GetProcessHeap(), 0, newcmdline );
1781 /*************************************************************************
1784 * Helper for CreateProcess: retrieve the file name to load from the
1785 * app name and command line. Store the file name in buffer, and
1786 * return a possibly modified command line.
1787 * Also returns a handle to the opened file if it's a Windows binary.
1789 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1790 int buflen, HANDLE *handle )
1792 static const WCHAR quotesW[] = {'"','%','s','"',0};
1794 WCHAR *name, *pos, *ret = NULL;
1798 /* if we have an app name, everything is easy */
1802 /* use the unmodified app name as file name */
1803 lstrcpynW( buffer, appname, buflen );
1804 *handle = open_exe_file( buffer );
1805 if (!(ret = cmdline) || !cmdline[0])
1807 /* no command-line, create one */
1808 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1809 sprintfW( ret, quotesW, appname );
1814 /* first check for a quoted file name */
1816 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1818 int len = p - cmdline - 1;
1819 /* extract the quoted portion as file name */
1820 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1821 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1824 if (find_exe_file( name, buffer, buflen, handle ))
1825 ret = cmdline; /* no change necessary */
1829 /* now try the command-line word by word */
1831 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1839 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1841 if (find_exe_file( name, buffer, buflen, handle ))
1846 if (*p) got_space = TRUE;
1849 if (ret && got_space) /* now build a new command-line with quotes */
1851 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1853 sprintfW( ret, quotesW, name );
1856 else if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1859 HeapFree( GetProcessHeap(), 0, name );
1864 /**********************************************************************
1865 * CreateProcessA (KERNEL32.@)
1867 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1868 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1869 DWORD flags, LPVOID env, LPCSTR cur_dir,
1870 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1873 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1874 UNICODE_STRING desktopW, titleW;
1877 desktopW.Buffer = NULL;
1878 titleW.Buffer = NULL;
1879 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1880 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1881 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1883 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1884 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1886 memcpy( &infoW, startup_info, sizeof(infoW) );
1887 infoW.lpDesktop = desktopW.Buffer;
1888 infoW.lpTitle = titleW.Buffer;
1890 if (startup_info->lpReserved)
1891 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1892 debugstr_a(startup_info->lpReserved));
1894 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1895 inherit, flags, env, cur_dirW, &infoW, info );
1897 HeapFree( GetProcessHeap(), 0, app_nameW );
1898 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1899 HeapFree( GetProcessHeap(), 0, cur_dirW );
1900 RtlFreeUnicodeString( &desktopW );
1901 RtlFreeUnicodeString( &titleW );
1906 /**********************************************************************
1907 * CreateProcessW (KERNEL32.@)
1909 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1910 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1911 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1912 LPPROCESS_INFORMATION info )
1916 char *unixdir = NULL;
1917 WCHAR name[MAX_PATH];
1918 WCHAR *tidy_cmdline, *p, *envW = env;
1919 void *res_start, *res_end;
1922 /* Process the AppName and/or CmdLine to get module name and path */
1924 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1926 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1928 if (hFile == INVALID_HANDLE_VALUE) goto done;
1930 /* Warn if unsupported features are used */
1932 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1933 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1934 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1935 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1936 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1940 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1942 SetLastError(ERROR_DIRECTORY);
1948 WCHAR buf[MAX_PATH];
1949 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1952 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1957 while (*p) p += strlen(p) + 1;
1958 p++; /* final null */
1959 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1960 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1961 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1962 flags |= CREATE_UNICODE_ENVIRONMENT;
1965 info->hThread = info->hProcess = 0;
1966 info->dwProcessId = info->dwThreadId = 0;
1968 /* Determine executable type */
1970 if (!hFile) /* builtin exe */
1972 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1973 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1974 inherit, flags, startup_info, info, unixdir, NULL, NULL,
1975 BINARY_UNIX_LIB, FALSE );
1979 binary_type = MODULE_GetBinaryType( hFile, &res_start, &res_end );
1980 if (binary_type & BINARY_FLAG_DLL)
1982 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1983 SetLastError( ERROR_BAD_EXE_FORMAT );
1985 else switch (binary_type & BINARY_TYPE_MASK)
1988 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1989 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1990 inherit, flags, startup_info, info, unixdir,
1991 res_start, res_end, binary_type, FALSE );
1996 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1997 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1998 inherit, flags, startup_info, info, unixdir, binary_type, FALSE );
2000 case BINARY_UNIX_LIB:
2001 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2002 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2003 inherit, flags, startup_info, info, unixdir,
2004 NULL, NULL, binary_type, FALSE );
2006 case BINARY_UNKNOWN:
2007 /* check for .com or .bat extension */
2008 if ((p = strrchrW( name, '.' )))
2010 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2012 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2013 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2014 inherit, flags, startup_info, info, unixdir,
2015 binary_type, FALSE );
2018 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2020 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2021 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2022 inherit, flags, startup_info, info );
2027 case BINARY_UNIX_EXE:
2029 /* unknown file, try as unix executable */
2032 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2034 if ((unix_name = wine_get_unix_file_name( name )))
2036 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2037 HeapFree( GetProcessHeap(), 0, unix_name );
2042 CloseHandle( hFile );
2045 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2046 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2047 HeapFree( GetProcessHeap(), 0, unixdir );
2049 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2054 /**********************************************************************
2057 static void exec_process( LPCWSTR name )
2061 void *res_start, *res_end;
2062 STARTUPINFOW startup_info;
2063 PROCESS_INFORMATION info;
2066 hFile = open_exe_file( name );
2067 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2069 memset( &startup_info, 0, sizeof(startup_info) );
2070 startup_info.cb = sizeof(startup_info);
2072 /* Determine executable type */
2074 binary_type = MODULE_GetBinaryType( hFile, &res_start, &res_end );
2075 if (binary_type & BINARY_FLAG_DLL) return;
2076 switch (binary_type & BINARY_TYPE_MASK)
2079 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
2080 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2081 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, binary_type, TRUE );
2083 case BINARY_UNIX_LIB:
2084 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2085 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2086 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, binary_type, TRUE );
2088 case BINARY_UNKNOWN:
2089 /* check for .com or .pif extension */
2090 if (!(p = strrchrW( name, '.' ))) break;
2091 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2096 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2097 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2098 FALSE, 0, &startup_info, &info, NULL, binary_type, TRUE );
2103 CloseHandle( hFile );
2107 /***********************************************************************
2110 * Wrapper to call WaitForInputIdle USER function
2112 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2114 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2116 HMODULE mod = GetModuleHandleA( "user32.dll" );
2119 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2120 if (ptr) return ptr( process, timeout );
2126 /***********************************************************************
2127 * WinExec (KERNEL32.@)
2129 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2131 PROCESS_INFORMATION info;
2132 STARTUPINFOA startup;
2136 memset( &startup, 0, sizeof(startup) );
2137 startup.cb = sizeof(startup);
2138 startup.dwFlags = STARTF_USESHOWWINDOW;
2139 startup.wShowWindow = nCmdShow;
2141 /* cmdline needs to be writable for CreateProcess */
2142 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2143 strcpy( cmdline, lpCmdLine );
2145 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2146 0, NULL, NULL, &startup, &info ))
2148 /* Give 30 seconds to the app to come up */
2149 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2150 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2152 /* Close off the handles */
2153 CloseHandle( info.hThread );
2154 CloseHandle( info.hProcess );
2156 else if ((ret = GetLastError()) >= 32)
2158 FIXME("Strange error set by CreateProcess: %d\n", ret );
2161 HeapFree( GetProcessHeap(), 0, cmdline );
2166 /**********************************************************************
2167 * LoadModule (KERNEL32.@)
2169 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2171 LOADPARMS32 *params = paramBlock;
2172 PROCESS_INFORMATION info;
2173 STARTUPINFOA startup;
2174 HINSTANCE hInstance;
2176 char filename[MAX_PATH];
2179 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2181 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2182 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2183 return ULongToHandle(GetLastError());
2185 len = (BYTE)params->lpCmdLine[0];
2186 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2187 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2189 strcpy( cmdline, filename );
2190 p = cmdline + strlen(cmdline);
2192 memcpy( p, params->lpCmdLine + 1, len );
2195 memset( &startup, 0, sizeof(startup) );
2196 startup.cb = sizeof(startup);
2197 if (params->lpCmdShow)
2199 startup.dwFlags = STARTF_USESHOWWINDOW;
2200 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2203 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2204 params->lpEnvAddress, NULL, &startup, &info ))
2206 /* Give 30 seconds to the app to come up */
2207 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2208 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2209 hInstance = (HINSTANCE)33;
2210 /* Close off the handles */
2211 CloseHandle( info.hThread );
2212 CloseHandle( info.hProcess );
2214 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2216 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2217 hInstance = (HINSTANCE)11;
2220 HeapFree( GetProcessHeap(), 0, cmdline );
2225 /******************************************************************************
2226 * TerminateProcess (KERNEL32.@)
2228 * Terminates a process.
2231 * handle [I] Process to terminate.
2232 * exit_code [I] Exit code.
2236 * Failure: FALSE, check GetLastError().
2238 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2240 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2241 if (status) SetLastError( RtlNtStatusToDosError(status) );
2245 /***********************************************************************
2246 * ExitProcess (KERNEL32.@)
2248 * Exits the current process.
2251 * status [I] Status code to exit with.
2257 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2259 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2260 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2261 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2263 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2267 void WINAPI process_ExitProcess( DWORD status )
2269 LdrShutdownProcess();
2270 NtTerminateProcess(GetCurrentProcess(), status);
2276 void WINAPI ExitProcess( DWORD status )
2278 LdrShutdownProcess();
2279 NtTerminateProcess(GetCurrentProcess(), status);
2285 /***********************************************************************
2286 * GetExitCodeProcess [KERNEL32.@]
2288 * Gets termination status of specified process.
2291 * hProcess [in] Handle to the process.
2292 * lpExitCode [out] Address to receive termination status.
2298 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2301 PROCESS_BASIC_INFORMATION pbi;
2303 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2305 if (status == STATUS_SUCCESS)
2307 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2310 SetLastError( RtlNtStatusToDosError(status) );
2315 /***********************************************************************
2316 * SetErrorMode (KERNEL32.@)
2318 UINT WINAPI SetErrorMode( UINT mode )
2320 UINT old = process_error_mode;
2321 process_error_mode = mode;
2325 /***********************************************************************
2326 * GetErrorMode (KERNEL32.@)
2328 UINT WINAPI GetErrorMode( void )
2330 return process_error_mode;
2333 /**********************************************************************
2334 * TlsAlloc [KERNEL32.@]
2336 * Allocates a thread local storage index.
2339 * Success: TLS index.
2340 * Failure: 0xFFFFFFFF
2342 DWORD WINAPI TlsAlloc( void )
2345 PEB * const peb = NtCurrentTeb()->Peb;
2347 RtlAcquirePebLock();
2348 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2349 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2352 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2355 if (!NtCurrentTeb()->TlsExpansionSlots &&
2356 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2357 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2359 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2361 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2365 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2366 index += TLS_MINIMUM_AVAILABLE;
2369 else SetLastError( ERROR_NO_MORE_ITEMS );
2371 RtlReleasePebLock();
2376 /**********************************************************************
2377 * TlsFree [KERNEL32.@]
2379 * Releases a thread local storage index, making it available for reuse.
2382 * index [in] TLS index to free.
2388 BOOL WINAPI TlsFree( DWORD index )
2392 RtlAcquirePebLock();
2393 if (index >= TLS_MINIMUM_AVAILABLE)
2395 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2396 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2400 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2401 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2403 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2404 else SetLastError( ERROR_INVALID_PARAMETER );
2405 RtlReleasePebLock();
2410 /**********************************************************************
2411 * TlsGetValue [KERNEL32.@]
2413 * Gets value in a thread's TLS slot.
2416 * index [in] TLS index to retrieve value for.
2419 * Success: Value stored in calling thread's TLS slot for index.
2420 * Failure: 0 and GetLastError() returns NO_ERROR.
2422 LPVOID WINAPI TlsGetValue( DWORD index )
2426 if (index < TLS_MINIMUM_AVAILABLE)
2428 ret = NtCurrentTeb()->TlsSlots[index];
2432 index -= TLS_MINIMUM_AVAILABLE;
2433 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2435 SetLastError( ERROR_INVALID_PARAMETER );
2438 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2439 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2441 SetLastError( ERROR_SUCCESS );
2446 /**********************************************************************
2447 * TlsSetValue [KERNEL32.@]
2449 * Stores a value in the thread's TLS slot.
2452 * index [in] TLS index to set value for.
2453 * value [in] Value to be stored.
2459 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2461 if (index < TLS_MINIMUM_AVAILABLE)
2463 NtCurrentTeb()->TlsSlots[index] = value;
2467 index -= TLS_MINIMUM_AVAILABLE;
2468 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2470 SetLastError( ERROR_INVALID_PARAMETER );
2473 if (!NtCurrentTeb()->TlsExpansionSlots &&
2474 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2475 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2477 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2480 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2486 /***********************************************************************
2487 * GetProcessFlags (KERNEL32.@)
2489 DWORD WINAPI GetProcessFlags( DWORD processid )
2491 IMAGE_NT_HEADERS *nt;
2494 if (processid && processid != GetCurrentProcessId()) return 0;
2496 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2498 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2499 flags |= PDB32_CONSOLE_PROC;
2501 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2502 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2507 /***********************************************************************
2508 * GetProcessDword (KERNEL.485)
2509 * GetProcessDword (KERNEL32.18)
2510 * 'Of course you cannot directly access Windows internal structures'
2512 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2517 TRACE("(%d, %d)\n", dwProcessID, offset );
2519 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2521 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2527 case GPD_APP_COMPAT_FLAGS:
2528 return GetAppCompatFlags16(0);
2529 case GPD_LOAD_DONE_EVENT:
2531 case GPD_HINSTANCE16:
2532 return GetTaskDS16();
2533 case GPD_WINDOWS_VERSION:
2534 return GetExeVersion16();
2536 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2538 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2539 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2540 GetStartupInfoW(&siw);
2541 return HandleToULong(siw.hStdOutput);
2542 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2543 GetStartupInfoW(&siw);
2544 return HandleToULong(siw.hStdInput);
2545 case GPD_STARTF_SHOWWINDOW:
2546 GetStartupInfoW(&siw);
2547 return siw.wShowWindow;
2548 case GPD_STARTF_SIZE:
2549 GetStartupInfoW(&siw);
2551 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2553 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2554 return MAKELONG( x, y );
2555 case GPD_STARTF_POSITION:
2556 GetStartupInfoW(&siw);
2558 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2560 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2561 return MAKELONG( x, y );
2562 case GPD_STARTF_FLAGS:
2563 GetStartupInfoW(&siw);
2568 return GetProcessFlags(0);
2570 return process_dword;
2572 ERR("Unknown offset %d\n", offset );
2577 /***********************************************************************
2578 * SetProcessDword (KERNEL.484)
2579 * 'Of course you cannot directly access Windows internal structures'
2581 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2583 TRACE("(%d, %d)\n", dwProcessID, offset );
2585 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2587 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2593 case GPD_APP_COMPAT_FLAGS:
2594 case GPD_LOAD_DONE_EVENT:
2595 case GPD_HINSTANCE16:
2596 case GPD_WINDOWS_VERSION:
2599 case GPD_STARTF_SHELLDATA:
2600 case GPD_STARTF_HOTKEY:
2601 case GPD_STARTF_SHOWWINDOW:
2602 case GPD_STARTF_SIZE:
2603 case GPD_STARTF_POSITION:
2604 case GPD_STARTF_FLAGS:
2607 ERR("Not allowed to modify offset %d\n", offset );
2610 process_dword = value;
2613 ERR("Unknown offset %d\n", offset );
2619 /***********************************************************************
2620 * ExitProcess (KERNEL.466)
2622 void WINAPI ExitProcess16( WORD status )
2625 ReleaseThunkLock( &count );
2626 ExitProcess( status );
2630 /*********************************************************************
2631 * OpenProcess (KERNEL32.@)
2633 * Opens a handle to a process.
2636 * access [I] Desired access rights assigned to the returned handle.
2637 * inherit [I] Determines whether or not child processes will inherit the handle.
2638 * id [I] Process identifier of the process to get a handle to.
2641 * Success: Valid handle to the specified process.
2642 * Failure: NULL, check GetLastError().
2644 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2648 OBJECT_ATTRIBUTES attr;
2651 cid.UniqueProcess = ULongToHandle(id);
2652 cid.UniqueThread = 0; /* FIXME ? */
2654 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2655 attr.RootDirectory = NULL;
2656 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2657 attr.SecurityDescriptor = NULL;
2658 attr.SecurityQualityOfService = NULL;
2659 attr.ObjectName = NULL;
2661 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2663 status = NtOpenProcess(&handle, access, &attr, &cid);
2664 if (status != STATUS_SUCCESS)
2666 SetLastError( RtlNtStatusToDosError(status) );
2673 /*********************************************************************
2674 * MapProcessHandle (KERNEL.483)
2675 * GetProcessId (KERNEL32.@)
2677 * Gets the a unique identifier of a process.
2680 * hProcess [I] Handle to the process.
2684 * Failure: FALSE, check GetLastError().
2688 * The identifier is unique only on the machine and only until the process
2689 * exits (including system shutdown).
2691 DWORD WINAPI GetProcessId( HANDLE hProcess )
2694 PROCESS_BASIC_INFORMATION pbi;
2696 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2698 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2699 SetLastError( RtlNtStatusToDosError(status) );
2704 /*********************************************************************
2705 * CloseW32Handle (KERNEL.474)
2706 * CloseHandle (KERNEL32.@)
2711 * handle [I] Handle to close.
2715 * Failure: FALSE, check GetLastError().
2717 BOOL WINAPI CloseHandle( HANDLE handle )
2721 /* stdio handles need special treatment */
2722 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2723 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2724 (handle == (HANDLE)STD_ERROR_HANDLE))
2725 handle = GetStdHandle( HandleToULong(handle) );
2727 if (is_console_handle(handle))
2728 return CloseConsoleHandle(handle);
2730 status = NtClose( handle );
2731 if (status) SetLastError( RtlNtStatusToDosError(status) );
2736 /*********************************************************************
2737 * GetHandleInformation (KERNEL32.@)
2739 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2741 OBJECT_DATA_INFORMATION info;
2742 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2744 if (status) SetLastError( RtlNtStatusToDosError(status) );
2748 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2749 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2755 /*********************************************************************
2756 * SetHandleInformation (KERNEL32.@)
2758 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2760 OBJECT_DATA_INFORMATION info;
2763 /* if not setting both fields, retrieve current value first */
2764 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2765 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2767 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2769 SetLastError( RtlNtStatusToDosError(status) );
2773 if (mask & HANDLE_FLAG_INHERIT)
2774 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2775 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2776 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2778 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2779 if (status) SetLastError( RtlNtStatusToDosError(status) );
2784 /*********************************************************************
2785 * DuplicateHandle (KERNEL32.@)
2787 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2788 HANDLE dest_process, HANDLE *dest,
2789 DWORD access, BOOL inherit, DWORD options )
2793 if (is_console_handle(source))
2795 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2796 if (source_process != dest_process ||
2797 source_process != GetCurrentProcess())
2799 SetLastError(ERROR_INVALID_PARAMETER);
2802 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2803 return (*dest != INVALID_HANDLE_VALUE);
2805 status = NtDuplicateObject( source_process, source, dest_process, dest,
2806 access, inherit ? OBJ_INHERIT : 0, options );
2807 if (status) SetLastError( RtlNtStatusToDosError(status) );
2812 /***********************************************************************
2813 * ConvertToGlobalHandle (KERNEL.476)
2814 * ConvertToGlobalHandle (KERNEL32.@)
2816 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2818 HANDLE ret = INVALID_HANDLE_VALUE;
2819 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2820 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2825 /***********************************************************************
2826 * SetHandleContext (KERNEL32.@)
2828 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2830 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2831 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2832 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2837 /***********************************************************************
2838 * GetHandleContext (KERNEL32.@)
2840 DWORD WINAPI GetHandleContext(HANDLE hnd)
2842 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2843 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2844 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2849 /***********************************************************************
2850 * CreateSocketHandle (KERNEL32.@)
2852 HANDLE WINAPI CreateSocketHandle(void)
2854 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2855 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2856 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2857 return INVALID_HANDLE_VALUE;
2861 /***********************************************************************
2862 * SetPriorityClass (KERNEL32.@)
2864 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2867 PROCESS_PRIORITY_CLASS ppc;
2869 ppc.Foreground = FALSE;
2870 switch (priorityclass)
2872 case IDLE_PRIORITY_CLASS:
2873 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2874 case BELOW_NORMAL_PRIORITY_CLASS:
2875 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2876 case NORMAL_PRIORITY_CLASS:
2877 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2878 case ABOVE_NORMAL_PRIORITY_CLASS:
2879 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2880 case HIGH_PRIORITY_CLASS:
2881 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2882 case REALTIME_PRIORITY_CLASS:
2883 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2885 SetLastError(ERROR_INVALID_PARAMETER);
2889 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2892 if (status != STATUS_SUCCESS)
2894 SetLastError( RtlNtStatusToDosError(status) );
2901 /***********************************************************************
2902 * GetPriorityClass (KERNEL32.@)
2904 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2907 PROCESS_BASIC_INFORMATION pbi;
2909 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2911 if (status != STATUS_SUCCESS)
2913 SetLastError( RtlNtStatusToDosError(status) );
2916 switch (pbi.BasePriority)
2918 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2919 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2920 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2921 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2922 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2923 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2925 SetLastError( ERROR_INVALID_PARAMETER );
2930 /***********************************************************************
2931 * SetProcessAffinityMask (KERNEL32.@)
2933 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2937 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2938 &affmask, sizeof(DWORD_PTR));
2941 SetLastError( RtlNtStatusToDosError(status) );
2948 /**********************************************************************
2949 * GetProcessAffinityMask (KERNEL32.@)
2951 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2952 PDWORD_PTR lpProcessAffinityMask,
2953 PDWORD_PTR lpSystemAffinityMask )
2955 PROCESS_BASIC_INFORMATION pbi;
2958 status = NtQueryInformationProcess(hProcess,
2959 ProcessBasicInformation,
2960 &pbi, sizeof(pbi), NULL);
2963 SetLastError( RtlNtStatusToDosError(status) );
2966 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2967 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2972 /***********************************************************************
2973 * GetProcessVersion (KERNEL32.@)
2975 DWORD WINAPI GetProcessVersion( DWORD pid )
2979 PROCESS_BASIC_INFORMATION pbi;
2982 IMAGE_DOS_HEADER dos;
2983 IMAGE_NT_HEADERS nt;
2986 if (!pid || pid == GetCurrentProcessId())
2988 IMAGE_NT_HEADERS *nt;
2990 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2991 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2992 nt->OptionalHeader.MinorSubsystemVersion);
2996 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2997 if (!process) return 0;
2999 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3000 if (status) goto err;
3002 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3003 if (status || count != sizeof(peb)) goto err;
3005 memset(&dos, 0, sizeof(dos));
3006 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3007 if (status || count != sizeof(dos)) goto err;
3008 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3010 memset(&nt, 0, sizeof(nt));
3011 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3012 if (status || count != sizeof(nt)) goto err;
3013 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3015 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3018 CloseHandle(process);
3020 if (status != STATUS_SUCCESS)
3021 SetLastError(RtlNtStatusToDosError(status));
3027 /***********************************************************************
3028 * SetProcessWorkingSetSize [KERNEL32.@]
3029 * Sets the min/max working set sizes for a specified process.
3032 * hProcess [I] Handle to the process of interest
3033 * minset [I] Specifies minimum working set size
3034 * maxset [I] Specifies maximum working set size
3040 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3043 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3044 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3045 /* Trim the working set to zero */
3046 /* Swap the process out of physical RAM */
3051 /***********************************************************************
3052 * GetProcessWorkingSetSize (KERNEL32.@)
3054 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3057 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3058 /* 32 MB working set size */
3059 if (minset) *minset = 32*1024*1024;
3060 if (maxset) *maxset = 32*1024*1024;
3065 /***********************************************************************
3066 * SetProcessShutdownParameters (KERNEL32.@)
3068 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3070 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3071 shutdown_flags = flags;
3072 shutdown_priority = level;
3077 /***********************************************************************
3078 * GetProcessShutdownParameters (KERNEL32.@)
3081 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3083 *lpdwLevel = shutdown_priority;
3084 *lpdwFlags = shutdown_flags;
3089 /***********************************************************************
3090 * GetProcessPriorityBoost (KERNEL32.@)
3092 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3094 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3096 /* Report that no boost is present.. */
3097 *pDisablePriorityBoost = FALSE;
3102 /***********************************************************************
3103 * SetProcessPriorityBoost (KERNEL32.@)
3105 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3107 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3108 /* Say we can do it. I doubt the program will notice that we don't. */
3113 /***********************************************************************
3114 * ReadProcessMemory (KERNEL32.@)
3116 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3117 SIZE_T *bytes_read )
3119 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3120 if (status) SetLastError( RtlNtStatusToDosError(status) );
3125 /***********************************************************************
3126 * WriteProcessMemory (KERNEL32.@)
3128 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3129 SIZE_T *bytes_written )
3131 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3132 if (status) SetLastError( RtlNtStatusToDosError(status) );
3137 /****************************************************************************
3138 * FlushInstructionCache (KERNEL32.@)
3140 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3143 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3144 if (status) SetLastError( RtlNtStatusToDosError(status) );
3149 /******************************************************************
3150 * GetProcessIoCounters (KERNEL32.@)
3152 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3156 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3157 ioc, sizeof(*ioc), NULL);
3158 if (status) SetLastError( RtlNtStatusToDosError(status) );
3162 /******************************************************************
3163 * GetProcessHandleCount (KERNEL32.@)
3165 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3169 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3170 cnt, sizeof(*cnt), NULL);
3171 if (status) SetLastError( RtlNtStatusToDosError(status) );
3175 /******************************************************************
3176 * QueryFullProcessImageNameA (KERNEL32.@)
3178 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3181 DWORD pdwSizeW = *pdwSize;
3182 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3184 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3187 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3188 lpExeName, *pdwSize, NULL, NULL));
3190 *pdwSize = strlen(lpExeName);
3192 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3196 /******************************************************************
3197 * QueryFullProcessImageNameW (KERNEL32.@)
3199 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3201 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3202 UNICODE_STRING *dynamic_buffer = NULL;
3203 UNICODE_STRING nt_path;
3204 UNICODE_STRING *result = NULL;
3208 RtlInitUnicodeStringEx(&nt_path, NULL);
3209 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3210 * as this is on Wine. */
3211 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3212 sizeof(buffer) - sizeof(WCHAR), &needed);
3213 if (status == STATUS_INFO_LENGTH_MISMATCH)
3215 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3216 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3217 result = dynamic_buffer;
3220 result = (PUNICODE_STRING)buffer;
3222 if (status) goto cleanup;
3224 if (dwFlags & PROCESS_NAME_NATIVE)
3226 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3227 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3229 status = STATUS_OBJECT_PATH_NOT_FOUND;
3235 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3237 status = STATUS_BUFFER_TOO_SMALL;
3241 *pdwSize = result->Length/sizeof(WCHAR);
3242 memcpy( lpExeName, result->Buffer, result->Length );
3243 lpExeName[*pdwSize] = 0;
3246 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3247 RtlFreeUnicodeString(&nt_path);
3248 if (status) SetLastError( RtlNtStatusToDosError(status) );
3252 /***********************************************************************
3253 * ProcessIdToSessionId (KERNEL32.@)
3254 * This function is available on Terminal Server 4SP4 and Windows 2000
3256 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3258 /* According to MSDN, if the calling process is not in a terminal
3259 * services environment, then the sessionid returned is zero.
3266 /***********************************************************************
3267 * RegisterServiceProcess (KERNEL.491)
3268 * RegisterServiceProcess (KERNEL32.@)
3270 * A service process calls this function to ensure that it continues to run
3271 * even after a user logged off.
3273 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3275 /* I don't think that Wine needs to do anything in this function */
3276 return 1; /* success */
3280 /**********************************************************************
3281 * IsWow64Process (KERNEL32.@)
3283 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3288 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3290 if (status != STATUS_SUCCESS)
3292 SetLastError( RtlNtStatusToDosError( status ) );
3295 *Wow64Process = (pbi != 0);
3300 /***********************************************************************
3301 * GetCurrentProcess (KERNEL32.@)
3303 * Get a handle to the current process.
3309 * A handle representing the current process.
3311 #undef GetCurrentProcess
3312 HANDLE WINAPI GetCurrentProcess(void)
3314 return (HANDLE)~(ULONG_PTR)0;
3317 /***********************************************************************
3318 * CmdBatNotification (KERNEL32.@)
3320 * Notifies the system that a batch file has started or finished.
3323 * bBatchRunning [I] TRUE if a batch file has started or
3324 * FALSE if a batch file has finished executing.
3329 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3331 FIXME("%d\n", bBatchRunning);
3336 /***********************************************************************
3337 * RegisterApplicationRestart (KERNEL32.@)
3339 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3341 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3346 /**********************************************************************
3347 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3349 DWORD WINAPI WTSGetActiveConsoleSessionId(void)