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"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
43 #include <sys/types.h>
46 #define WIN32_NO_STATUS
48 #include "kernel_private.h"
49 #include "wine/library.h"
50 #include "wine/server.h"
51 #include "wine/unicode.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(process);
55 WINE_DECLARE_DEBUG_CHANNEL(file);
56 WINE_DECLARE_DEBUG_CHANNEL(relay);
59 extern char **__wine_get_main_environment(void);
61 extern char **__wine_main_environ;
62 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
73 static UINT process_error_mode;
75 static DWORD shutdown_flags = 0;
76 static DWORD shutdown_priority = 0x280;
79 HMODULE kernel32_handle = 0;
81 const WCHAR *DIR_Windows = NULL;
82 const WCHAR *DIR_System = NULL;
83 const WCHAR *DIR_SysWow64 = 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 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
133 unsigned int len = strlenW( prefix );
135 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
136 while (filename[len] == '\\') len++;
141 /***************************************************************************
144 * Get the path of a builtin module when the native file does not exist.
146 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
147 UINT size, struct binary_info *binary_info )
151 void *redir_disabled = 0;
152 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
154 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
155 Wow64RevertWow64FsRedirection( redir_disabled );
157 if (contains_path( libname ))
159 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
160 filename, &file_part ) > size * sizeof(WCHAR))
161 return FALSE; /* too long */
163 if ((len = is_path_prefix( DIR_System, filename )))
165 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
167 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
173 if (filename + len != file_part) return FALSE;
177 len = strlenW( DIR_System );
178 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
179 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
180 file_part = filename + len;
181 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
182 strcpyW( file_part, libname );
183 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
185 if (ext && !strchrW( file_part, '.' ))
187 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
188 return FALSE; /* too long */
189 strcatW( file_part, ext );
191 binary_info->type = BINARY_UNIX_LIB;
192 binary_info->flags = flags;
193 binary_info->res_start = NULL;
194 binary_info->res_end = NULL;
199 /***********************************************************************
200 * open_builtin_exe_file
202 * Open an exe file for a builtin exe.
204 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
205 int test_only, int *file_exists )
207 char exename[MAX_PATH];
212 if ((p = strrchrW( name, '/' ))) name = p + 1;
213 if ((p = strrchrW( name, '\\' ))) name = p + 1;
215 /* we don't want to depend on the current codepage here */
216 len = strlenW( name ) + 1;
217 if (len >= sizeof(exename)) return NULL;
218 for (i = 0; i < len; i++)
220 if (name[i] > 127) return NULL;
221 exename[i] = (char)name[i];
222 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
224 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
228 /***********************************************************************
231 * Open a specific exe file, taking load order into account.
232 * Returns the file handle or 0 for a builtin exe.
234 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
238 TRACE("looking for %s\n", debugstr_w(name) );
240 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
241 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
243 WCHAR buffer[MAX_PATH];
244 /* file doesn't exist, check for builtin */
245 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
248 else MODULE_get_binary_info( handle, binary_info );
254 /***********************************************************************
257 * Open an exe file, and return the full name and file handle.
258 * Returns FALSE if file could not be found.
259 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
260 * If file is a builtin exe, returns TRUE and sets handle to 0.
262 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
263 HANDLE *handle, struct binary_info *binary_info )
265 static const WCHAR exeW[] = {'.','e','x','e',0};
268 TRACE("looking for %s\n", debugstr_w(name) );
270 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
272 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
274 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
275 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
284 /* no builtin found, try native without extension in case it is a Unix app */
286 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
289 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
290 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
291 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
293 MODULE_get_binary_info( *handle, binary_info );
300 /***********************************************************************
301 * build_initial_environment
303 * Build the Win32 environment from the Unix environment
305 static BOOL build_initial_environment(void)
311 char **env = __wine_get_main_environment();
313 /* Compute the total size of the Unix environment */
314 for (e = env; *e; e++)
316 if (is_special_env_var( *e )) continue;
317 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
319 size *= sizeof(WCHAR);
321 /* Now allocate the environment */
323 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
324 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
327 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
328 endptr = p + size / sizeof(WCHAR);
330 /* And fill it with the Unix environment */
331 for (e = env; *e; e++)
335 /* skip Unix special variables and use the Wine variants instead */
336 if (!strncmp( str, "WINE", 4 ))
338 if (is_special_env_var( str + 4 )) str += 4;
339 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
341 else if (is_special_env_var( str )) continue; /* skip it */
343 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
351 /***********************************************************************
352 * set_registry_variables
354 * Set environment variables by enumerating the values of a key;
355 * helper for set_registry_environment().
356 * Note that Windows happily truncates the value if it's too big.
358 static void set_registry_variables( HANDLE hkey, ULONG type )
360 UNICODE_STRING env_name, env_value;
364 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
365 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
367 for (index = 0; ; index++)
369 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
370 buffer, sizeof(buffer), &size );
371 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
373 if (info->Type != type)
375 env_name.Buffer = info->Name;
376 env_name.Length = env_name.MaximumLength = info->NameLength;
377 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
378 env_value.Length = env_value.MaximumLength = info->DataLength;
379 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
380 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
381 if (!env_value.Length) continue;
382 if (info->Type == REG_EXPAND_SZ)
384 WCHAR buf_expanded[1024];
385 UNICODE_STRING env_expanded;
386 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
387 env_expanded.Buffer=buf_expanded;
388 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
389 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
390 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
394 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
400 /***********************************************************************
401 * set_registry_environment
403 * Set the environment variables specified in the registry.
405 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
406 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
407 * on the order in which the variables are processed. But on Windows it
408 * does not really matter since they only use %SystemDrive% and
409 * %SystemRoot% which are predefined. But Wine defines these in the
410 * registry, so we need two passes.
412 static BOOL set_registry_environment(void)
414 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
415 'S','y','s','t','e','m','\\',
416 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
417 'C','o','n','t','r','o','l','\\',
418 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
419 'E','n','v','i','r','o','n','m','e','n','t',0};
420 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
421 static const WCHAR volatile_envW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
423 OBJECT_ATTRIBUTES attr;
424 UNICODE_STRING nameW;
428 attr.Length = sizeof(attr);
429 attr.RootDirectory = 0;
430 attr.ObjectName = &nameW;
432 attr.SecurityDescriptor = NULL;
433 attr.SecurityQualityOfService = NULL;
435 /* first the system environment variables */
436 RtlInitUnicodeString( &nameW, env_keyW );
437 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
439 set_registry_variables( hkey, REG_SZ );
440 set_registry_variables( hkey, REG_EXPAND_SZ );
445 /* then the ones for the current user */
446 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
447 RtlInitUnicodeString( &nameW, envW );
448 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
450 set_registry_variables( hkey, REG_SZ );
451 set_registry_variables( hkey, REG_EXPAND_SZ );
455 RtlInitUnicodeString( &nameW, volatile_envW );
456 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
458 set_registry_variables( hkey, REG_SZ );
459 set_registry_variables( hkey, REG_EXPAND_SZ );
463 NtClose( attr.RootDirectory );
468 /***********************************************************************
471 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
473 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
474 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
475 DWORD len, size = sizeof(buffer);
477 UNICODE_STRING nameW;
479 RtlInitUnicodeString( &nameW, name );
480 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
483 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
484 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
486 if (info->Type == REG_EXPAND_SZ)
488 UNICODE_STRING value, expanded;
490 value.MaximumLength = len * sizeof(WCHAR);
491 value.Buffer = (WCHAR *)info->Data;
492 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
493 value.Length = len * sizeof(WCHAR);
494 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
495 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
496 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
497 else RtlFreeUnicodeString( &expanded );
499 else if (info->Type == REG_SZ)
501 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
503 memcpy( ret, info->Data, len * sizeof(WCHAR) );
511 /***********************************************************************
512 * set_additional_environment
514 * Set some additional environment variables not specified in the registry.
516 static void set_additional_environment(void)
518 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
519 'S','o','f','t','w','a','r','e','\\',
520 'M','i','c','r','o','s','o','f','t','\\',
521 'W','i','n','d','o','w','s',' ','N','T','\\',
522 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
523 'P','r','o','f','i','l','e','L','i','s','t',0};
524 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
525 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
526 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
527 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
528 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
529 OBJECT_ATTRIBUTES attr;
530 UNICODE_STRING nameW;
531 WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
533 const char *name = wine_get_user_name();
536 /* set the USERNAME variable */
538 len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
541 user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
542 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
543 SetEnvironmentVariableW( usernameW, user_name );
545 else WARN( "user name %s not convertible.\n", debugstr_a(name) );
547 /* set the USERPROFILE and ALLUSERSPROFILE variables */
549 attr.Length = sizeof(attr);
550 attr.RootDirectory = 0;
551 attr.ObjectName = &nameW;
553 attr.SecurityDescriptor = NULL;
554 attr.SecurityQualityOfService = NULL;
555 RtlInitUnicodeString( &nameW, profile_keyW );
556 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
558 profile_dir = get_reg_value( hkey, profiles_valueW );
559 all_users_dir = get_reg_value( hkey, all_users_valueW );
567 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
568 len += strlenW(profile_dir) + 1;
569 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
570 strcpyW( value, profile_dir );
571 p = value + strlenW(value);
572 if (p > value && p[-1] != '\\') *p++ = '\\';
574 strcpyW( p, user_name );
575 SetEnvironmentVariableW( userprofileW, value );
579 strcpyW( p, all_users_dir );
580 SetEnvironmentVariableW( allusersW, value );
582 HeapFree( GetProcessHeap(), 0, value );
585 HeapFree( GetProcessHeap(), 0, all_users_dir );
586 HeapFree( GetProcessHeap(), 0, profile_dir );
587 HeapFree( GetProcessHeap(), 0, user_name );
590 /***********************************************************************
593 * Set the Wine library Unicode argv global variables.
595 static void set_library_wargv( char **argv )
603 for (argc = 0; argv[argc]; argc++)
604 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
606 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
607 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
608 p = (WCHAR *)(wargv + argc + 1);
609 for (argc = 0; argv[argc]; argc++)
611 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
618 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
620 for (argc = 0; wargv[argc]; argc++)
621 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
623 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
624 q = (char *)(argv + argc + 1);
625 for (argc = 0; wargv[argc]; argc++)
627 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
634 __wine_main_argc = argc;
635 __wine_main_argv = argv;
636 __wine_main_wargv = wargv;
640 /***********************************************************************
641 * update_library_argv0
643 * Update the argv[0] global variable with the binary we have found.
645 static void update_library_argv0( const WCHAR *argv0 )
647 DWORD len = strlenW( argv0 );
649 if (len > strlenW( __wine_main_wargv[0] ))
651 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
653 strcpyW( __wine_main_wargv[0], argv0 );
655 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
656 if (len > strlen( __wine_main_argv[0] ) + 1)
658 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
660 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
664 /***********************************************************************
667 * Build the command line of a process from the argv array.
669 * Note that it does NOT necessarily include the file name.
670 * Sometimes we don't even have any command line options at all.
672 * We must quote and escape characters so that the argv array can be rebuilt
673 * from the command line:
674 * - spaces and tabs must be quoted
676 * - quotes must be escaped
678 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
679 * resulting in an odd number of '\' followed by a '"'
682 * - '\'s that are not followed by a '"' can be left as is
686 static BOOL build_command_line( WCHAR **argv )
691 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
693 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
696 for (arg = argv; *arg; arg++)
698 int has_space,bcount;
704 if( !*a ) has_space=1;
709 if (*a==' ' || *a=='\t') {
711 } else if (*a=='"') {
712 /* doubling of '\' preceding a '"',
713 * plus escaping of said '"'
721 len+=(a-*arg)+1 /* for the separating space */;
723 len+=2; /* for the quotes */
726 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
729 p = rupp->CommandLine.Buffer;
730 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
731 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
732 for (arg = argv; *arg; arg++)
734 int has_space,has_quote;
737 /* Check for quotes and spaces in this argument */
738 has_space=has_quote=0;
740 if( !*a ) has_space=1;
742 if (*a==' ' || *a=='\t') {
746 } else if (*a=='"') {
754 /* Now transfer it to the command line */
771 /* Double all the '\\' preceding this '"', plus one */
772 for (i=0;i<=bcount;i++)
784 while ((*p=*x++)) p++;
790 if (p > rupp->CommandLine.Buffer)
791 p--; /* remove last space */
798 /***********************************************************************
799 * init_current_directory
801 * Initialize the current directory from the Unix cwd or the parent info.
803 static void init_current_directory( CURDIR *cur_dir )
805 UNICODE_STRING dir_str;
810 /* if we received a cur dir from the parent, try this first */
812 if (cur_dir->DosPath.Length)
814 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
817 /* now try to get it from the Unix cwd */
819 for (size = 256; ; size *= 2)
821 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
822 if (getcwd( cwd, size )) break;
823 HeapFree( GetProcessHeap(), 0, cwd );
824 if (errno == ERANGE) continue;
829 /* try to use PWD if it is valid, so that we don't resolve symlinks */
831 pwd = getenv( "PWD" );
834 struct stat st1, st2;
836 if (!pwd || stat( pwd, &st1 ) == -1 ||
837 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
843 ANSI_STRING unix_name;
844 UNICODE_STRING nt_name;
845 RtlInitAnsiString( &unix_name, pwd );
846 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
848 UNICODE_STRING dos_path;
849 /* skip the \??\ prefix, nt_name is 0 terminated */
850 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
851 RtlSetCurrentDirectory_U( &dos_path );
852 RtlFreeUnicodeString( &nt_name );
856 if (!cur_dir->DosPath.Length) /* still not initialized */
858 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
859 "starting in the Windows directory.\n", cwd ? cwd : "" );
860 RtlInitUnicodeString( &dir_str, DIR_Windows );
861 RtlSetCurrentDirectory_U( &dir_str );
863 HeapFree( GetProcessHeap(), 0, cwd );
866 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
867 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
871 /***********************************************************************
874 * Initialize the windows and system directories from the environment.
876 static void init_windows_dirs(void)
878 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
880 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
881 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
882 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
883 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
884 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
889 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
891 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
892 GetEnvironmentVariableW( windirW, buffer, len );
893 DIR_Windows = buffer;
895 else DIR_Windows = default_windirW;
897 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
899 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
900 GetEnvironmentVariableW( winsysdirW, buffer, len );
905 len = strlenW( DIR_Windows );
906 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
907 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
908 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
912 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
913 ERR( "directory %s could not be created, error %u\n",
914 debugstr_w(DIR_Windows), GetLastError() );
915 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
916 ERR( "directory %s could not be created, error %u\n",
917 debugstr_w(DIR_System), GetLastError() );
919 #ifndef _WIN64 /* SysWow64 is always defined on 64-bit */
923 len = strlenW( DIR_Windows );
924 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
925 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
926 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
927 DIR_SysWow64 = buffer;
928 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
929 ERR( "directory %s could not be created, error %u\n",
930 debugstr_w(DIR_SysWow64), GetLastError() );
933 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
934 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
936 /* set the directories in ntdll too */
937 __wine_init_windows_dir( DIR_Windows, DIR_System );
941 /***********************************************************************
944 * Start the wineboot process if necessary. Return the handles to wait on.
946 static void start_wineboot( HANDLE handles[2] )
948 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
951 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
953 ERR( "failed to create wineboot event, expect trouble\n" );
956 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
958 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
959 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
960 const DWORD expected_type = (sizeof(void*) > sizeof(int) || is_wow64) ?
961 SCS_64BIT_BINARY : SCS_32BIT_BINARY;
963 PROCESS_INFORMATION pi;
967 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
969 memset( &si, 0, sizeof(si) );
971 si.dwFlags = STARTF_USESTDHANDLES;
974 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
976 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
977 lstrcatW( app, wineboot );
979 Wow64DisableWow64FsRedirection( &redir );
980 if (GetBinaryTypeW( app, &type ) && type != expected_type)
982 if (type == SCS_64BIT_BINARY)
983 MESSAGE( "wine: '%s' is a 64-bit prefix, it cannot be used with 32-bit Wine.\n",
984 wine_get_config_dir() );
986 MESSAGE( "wine: '%s' is a 32-bit prefix, it cannot be used with %s Wine.\n",
987 wine_get_config_dir(), is_wow64 ? "wow64" : "64-bit" );
991 strcpyW( cmdline, app );
992 strcatW( cmdline, args );
993 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
995 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
996 CloseHandle( pi.hThread );
997 handles[1] = pi.hProcess;
1001 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1002 CloseHandle( handles[0] );
1005 Wow64RevertWow64FsRedirection( redir );
1010 /***********************************************************************
1013 * Startup routine of a new process. Runs on the new process stack.
1015 static DWORD WINAPI start_process( PEB *peb )
1017 IMAGE_NT_HEADERS *nt;
1018 LPTHREAD_START_ROUTINE entry;
1020 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1021 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1022 nt->OptionalHeader.AddressOfEntryPoint);
1024 if (!nt->OptionalHeader.AddressOfEntryPoint)
1026 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1027 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1031 if (TRACE_ON(relay))
1032 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1033 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1035 SetLastError( 0 ); /* clear error code */
1036 if (peb->BeingDebugged) DbgBreakPoint();
1037 return entry( peb );
1041 /***********************************************************************
1044 * Change the process name in the ps output.
1046 static void set_process_name( int argc, char *argv[] )
1048 #ifdef HAVE_SETPROCTITLE
1049 setproctitle("-%s", argv[1]);
1054 char *p, *prctl_name = argv[1];
1055 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1058 # define PR_SET_NAME 15
1061 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1062 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1064 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1066 offset = argv[1] - argv[0];
1067 memmove( argv[1] - offset, argv[1], end - argv[1] );
1068 memset( end - offset, 0, offset );
1069 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1073 #endif /* HAVE_PRCTL */
1075 /* remove argv[0] */
1076 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1081 /***********************************************************************
1082 * __wine_kernel_init
1084 * Wine initialisation: load and start the main exe file.
1086 void CDECL __wine_kernel_init(void)
1088 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1089 static const WCHAR dotW[] = {'.',0};
1090 static const WCHAR exeW[] = {'.','e','x','e',0};
1092 WCHAR *p, main_exe_name[MAX_PATH+1];
1093 PEB *peb = NtCurrentTeb()->Peb;
1094 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1095 HANDLE boot_events[2];
1096 BOOL got_environment = TRUE;
1098 /* Initialize everything */
1100 setbuf(stdout,NULL);
1101 setbuf(stderr,NULL);
1102 kernel32_handle = GetModuleHandleW(kernel32W);
1103 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1107 if (!params->Environment)
1109 /* Copy the parent environment */
1110 if (!build_initial_environment()) exit(1);
1112 /* convert old configuration to new format */
1113 convert_old_config();
1115 got_environment = set_registry_environment();
1116 set_additional_environment();
1119 init_windows_dirs();
1120 init_current_directory( ¶ms->CurrentDirectory );
1122 set_process_name( __wine_main_argc, __wine_main_argv );
1123 set_library_wargv( __wine_main_argv );
1124 boot_events[0] = boot_events[1] = 0;
1126 if (peb->ProcessParameters->ImagePathName.Buffer)
1128 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1132 struct binary_info binary_info;
1134 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1135 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1137 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1138 ExitProcess( GetLastError() );
1140 update_library_argv0( main_exe_name );
1141 if (!build_command_line( __wine_main_wargv )) goto error;
1142 start_wineboot( boot_events );
1145 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1146 p = strrchrW( main_exe_name, '.' );
1147 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1149 TRACE( "starting process name=%s argv[0]=%s\n",
1150 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1152 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1153 MODULE_get_dll_load_path(main_exe_name) );
1157 DWORD timeout = 30000, count = 1;
1159 if (boot_events[1]) count++;
1160 if (!got_environment) timeout = 300000; /* initial prefix creation can take longer */
1161 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1162 ERR( "boot event wait timed out\n" );
1163 CloseHandle( boot_events[0] );
1164 if (boot_events[1]) CloseHandle( boot_events[1] );
1165 /* if we didn't find environment section, try again now that wineboot has run */
1166 if (!got_environment)
1168 set_registry_environment();
1169 set_additional_environment();
1173 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1178 DWORD error = GetLastError();
1180 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1181 if (error == ERROR_BAD_EXE_FORMAT ||
1182 error == ERROR_INVALID_ADDRESS ||
1183 error == ERROR_NOT_ENOUGH_MEMORY)
1185 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1186 /* if we get back here, it failed */
1188 else if (error == ERROR_MOD_NOT_FOUND)
1190 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1191 else p = main_exe_name;
1192 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1194 /* args 1 and 2 are --app-name full_path */
1195 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1196 debugstr_w(__wine_main_wargv[3]) );
1197 ExitProcess( ERROR_BAD_EXE_FORMAT );
1200 args[0] = (DWORD_PTR)main_exe_name;
1201 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1202 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1203 WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1204 MESSAGE( "wine: %s", msg );
1205 ExitProcess( error );
1208 LdrInitializeThunk( start_process, 0, 0, 0 );
1211 ExitProcess( GetLastError() );
1215 /***********************************************************************
1218 * Build an argv array from a command-line.
1219 * 'reserved' is the number of args to reserve before the first one.
1221 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1225 char *arg,*s,*d,*cmdline;
1226 int in_quotes,bcount,len;
1228 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1229 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1230 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1237 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1240 /* skip the remaining spaces */
1241 while (*s==' ' || *s=='\t') {
1248 } else if (*s=='\\') {
1249 /* '\', count them */
1251 } else if ((*s=='"') && ((bcount & 1)==0)) {
1253 in_quotes=!in_quotes;
1256 /* a regular character */
1261 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1263 HeapFree( GetProcessHeap(), 0, cmdline );
1267 arg = d = s = (char *)(argv + argc);
1268 memcpy( d, cmdline, len );
1273 if ((*s==' ' || *s=='\t') && !in_quotes) {
1274 /* Close the argument and copy it */
1278 /* skip the remaining spaces */
1281 } while (*s==' ' || *s=='\t');
1283 /* Start with a new argument */
1286 } else if (*s=='\\') {
1290 } else if (*s=='"') {
1292 if ((bcount & 1)==0) {
1293 /* Preceded by an even number of '\', this is half that
1294 * number of '\', plus a '"' which we discard.
1298 in_quotes=!in_quotes;
1300 /* Preceded by an odd number of '\', this is half that
1301 * number of '\' followed by a '"'
1309 /* a regular character */
1320 HeapFree( GetProcessHeap(), 0, cmdline );
1325 /***********************************************************************
1328 * Build the environment of a new child process.
1330 static char **build_envp( const WCHAR *envW )
1332 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1337 int count = 1, length;
1340 for (end = envW; *end; count++) end += strlenW(end) + 1;
1342 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1343 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1344 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1346 for (p = env; *p; p += strlen(p) + 1)
1347 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1349 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1351 if (!(p = getenv(unix_vars[i]))) continue;
1352 length += strlen(unix_vars[i]) + strlen(p) + 2;
1356 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1358 char **envptr = envp;
1359 char *dst = (char *)(envp + count);
1361 /* some variables must not be modified, so we get them directly from the unix env */
1362 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1364 if (!(p = getenv(unix_vars[i]))) continue;
1365 *envptr++ = strcpy( dst, unix_vars[i] );
1368 dst += strlen(dst) + 1;
1371 /* now put the Windows environment strings */
1372 for (p = env; *p; p += strlen(p) + 1)
1374 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1375 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1376 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1377 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1378 if (is_special_env_var( p )) /* prefix it with "WINE" */
1380 *envptr++ = strcpy( dst, "WINE" );
1385 *envptr++ = strcpy( dst, p );
1387 dst += strlen(dst) + 1;
1391 HeapFree( GetProcessHeap(), 0, env );
1396 /***********************************************************************
1399 * Fork and exec a new Unix binary, checking for errors.
1401 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1402 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1404 int fd[2], stdin_fd = -1, stdout_fd = -1;
1406 char **argv, **envp;
1408 if (!env) env = GetEnvironmentStringsW();
1411 if (pipe2( fd, O_CLOEXEC ) == -1)
1416 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1419 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1420 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1423 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1425 HANDLE hstdin, hstdout;
1427 if (startup->dwFlags & STARTF_USESTDHANDLES)
1429 hstdin = startup->hStdInput;
1430 hstdout = startup->hStdOutput;
1434 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1435 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1438 if (is_console_handle( hstdin ))
1439 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1440 if (is_console_handle( hstdout ))
1441 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1442 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1443 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1446 argv = build_argv( cmdline, 0 );
1447 envp = build_envp( env );
1449 if (!(pid = fork())) /* child */
1453 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1456 if (!(pid = fork()))
1458 int fd = open( "/dev/null", O_RDWR );
1460 /* close stdin and stdout */
1468 else if (pid != -1) _exit(0); /* parent */
1474 dup2( stdin_fd, 0 );
1477 if (stdout_fd != -1)
1479 dup2( stdout_fd, 1 );
1484 /* Reset signals that we previously set to SIG_IGN */
1485 signal( SIGPIPE, SIG_DFL );
1486 signal( SIGCHLD, SIG_DFL );
1488 if (newdir) chdir(newdir);
1490 if (argv && envp) execve( filename, argv, envp );
1492 write( fd[1], &err, sizeof(err) );
1495 HeapFree( GetProcessHeap(), 0, argv );
1496 HeapFree( GetProcessHeap(), 0, envp );
1497 if (stdin_fd != -1) close( stdin_fd );
1498 if (stdout_fd != -1) close( stdout_fd );
1500 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1505 if (pid == -1) FILE_SetDosError();
1511 static inline DWORD append_string( void **ptr, const WCHAR *str )
1513 DWORD len = strlenW( str );
1514 memcpy( *ptr, str, len * sizeof(WCHAR) );
1515 *ptr = (WCHAR *)*ptr + len;
1516 return len * sizeof(WCHAR);
1519 /***********************************************************************
1520 * create_startup_info
1522 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1523 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1524 const STARTUPINFOW *startup, DWORD *info_size )
1526 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1527 startup_info_t *info;
1530 UNICODE_STRING newdir;
1531 WCHAR imagepath[MAX_PATH];
1532 HANDLE hstdin, hstdout, hstderr;
1534 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1535 lstrcpynW( imagepath, filename, MAX_PATH );
1536 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1537 lstrcpynW( imagepath, filename, MAX_PATH );
1539 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1541 newdir.Buffer = NULL;
1544 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1545 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1551 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1552 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1554 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1557 size = sizeof(*info);
1558 size += strlenW( cur_dir ) * sizeof(WCHAR);
1559 size += cur_params->DllPath.Length;
1560 size += strlenW( imagepath ) * sizeof(WCHAR);
1561 size += strlenW( cmdline ) * sizeof(WCHAR);
1562 if (startup->lpTitle) size += strlenW( startup->lpTitle ) * sizeof(WCHAR);
1563 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1564 /* FIXME: shellinfo */
1565 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1566 size = (size + 1) & ~1;
1569 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1571 info->console_flags = cur_params->ConsoleFlags;
1572 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1573 if (flags & CREATE_NEW_CONSOLE) info->console = (obj_handle_t)1; /* FIXME: cf. kernel_main.c */
1575 if (startup->dwFlags & STARTF_USESTDHANDLES)
1577 hstdin = startup->hStdInput;
1578 hstdout = startup->hStdOutput;
1579 hstderr = startup->hStdError;
1583 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1584 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1585 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1587 info->hstdin = wine_server_obj_handle( hstdin );
1588 info->hstdout = wine_server_obj_handle( hstdout );
1589 info->hstderr = wine_server_obj_handle( hstderr );
1590 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1592 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1593 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1594 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1595 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1599 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1600 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1601 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1604 info->x = startup->dwX;
1605 info->y = startup->dwY;
1606 info->xsize = startup->dwXSize;
1607 info->ysize = startup->dwYSize;
1608 info->xchars = startup->dwXCountChars;
1609 info->ychars = startup->dwYCountChars;
1610 info->attribute = startup->dwFillAttribute;
1611 info->flags = startup->dwFlags;
1612 info->show = startup->wShowWindow;
1615 info->curdir_len = append_string( &ptr, cur_dir );
1616 info->dllpath_len = cur_params->DllPath.Length;
1617 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1618 ptr = (char *)ptr + cur_params->DllPath.Length;
1619 info->imagepath_len = append_string( &ptr, imagepath );
1620 info->cmdline_len = append_string( &ptr, cmdline );
1621 if (startup->lpTitle) info->title_len = append_string( &ptr, startup->lpTitle );
1622 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1623 if (startup->lpReserved2 && startup->cbReserved2)
1625 info->runtime_len = startup->cbReserved2;
1626 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1630 RtlFreeUnicodeString( &newdir );
1635 /***********************************************************************
1638 * Create a new process. If hFile is a valid handle we have an exe
1639 * file, otherwise it is a Winelib app.
1641 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1642 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1643 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1644 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1645 const struct binary_info *binary_info, int exec_only )
1647 BOOL ret, success = FALSE;
1648 HANDLE process_info;
1650 char *winedebug = NULL;
1652 startup_info_t *startup_info;
1653 DWORD startup_info_size;
1654 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1658 if (sizeof(void *) == sizeof(int) && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1660 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename) );
1661 SetLastError( ERROR_BAD_EXE_FORMAT );
1665 RtlAcquirePebLock();
1667 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1668 &startup_info_size )))
1670 RtlReleasePebLock();
1673 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1677 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1678 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1680 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1681 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1682 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1684 env_end += strlenW(env_end) + 1;
1688 /* create the socket for the new process */
1690 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1692 RtlReleasePebLock();
1693 HeapFree( GetProcessHeap(), 0, winedebug );
1694 HeapFree( GetProcessHeap(), 0, startup_info );
1695 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1698 wine_server_send_fd( socketfd[1] );
1699 close( socketfd[1] );
1701 /* create the process on the server side */
1703 SERVER_START_REQ( new_process )
1705 req->inherit_all = inherit;
1706 req->create_flags = flags;
1707 req->socket_fd = socketfd[1];
1708 req->exe_file = wine_server_obj_handle( hFile );
1709 req->process_access = PROCESS_ALL_ACCESS;
1710 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1711 req->thread_access = THREAD_ALL_ACCESS;
1712 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1713 req->info_size = startup_info_size;
1715 wine_server_add_data( req, startup_info, startup_info_size );
1716 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1717 if ((ret = !wine_server_call_err( req )))
1719 info->dwProcessId = (DWORD)reply->pid;
1720 info->dwThreadId = (DWORD)reply->tid;
1721 info->hProcess = wine_server_ptr_handle( reply->phandle );
1722 info->hThread = wine_server_ptr_handle( reply->thandle );
1724 process_info = wine_server_ptr_handle( reply->info );
1728 RtlReleasePebLock();
1731 close( socketfd[0] );
1732 HeapFree( GetProcessHeap(), 0, startup_info );
1733 HeapFree( GetProcessHeap(), 0, winedebug );
1737 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1739 if (startup_info->hstdin)
1740 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1741 FILE_READ_DATA, &stdin_fd, NULL );
1742 if (startup_info->hstdout)
1743 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1744 FILE_WRITE_DATA, &stdout_fd, NULL );
1746 HeapFree( GetProcessHeap(), 0, startup_info );
1748 /* create the child process */
1749 argv = build_argv( cmd_line, 1 );
1751 if (exec_only || !(pid = fork())) /* child */
1753 char preloader_reserve[64], socket_env[64];
1755 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1757 if (!(pid = fork()))
1759 int fd = open( "/dev/null", O_RDWR );
1761 /* close stdin and stdout */
1769 else if (pid != -1) _exit(0); /* parent */
1773 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1774 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1777 if (stdin_fd != -1) close( stdin_fd );
1778 if (stdout_fd != -1) close( stdout_fd );
1780 /* Reset signals that we previously set to SIG_IGN */
1781 signal( SIGPIPE, SIG_DFL );
1782 signal( SIGCHLD, SIG_DFL );
1784 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1785 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1786 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1788 putenv( preloader_reserve );
1789 putenv( socket_env );
1790 if (winedebug) putenv( winedebug );
1791 if (unixdir) chdir(unixdir);
1793 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1797 /* this is the parent */
1799 if (stdin_fd != -1) close( stdin_fd );
1800 if (stdout_fd != -1) close( stdout_fd );
1801 close( socketfd[0] );
1802 HeapFree( GetProcessHeap(), 0, argv );
1803 HeapFree( GetProcessHeap(), 0, winedebug );
1810 /* wait for the new process info to be ready */
1812 WaitForSingleObject( process_info, INFINITE );
1813 SERVER_START_REQ( get_new_process_info )
1815 req->info = wine_server_obj_handle( process_info );
1816 wine_server_call( req );
1817 success = reply->success;
1818 err = reply->exit_code;
1824 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1827 CloseHandle( process_info );
1831 CloseHandle( process_info );
1832 CloseHandle( info->hProcess );
1833 CloseHandle( info->hThread );
1834 info->hProcess = info->hThread = 0;
1835 info->dwProcessId = info->dwThreadId = 0;
1840 /***********************************************************************
1841 * create_vdm_process
1843 * Create a new VDM process for a 16-bit or DOS application.
1845 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1846 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1847 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1848 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1849 const struct binary_info *binary_info, int exec_only )
1851 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1854 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1855 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1859 SetLastError( ERROR_OUTOFMEMORY );
1862 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1863 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1864 flags, startup, info, unixdir, binary_info, exec_only );
1865 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1870 /***********************************************************************
1871 * create_cmd_process
1873 * Create a new cmd shell process for a .BAT file.
1875 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1876 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1877 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1878 LPPROCESS_INFORMATION info )
1881 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1882 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1883 WCHAR comspec[MAX_PATH];
1887 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1889 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1890 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1893 strcpyW( newcmdline, comspec );
1894 strcatW( newcmdline, slashcW );
1895 strcatW( newcmdline, cmd_line );
1896 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1897 flags, env, cur_dir, startup, info );
1898 HeapFree( GetProcessHeap(), 0, newcmdline );
1903 /*************************************************************************
1906 * Helper for CreateProcess: retrieve the file name to load from the
1907 * app name and command line. Store the file name in buffer, and
1908 * return a possibly modified command line.
1909 * Also returns a handle to the opened file if it's a Windows binary.
1911 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1912 int buflen, HANDLE *handle, struct binary_info *binary_info )
1914 static const WCHAR quotesW[] = {'"','%','s','"',0};
1916 WCHAR *name, *pos, *ret = NULL;
1920 /* if we have an app name, everything is easy */
1924 /* use the unmodified app name as file name */
1925 lstrcpynW( buffer, appname, buflen );
1926 *handle = open_exe_file( buffer, binary_info );
1927 if (!(ret = cmdline) || !cmdline[0])
1929 /* no command-line, create one */
1930 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1931 sprintfW( ret, quotesW, appname );
1936 /* first check for a quoted file name */
1938 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1940 int len = p - cmdline - 1;
1941 /* extract the quoted portion as file name */
1942 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1943 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1946 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1947 ret = cmdline; /* no change necessary */
1951 /* now try the command-line word by word */
1953 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1961 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1963 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1968 if (*p) got_space = TRUE;
1971 if (ret && got_space) /* now build a new command-line with quotes */
1973 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1975 sprintfW( ret, quotesW, name );
1978 else if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1981 HeapFree( GetProcessHeap(), 0, name );
1986 /**********************************************************************
1987 * CreateProcessA (KERNEL32.@)
1989 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1990 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1991 DWORD flags, LPVOID env, LPCSTR cur_dir,
1992 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1995 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1996 UNICODE_STRING desktopW, titleW;
1999 desktopW.Buffer = NULL;
2000 titleW.Buffer = NULL;
2001 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2002 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2003 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2005 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2006 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2008 memcpy( &infoW, startup_info, sizeof(infoW) );
2009 infoW.lpDesktop = desktopW.Buffer;
2010 infoW.lpTitle = titleW.Buffer;
2012 if (startup_info->lpReserved)
2013 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2014 debugstr_a(startup_info->lpReserved));
2016 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
2017 inherit, flags, env, cur_dirW, &infoW, info );
2019 HeapFree( GetProcessHeap(), 0, app_nameW );
2020 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2021 HeapFree( GetProcessHeap(), 0, cur_dirW );
2022 RtlFreeUnicodeString( &desktopW );
2023 RtlFreeUnicodeString( &titleW );
2028 /**********************************************************************
2029 * CreateProcessW (KERNEL32.@)
2031 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2032 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2033 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2034 LPPROCESS_INFORMATION info )
2038 char *unixdir = NULL;
2039 WCHAR name[MAX_PATH];
2040 WCHAR *tidy_cmdline, *p, *envW = env;
2041 struct binary_info binary_info;
2043 /* Process the AppName and/or CmdLine to get module name and path */
2045 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2047 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2048 &hFile, &binary_info )))
2050 if (hFile == INVALID_HANDLE_VALUE) goto done;
2052 /* Warn if unsupported features are used */
2054 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2055 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2056 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2057 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2058 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2062 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2064 SetLastError(ERROR_DIRECTORY);
2070 WCHAR buf[MAX_PATH];
2071 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2074 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2079 while (*p) p += strlen(p) + 1;
2080 p++; /* final null */
2081 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2082 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2083 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2084 flags |= CREATE_UNICODE_ENVIRONMENT;
2087 info->hThread = info->hProcess = 0;
2088 info->dwProcessId = info->dwThreadId = 0;
2090 if (binary_info.flags & BINARY_FLAG_DLL)
2092 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2093 SetLastError( ERROR_BAD_EXE_FORMAT );
2095 else switch (binary_info.type)
2098 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2099 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2100 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2101 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2106 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2107 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2108 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2110 case BINARY_UNIX_LIB:
2111 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
2112 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2113 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2115 case BINARY_UNKNOWN:
2116 /* check for .com or .bat extension */
2117 if ((p = strrchrW( name, '.' )))
2119 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2121 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2122 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2123 inherit, flags, startup_info, info, unixdir,
2124 &binary_info, FALSE );
2127 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2129 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2130 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2131 inherit, flags, startup_info, info );
2136 case BINARY_UNIX_EXE:
2138 /* unknown file, try as unix executable */
2141 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2143 if ((unix_name = wine_get_unix_file_name( name )))
2145 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2146 HeapFree( GetProcessHeap(), 0, unix_name );
2151 if (hFile) CloseHandle( hFile );
2154 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2155 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2156 HeapFree( GetProcessHeap(), 0, unixdir );
2158 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2163 /**********************************************************************
2166 static void exec_process( LPCWSTR name )
2170 STARTUPINFOW startup_info;
2171 PROCESS_INFORMATION info;
2172 struct binary_info binary_info;
2174 hFile = open_exe_file( name, &binary_info );
2175 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2177 memset( &startup_info, 0, sizeof(startup_info) );
2178 startup_info.cb = sizeof(startup_info);
2180 /* Determine executable type */
2182 if (binary_info.flags & BINARY_FLAG_DLL) return;
2183 switch (binary_info.type)
2186 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2187 debugstr_w(name), binary_info.res_start, binary_info.res_end );
2188 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2189 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2191 case BINARY_UNIX_LIB:
2192 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2193 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2194 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2196 case BINARY_UNKNOWN:
2197 /* check for .com or .pif extension */
2198 if (!(p = strrchrW( name, '.' ))) break;
2199 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2204 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2205 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2206 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2211 CloseHandle( hFile );
2215 /***********************************************************************
2218 * Wrapper to call WaitForInputIdle USER function
2220 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2222 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2224 HMODULE mod = GetModuleHandleA( "user32.dll" );
2227 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2228 if (ptr) return ptr( process, timeout );
2234 /***********************************************************************
2235 * WinExec (KERNEL32.@)
2237 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2239 PROCESS_INFORMATION info;
2240 STARTUPINFOA startup;
2244 memset( &startup, 0, sizeof(startup) );
2245 startup.cb = sizeof(startup);
2246 startup.dwFlags = STARTF_USESHOWWINDOW;
2247 startup.wShowWindow = nCmdShow;
2249 /* cmdline needs to be writable for CreateProcess */
2250 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2251 strcpy( cmdline, lpCmdLine );
2253 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2254 0, NULL, NULL, &startup, &info ))
2256 /* Give 30 seconds to the app to come up */
2257 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2258 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2260 /* Close off the handles */
2261 CloseHandle( info.hThread );
2262 CloseHandle( info.hProcess );
2264 else if ((ret = GetLastError()) >= 32)
2266 FIXME("Strange error set by CreateProcess: %d\n", ret );
2269 HeapFree( GetProcessHeap(), 0, cmdline );
2274 /**********************************************************************
2275 * LoadModule (KERNEL32.@)
2277 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2279 LOADPARMS32 *params = paramBlock;
2280 PROCESS_INFORMATION info;
2281 STARTUPINFOA startup;
2282 HINSTANCE hInstance;
2284 char filename[MAX_PATH];
2287 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2289 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2290 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2291 return ULongToHandle(GetLastError());
2293 len = (BYTE)params->lpCmdLine[0];
2294 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2295 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2297 strcpy( cmdline, filename );
2298 p = cmdline + strlen(cmdline);
2300 memcpy( p, params->lpCmdLine + 1, len );
2303 memset( &startup, 0, sizeof(startup) );
2304 startup.cb = sizeof(startup);
2305 if (params->lpCmdShow)
2307 startup.dwFlags = STARTF_USESHOWWINDOW;
2308 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2311 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2312 params->lpEnvAddress, NULL, &startup, &info ))
2314 /* Give 30 seconds to the app to come up */
2315 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2316 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2317 hInstance = (HINSTANCE)33;
2318 /* Close off the handles */
2319 CloseHandle( info.hThread );
2320 CloseHandle( info.hProcess );
2322 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2324 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2325 hInstance = (HINSTANCE)11;
2328 HeapFree( GetProcessHeap(), 0, cmdline );
2333 /******************************************************************************
2334 * TerminateProcess (KERNEL32.@)
2336 * Terminates a process.
2339 * handle [I] Process to terminate.
2340 * exit_code [I] Exit code.
2344 * Failure: FALSE, check GetLastError().
2346 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2348 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2349 if (status) SetLastError( RtlNtStatusToDosError(status) );
2353 /***********************************************************************
2354 * ExitProcess (KERNEL32.@)
2356 * Exits the current process.
2359 * status [I] Status code to exit with.
2365 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2367 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2368 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2369 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2371 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2375 void WINAPI process_ExitProcess( DWORD status )
2377 LdrShutdownProcess();
2378 NtTerminateProcess(GetCurrentProcess(), status);
2384 void WINAPI ExitProcess( DWORD status )
2386 LdrShutdownProcess();
2387 NtTerminateProcess(GetCurrentProcess(), status);
2393 /***********************************************************************
2394 * GetExitCodeProcess [KERNEL32.@]
2396 * Gets termination status of specified process.
2399 * hProcess [in] Handle to the process.
2400 * lpExitCode [out] Address to receive termination status.
2406 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2409 PROCESS_BASIC_INFORMATION pbi;
2411 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2413 if (status == STATUS_SUCCESS)
2415 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2418 SetLastError( RtlNtStatusToDosError(status) );
2423 /***********************************************************************
2424 * SetErrorMode (KERNEL32.@)
2426 UINT WINAPI SetErrorMode( UINT mode )
2428 UINT old = process_error_mode;
2429 process_error_mode = mode;
2433 /***********************************************************************
2434 * GetErrorMode (KERNEL32.@)
2436 UINT WINAPI GetErrorMode( void )
2438 return process_error_mode;
2441 /**********************************************************************
2442 * TlsAlloc [KERNEL32.@]
2444 * Allocates a thread local storage index.
2447 * Success: TLS index.
2448 * Failure: 0xFFFFFFFF
2450 DWORD WINAPI TlsAlloc( void )
2453 PEB * const peb = NtCurrentTeb()->Peb;
2455 RtlAcquirePebLock();
2456 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2457 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2460 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2463 if (!NtCurrentTeb()->TlsExpansionSlots &&
2464 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2465 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2467 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2469 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2473 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2474 index += TLS_MINIMUM_AVAILABLE;
2477 else SetLastError( ERROR_NO_MORE_ITEMS );
2479 RtlReleasePebLock();
2484 /**********************************************************************
2485 * TlsFree [KERNEL32.@]
2487 * Releases a thread local storage index, making it available for reuse.
2490 * index [in] TLS index to free.
2496 BOOL WINAPI TlsFree( DWORD index )
2500 RtlAcquirePebLock();
2501 if (index >= TLS_MINIMUM_AVAILABLE)
2503 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2504 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2508 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2509 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2511 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2512 else SetLastError( ERROR_INVALID_PARAMETER );
2513 RtlReleasePebLock();
2518 /**********************************************************************
2519 * TlsGetValue [KERNEL32.@]
2521 * Gets value in a thread's TLS slot.
2524 * index [in] TLS index to retrieve value for.
2527 * Success: Value stored in calling thread's TLS slot for index.
2528 * Failure: 0 and GetLastError() returns NO_ERROR.
2530 LPVOID WINAPI TlsGetValue( DWORD index )
2534 if (index < TLS_MINIMUM_AVAILABLE)
2536 ret = NtCurrentTeb()->TlsSlots[index];
2540 index -= TLS_MINIMUM_AVAILABLE;
2541 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2543 SetLastError( ERROR_INVALID_PARAMETER );
2546 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2547 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2549 SetLastError( ERROR_SUCCESS );
2554 /**********************************************************************
2555 * TlsSetValue [KERNEL32.@]
2557 * Stores a value in the thread's TLS slot.
2560 * index [in] TLS index to set value for.
2561 * value [in] Value to be stored.
2567 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2569 if (index < TLS_MINIMUM_AVAILABLE)
2571 NtCurrentTeb()->TlsSlots[index] = value;
2575 index -= TLS_MINIMUM_AVAILABLE;
2576 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2578 SetLastError( ERROR_INVALID_PARAMETER );
2581 if (!NtCurrentTeb()->TlsExpansionSlots &&
2582 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2583 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2585 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2588 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2594 /***********************************************************************
2595 * GetProcessFlags (KERNEL32.@)
2597 DWORD WINAPI GetProcessFlags( DWORD processid )
2599 IMAGE_NT_HEADERS *nt;
2602 if (processid && processid != GetCurrentProcessId()) return 0;
2604 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2606 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2607 flags |= PDB32_CONSOLE_PROC;
2609 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2610 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2615 /***********************************************************************
2616 * GetProcessDword (KERNEL32.18)
2618 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2620 FIXME( "(%d, %d): not supported\n", dwProcessID, offset );
2625 /*********************************************************************
2626 * OpenProcess (KERNEL32.@)
2628 * Opens a handle to a process.
2631 * access [I] Desired access rights assigned to the returned handle.
2632 * inherit [I] Determines whether or not child processes will inherit the handle.
2633 * id [I] Process identifier of the process to get a handle to.
2636 * Success: Valid handle to the specified process.
2637 * Failure: NULL, check GetLastError().
2639 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2643 OBJECT_ATTRIBUTES attr;
2646 cid.UniqueProcess = ULongToHandle(id);
2647 cid.UniqueThread = 0; /* FIXME ? */
2649 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2650 attr.RootDirectory = NULL;
2651 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2652 attr.SecurityDescriptor = NULL;
2653 attr.SecurityQualityOfService = NULL;
2654 attr.ObjectName = NULL;
2656 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2658 status = NtOpenProcess(&handle, access, &attr, &cid);
2659 if (status != STATUS_SUCCESS)
2661 SetLastError( RtlNtStatusToDosError(status) );
2668 /*********************************************************************
2669 * GetProcessId (KERNEL32.@)
2671 * Gets the a unique identifier of a process.
2674 * hProcess [I] Handle to the process.
2678 * Failure: FALSE, check GetLastError().
2682 * The identifier is unique only on the machine and only until the process
2683 * exits (including system shutdown).
2685 DWORD WINAPI GetProcessId( HANDLE hProcess )
2688 PROCESS_BASIC_INFORMATION pbi;
2690 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2692 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2693 SetLastError( RtlNtStatusToDosError(status) );
2698 /*********************************************************************
2699 * CloseHandle (KERNEL32.@)
2704 * handle [I] Handle to close.
2708 * Failure: FALSE, check GetLastError().
2710 BOOL WINAPI CloseHandle( HANDLE handle )
2714 /* stdio handles need special treatment */
2715 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2716 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2717 (handle == (HANDLE)STD_ERROR_HANDLE))
2718 handle = GetStdHandle( HandleToULong(handle) );
2720 if (is_console_handle(handle))
2721 return CloseConsoleHandle(handle);
2723 status = NtClose( handle );
2724 if (status) SetLastError( RtlNtStatusToDosError(status) );
2729 /*********************************************************************
2730 * GetHandleInformation (KERNEL32.@)
2732 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2734 OBJECT_DATA_INFORMATION info;
2735 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2737 if (status) SetLastError( RtlNtStatusToDosError(status) );
2741 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2742 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2748 /*********************************************************************
2749 * SetHandleInformation (KERNEL32.@)
2751 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2753 OBJECT_DATA_INFORMATION info;
2756 /* if not setting both fields, retrieve current value first */
2757 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2758 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2760 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2762 SetLastError( RtlNtStatusToDosError(status) );
2766 if (mask & HANDLE_FLAG_INHERIT)
2767 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2768 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2769 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2771 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2772 if (status) SetLastError( RtlNtStatusToDosError(status) );
2777 /*********************************************************************
2778 * DuplicateHandle (KERNEL32.@)
2780 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2781 HANDLE dest_process, HANDLE *dest,
2782 DWORD access, BOOL inherit, DWORD options )
2786 if (is_console_handle(source))
2788 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2789 if (source_process != dest_process ||
2790 source_process != GetCurrentProcess())
2792 SetLastError(ERROR_INVALID_PARAMETER);
2795 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2796 return (*dest != INVALID_HANDLE_VALUE);
2798 status = NtDuplicateObject( source_process, source, dest_process, dest,
2799 access, inherit ? OBJ_INHERIT : 0, options );
2800 if (status) SetLastError( RtlNtStatusToDosError(status) );
2805 /***********************************************************************
2806 * ConvertToGlobalHandle (KERNEL32.@)
2808 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2810 HANDLE ret = INVALID_HANDLE_VALUE;
2811 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2812 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2817 /***********************************************************************
2818 * SetHandleContext (KERNEL32.@)
2820 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2822 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2823 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2824 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2829 /***********************************************************************
2830 * GetHandleContext (KERNEL32.@)
2832 DWORD WINAPI GetHandleContext(HANDLE hnd)
2834 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2835 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2836 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2841 /***********************************************************************
2842 * CreateSocketHandle (KERNEL32.@)
2844 HANDLE WINAPI CreateSocketHandle(void)
2846 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2847 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2848 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2849 return INVALID_HANDLE_VALUE;
2853 /***********************************************************************
2854 * SetPriorityClass (KERNEL32.@)
2856 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2859 PROCESS_PRIORITY_CLASS ppc;
2861 ppc.Foreground = FALSE;
2862 switch (priorityclass)
2864 case IDLE_PRIORITY_CLASS:
2865 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2866 case BELOW_NORMAL_PRIORITY_CLASS:
2867 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2868 case NORMAL_PRIORITY_CLASS:
2869 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2870 case ABOVE_NORMAL_PRIORITY_CLASS:
2871 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2872 case HIGH_PRIORITY_CLASS:
2873 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2874 case REALTIME_PRIORITY_CLASS:
2875 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2877 SetLastError(ERROR_INVALID_PARAMETER);
2881 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2884 if (status != STATUS_SUCCESS)
2886 SetLastError( RtlNtStatusToDosError(status) );
2893 /***********************************************************************
2894 * GetPriorityClass (KERNEL32.@)
2896 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2899 PROCESS_BASIC_INFORMATION pbi;
2901 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2903 if (status != STATUS_SUCCESS)
2905 SetLastError( RtlNtStatusToDosError(status) );
2908 switch (pbi.BasePriority)
2910 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2911 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2912 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2913 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2914 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2915 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2917 SetLastError( ERROR_INVALID_PARAMETER );
2922 /***********************************************************************
2923 * SetProcessAffinityMask (KERNEL32.@)
2925 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2929 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2930 &affmask, sizeof(DWORD_PTR));
2933 SetLastError( RtlNtStatusToDosError(status) );
2940 /**********************************************************************
2941 * GetProcessAffinityMask (KERNEL32.@)
2943 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2944 PDWORD_PTR lpProcessAffinityMask,
2945 PDWORD_PTR lpSystemAffinityMask )
2947 PROCESS_BASIC_INFORMATION pbi;
2950 status = NtQueryInformationProcess(hProcess,
2951 ProcessBasicInformation,
2952 &pbi, sizeof(pbi), NULL);
2955 SetLastError( RtlNtStatusToDosError(status) );
2958 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2959 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2964 /***********************************************************************
2965 * GetProcessVersion (KERNEL32.@)
2967 DWORD WINAPI GetProcessVersion( DWORD pid )
2971 PROCESS_BASIC_INFORMATION pbi;
2974 IMAGE_DOS_HEADER dos;
2975 IMAGE_NT_HEADERS nt;
2978 if (!pid || pid == GetCurrentProcessId())
2980 IMAGE_NT_HEADERS *nt;
2982 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2983 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2984 nt->OptionalHeader.MinorSubsystemVersion);
2988 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2989 if (!process) return 0;
2991 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2992 if (status) goto err;
2994 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2995 if (status || count != sizeof(peb)) goto err;
2997 memset(&dos, 0, sizeof(dos));
2998 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2999 if (status || count != sizeof(dos)) goto err;
3000 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3002 memset(&nt, 0, sizeof(nt));
3003 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3004 if (status || count != sizeof(nt)) goto err;
3005 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3007 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3010 CloseHandle(process);
3012 if (status != STATUS_SUCCESS)
3013 SetLastError(RtlNtStatusToDosError(status));
3019 /***********************************************************************
3020 * SetProcessWorkingSetSize [KERNEL32.@]
3021 * Sets the min/max working set sizes for a specified process.
3024 * hProcess [I] Handle to the process of interest
3025 * minset [I] Specifies minimum working set size
3026 * maxset [I] Specifies maximum working set size
3032 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3035 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3036 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3037 /* Trim the working set to zero */
3038 /* Swap the process out of physical RAM */
3043 /***********************************************************************
3044 * GetProcessWorkingSetSize (KERNEL32.@)
3046 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3049 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3050 /* 32 MB working set size */
3051 if (minset) *minset = 32*1024*1024;
3052 if (maxset) *maxset = 32*1024*1024;
3057 /***********************************************************************
3058 * SetProcessShutdownParameters (KERNEL32.@)
3060 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3062 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3063 shutdown_flags = flags;
3064 shutdown_priority = level;
3069 /***********************************************************************
3070 * GetProcessShutdownParameters (KERNEL32.@)
3073 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3075 *lpdwLevel = shutdown_priority;
3076 *lpdwFlags = shutdown_flags;
3081 /***********************************************************************
3082 * GetProcessPriorityBoost (KERNEL32.@)
3084 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3086 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3088 /* Report that no boost is present.. */
3089 *pDisablePriorityBoost = FALSE;
3094 /***********************************************************************
3095 * SetProcessPriorityBoost (KERNEL32.@)
3097 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3099 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3100 /* Say we can do it. I doubt the program will notice that we don't. */
3105 /***********************************************************************
3106 * ReadProcessMemory (KERNEL32.@)
3108 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3109 SIZE_T *bytes_read )
3111 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3112 if (status) SetLastError( RtlNtStatusToDosError(status) );
3117 /***********************************************************************
3118 * WriteProcessMemory (KERNEL32.@)
3120 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3121 SIZE_T *bytes_written )
3123 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3124 if (status) SetLastError( RtlNtStatusToDosError(status) );
3129 /****************************************************************************
3130 * FlushInstructionCache (KERNEL32.@)
3132 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3135 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3136 if (status) SetLastError( RtlNtStatusToDosError(status) );
3141 /******************************************************************
3142 * GetProcessIoCounters (KERNEL32.@)
3144 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3148 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3149 ioc, sizeof(*ioc), NULL);
3150 if (status) SetLastError( RtlNtStatusToDosError(status) );
3154 /******************************************************************
3155 * GetProcessHandleCount (KERNEL32.@)
3157 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3161 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3162 cnt, sizeof(*cnt), NULL);
3163 if (status) SetLastError( RtlNtStatusToDosError(status) );
3167 /******************************************************************
3168 * QueryFullProcessImageNameA (KERNEL32.@)
3170 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3173 DWORD pdwSizeW = *pdwSize;
3174 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3176 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3179 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3180 lpExeName, *pdwSize, NULL, NULL));
3182 *pdwSize = strlen(lpExeName);
3184 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3188 /******************************************************************
3189 * QueryFullProcessImageNameW (KERNEL32.@)
3191 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3193 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3194 UNICODE_STRING *dynamic_buffer = NULL;
3195 UNICODE_STRING nt_path;
3196 UNICODE_STRING *result = NULL;
3200 RtlInitUnicodeStringEx(&nt_path, NULL);
3201 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3202 * as this is on Wine. */
3203 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3204 sizeof(buffer) - sizeof(WCHAR), &needed);
3205 if (status == STATUS_INFO_LENGTH_MISMATCH)
3207 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3208 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3209 result = dynamic_buffer;
3212 result = (PUNICODE_STRING)buffer;
3214 if (status) goto cleanup;
3216 if (dwFlags & PROCESS_NAME_NATIVE)
3218 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3219 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3221 status = STATUS_OBJECT_PATH_NOT_FOUND;
3227 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3229 status = STATUS_BUFFER_TOO_SMALL;
3233 *pdwSize = result->Length/sizeof(WCHAR);
3234 memcpy( lpExeName, result->Buffer, result->Length );
3235 lpExeName[*pdwSize] = 0;
3238 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3239 RtlFreeUnicodeString(&nt_path);
3240 if (status) SetLastError( RtlNtStatusToDosError(status) );
3244 /***********************************************************************
3245 * ProcessIdToSessionId (KERNEL32.@)
3246 * This function is available on Terminal Server 4SP4 and Windows 2000
3248 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3250 /* According to MSDN, if the calling process is not in a terminal
3251 * services environment, then the sessionid returned is zero.
3258 /***********************************************************************
3259 * RegisterServiceProcess (KERNEL32.@)
3261 * A service process calls this function to ensure that it continues to run
3262 * even after a user logged off.
3264 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3266 /* I don't think that Wine needs to do anything in this function */
3267 return 1; /* success */
3271 /**********************************************************************
3272 * IsWow64Process (KERNEL32.@)
3274 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3279 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3281 if (status != STATUS_SUCCESS)
3283 SetLastError( RtlNtStatusToDosError( status ) );
3286 *Wow64Process = (pbi != 0);
3291 /***********************************************************************
3292 * GetCurrentProcess (KERNEL32.@)
3294 * Get a handle to the current process.
3300 * A handle representing the current process.
3302 #undef GetCurrentProcess
3303 HANDLE WINAPI GetCurrentProcess(void)
3305 return (HANDLE)~(ULONG_PTR)0;
3308 /***********************************************************************
3309 * CmdBatNotification (KERNEL32.@)
3311 * Notifies the system that a batch file has started or finished.
3314 * bBatchRunning [I] TRUE if a batch file has started or
3315 * FALSE if a batch file has finished executing.
3320 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3322 FIXME("%d\n", bBatchRunning);
3327 /***********************************************************************
3328 * RegisterApplicationRestart (KERNEL32.@)
3330 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3332 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3337 /**********************************************************************
3338 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3340 DWORD WINAPI WTSGetActiveConsoleSessionId(void)