push 556f62bab943c37bb6cbad95a6ecb3d73e04a93f
[wine/hacks.git] / dlls / kernel32 / process.c
blob624d4de544d901982fe17853e27ca98d7d229890
1 /*
2 * Win32 processes
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <time.h>
30 #ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
32 #endif
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
35 #endif
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
38 #endif
39 #ifdef HAVE_SYS_PRCTL_H
40 # include <sys/prctl.h>
41 #endif
42 #include <sys/types.h>
44 #include "ntstatus.h"
45 #define WIN32_NO_STATUS
46 #include "wine/winbase16.h"
47 #include "wine/winuser16.h"
48 #include "winternl.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);
59 #ifdef __APPLE__
60 extern char **__wine_get_main_environment(void);
61 #else
62 extern char **__wine_main_environ;
63 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
64 #endif
66 typedef struct
68 LPSTR lpEnvAddress;
69 LPSTR lpCmdLine;
70 LPSTR lpCmdShow;
71 DWORD dwReserved;
72 } LOADPARMS32;
74 static UINT process_error_mode;
76 static DWORD shutdown_flags = 0;
77 static DWORD shutdown_priority = 0x280;
78 static DWORD process_dword;
80 HMODULE kernel32_handle = 0;
82 const WCHAR *DIR_Windows = NULL;
83 const WCHAR *DIR_System = NULL;
85 /* Process flags */
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 /***********************************************************************
105 * contains_path
107 static inline int contains_path( LPCWSTR name )
109 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
113 /***********************************************************************
114 * is_special_env_var
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 /***************************************************************************
129 * get_builtin_path
131 * Get the path of a builtin module when the native file does not exist.
133 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
135 WCHAR *file_part;
136 UINT len = strlenW( DIR_System );
138 if (contains_path( libname ))
140 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
141 filename, &file_part ) > size * sizeof(WCHAR))
142 return FALSE; /* too long */
144 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
145 return FALSE;
146 while (filename[len] == '\\') len++;
147 if (filename + len != file_part) return FALSE;
149 else
151 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
152 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
153 file_part = filename + len;
154 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
155 strcpyW( file_part, libname );
157 if (ext && !strchrW( file_part, '.' ))
159 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
160 return FALSE; /* too long */
161 strcatW( file_part, ext );
163 return TRUE;
167 /***********************************************************************
168 * open_builtin_exe_file
170 * Open an exe file for a builtin exe.
172 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
173 int test_only, int *file_exists )
175 char exename[MAX_PATH];
176 WCHAR *p;
177 UINT i, len;
179 *file_exists = 0;
180 if ((p = strrchrW( name, '/' ))) name = p + 1;
181 if ((p = strrchrW( name, '\\' ))) name = p + 1;
183 /* we don't want to depend on the current codepage here */
184 len = strlenW( name ) + 1;
185 if (len >= sizeof(exename)) return NULL;
186 for (i = 0; i < len; i++)
188 if (name[i] > 127) return NULL;
189 exename[i] = (char)name[i];
190 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
192 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
196 /***********************************************************************
197 * open_exe_file
199 * Open a specific exe file, taking load order into account.
200 * Returns the file handle or 0 for a builtin exe.
202 static HANDLE open_exe_file( const WCHAR *name )
204 HANDLE handle;
206 TRACE("looking for %s\n", debugstr_w(name) );
208 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
209 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
211 WCHAR buffer[MAX_PATH];
212 /* file doesn't exist, check for builtin */
213 if (!contains_path( name )) goto error;
214 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
215 handle = 0;
217 return handle;
219 error:
220 SetLastError( ERROR_FILE_NOT_FOUND );
221 return INVALID_HANDLE_VALUE;
225 /***********************************************************************
226 * find_exe_file
228 * Open an exe file, and return the full name and file handle.
229 * Returns FALSE if file could not be found.
230 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
231 * If file is a builtin exe, returns TRUE and sets handle to 0.
233 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
235 static const WCHAR exeW[] = {'.','e','x','e',0};
236 int file_exists;
238 TRACE("looking for %s\n", debugstr_w(name) );
240 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
241 !get_builtin_path( name, exeW, buffer, buflen ))
243 /* no builtin found, try native without extension in case it is a Unix app */
245 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
247 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
248 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
249 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
250 return TRUE;
252 return FALSE;
255 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
256 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
257 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
258 return TRUE;
260 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
261 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
262 if (file_exists)
264 *handle = 0;
265 return TRUE;
268 return FALSE;
272 /***********************************************************************
273 * build_initial_environment
275 * Build the Win32 environment from the Unix environment
277 static BOOL build_initial_environment(void)
279 SIZE_T size = 1;
280 char **e;
281 WCHAR *p, *endptr;
282 void *ptr;
283 char **env = __wine_get_main_environment();
285 /* Compute the total size of the Unix environment */
286 for (e = env; *e; e++)
288 if (is_special_env_var( *e )) continue;
289 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
291 size *= sizeof(WCHAR);
293 /* Now allocate the environment */
294 ptr = NULL;
295 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
296 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
297 return FALSE;
299 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
300 endptr = p + size / sizeof(WCHAR);
302 /* And fill it with the Unix environment */
303 for (e = env; *e; e++)
305 char *str = *e;
307 /* skip Unix special variables and use the Wine variants instead */
308 if (!strncmp( str, "WINE", 4 ))
310 if (is_special_env_var( str + 4 )) str += 4;
311 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
313 else if (is_special_env_var( str )) continue; /* skip it */
315 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
316 p += strlenW(p) + 1;
318 *p = 0;
319 return TRUE;
323 /***********************************************************************
324 * set_registry_variables
326 * Set environment variables by enumerating the values of a key;
327 * helper for set_registry_environment().
328 * Note that Windows happily truncates the value if it's too big.
330 static void set_registry_variables( HANDLE hkey, ULONG type )
332 UNICODE_STRING env_name, env_value;
333 NTSTATUS status;
334 DWORD size;
335 int index;
336 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
337 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
339 for (index = 0; ; index++)
341 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
342 buffer, sizeof(buffer), &size );
343 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
344 break;
345 if (info->Type != type)
346 continue;
347 env_name.Buffer = info->Name;
348 env_name.Length = env_name.MaximumLength = info->NameLength;
349 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
350 env_value.Length = env_value.MaximumLength = info->DataLength;
351 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
352 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
353 if (info->Type == REG_EXPAND_SZ)
355 WCHAR buf_expanded[1024];
356 UNICODE_STRING env_expanded;
357 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
358 env_expanded.Buffer=buf_expanded;
359 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
360 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
361 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
363 else
365 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
371 /***********************************************************************
372 * set_registry_environment
374 * Set the environment variables specified in the registry.
376 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
377 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
378 * on the order in which the variables are processed. But on Windows it
379 * does not really matter since they only use %SystemDrive% and
380 * %SystemRoot% which are predefined. But Wine defines these in the
381 * registry, so we need two passes.
383 static BOOL set_registry_environment(void)
385 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
386 'S','y','s','t','e','m','\\',
387 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
388 'C','o','n','t','r','o','l','\\',
389 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
390 'E','n','v','i','r','o','n','m','e','n','t',0};
391 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
393 OBJECT_ATTRIBUTES attr;
394 UNICODE_STRING nameW;
395 HANDLE hkey;
396 BOOL ret = FALSE;
398 attr.Length = sizeof(attr);
399 attr.RootDirectory = 0;
400 attr.ObjectName = &nameW;
401 attr.Attributes = 0;
402 attr.SecurityDescriptor = NULL;
403 attr.SecurityQualityOfService = NULL;
405 /* first the system environment variables */
406 RtlInitUnicodeString( &nameW, env_keyW );
407 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
409 set_registry_variables( hkey, REG_SZ );
410 set_registry_variables( hkey, REG_EXPAND_SZ );
411 NtClose( hkey );
412 ret = TRUE;
415 /* then the ones for the current user */
416 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
417 RtlInitUnicodeString( &nameW, envW );
418 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
420 set_registry_variables( hkey, REG_SZ );
421 set_registry_variables( hkey, REG_EXPAND_SZ );
422 NtClose( hkey );
424 NtClose( attr.RootDirectory );
425 return ret;
429 /***********************************************************************
430 * get_reg_value
432 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
434 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
435 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
436 DWORD len, size = sizeof(buffer);
437 WCHAR *ret = NULL;
438 UNICODE_STRING nameW;
440 RtlInitUnicodeString( &nameW, name );
441 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
442 return NULL;
444 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
445 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
447 if (info->Type == REG_EXPAND_SZ)
449 UNICODE_STRING value, expanded;
451 value.MaximumLength = len * sizeof(WCHAR);
452 value.Buffer = (WCHAR *)info->Data;
453 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
454 value.Length = len * sizeof(WCHAR);
455 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
456 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
457 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
458 else RtlFreeUnicodeString( &expanded );
460 else if (info->Type == REG_SZ)
462 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
464 memcpy( ret, info->Data, len * sizeof(WCHAR) );
465 ret[len] = 0;
468 return ret;
472 /***********************************************************************
473 * set_additional_environment
475 * Set some additional environment variables not specified in the registry.
477 static void set_additional_environment(void)
479 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
480 'S','o','f','t','w','a','r','e','\\',
481 'M','i','c','r','o','s','o','f','t','\\',
482 'W','i','n','d','o','w','s',' ','N','T','\\',
483 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
484 'P','r','o','f','i','l','e','L','i','s','t',0};
485 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
486 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
487 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
488 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
489 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
490 OBJECT_ATTRIBUTES attr;
491 UNICODE_STRING nameW;
492 WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
493 HANDLE hkey;
494 const char *name = wine_get_user_name();
495 DWORD len;
497 /* set the USERNAME variable */
499 len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
500 if (len)
502 user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
503 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
504 SetEnvironmentVariableW( usernameW, user_name );
506 else WARN( "user name %s not convertible.\n", debugstr_a(name) );
508 /* set the USERPROFILE and ALLUSERSPROFILE variables */
510 attr.Length = sizeof(attr);
511 attr.RootDirectory = 0;
512 attr.ObjectName = &nameW;
513 attr.Attributes = 0;
514 attr.SecurityDescriptor = NULL;
515 attr.SecurityQualityOfService = NULL;
516 RtlInitUnicodeString( &nameW, profile_keyW );
517 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
519 profile_dir = get_reg_value( hkey, profiles_valueW );
520 all_users_dir = get_reg_value( hkey, all_users_valueW );
521 NtClose( hkey );
524 if (profile_dir)
526 WCHAR *value, *p;
528 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
529 len += strlenW(profile_dir) + 1;
530 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
531 strcpyW( value, profile_dir );
532 p = value + strlenW(value);
533 if (p > value && p[-1] != '\\') *p++ = '\\';
534 if (user_name) {
535 strcpyW( p, user_name );
536 SetEnvironmentVariableW( userprofileW, value );
538 if (all_users_dir)
540 strcpyW( p, all_users_dir );
541 SetEnvironmentVariableW( allusersW, value );
543 HeapFree( GetProcessHeap(), 0, value );
546 HeapFree( GetProcessHeap(), 0, all_users_dir );
547 HeapFree( GetProcessHeap(), 0, profile_dir );
548 HeapFree( GetProcessHeap(), 0, user_name );
551 /***********************************************************************
552 * set_library_wargv
554 * Set the Wine library Unicode argv global variables.
556 static void set_library_wargv( char **argv )
558 int argc;
559 char *q;
560 WCHAR *p;
561 WCHAR **wargv;
562 DWORD total = 0;
564 for (argc = 0; argv[argc]; argc++)
565 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
567 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
568 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
569 p = (WCHAR *)(wargv + argc + 1);
570 for (argc = 0; argv[argc]; argc++)
572 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
573 wargv[argc] = p;
574 p += reslen;
575 total -= reslen;
577 wargv[argc] = NULL;
579 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
581 for (argc = 0; wargv[argc]; argc++)
582 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
584 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
585 q = (char *)(argv + argc + 1);
586 for (argc = 0; wargv[argc]; argc++)
588 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
589 argv[argc] = q;
590 q += reslen;
591 total -= reslen;
593 argv[argc] = NULL;
595 __wine_main_argc = argc;
596 __wine_main_argv = argv;
597 __wine_main_wargv = wargv;
601 /***********************************************************************
602 * update_library_argv0
604 * Update the argv[0] global variable with the binary we have found.
606 static void update_library_argv0( const WCHAR *argv0 )
608 DWORD len = strlenW( argv0 );
610 if (len > strlenW( __wine_main_wargv[0] ))
612 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
614 strcpyW( __wine_main_wargv[0], argv0 );
616 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
617 if (len > strlen( __wine_main_argv[0] ) + 1)
619 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
621 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
625 /***********************************************************************
626 * build_command_line
628 * Build the command line of a process from the argv array.
630 * Note that it does NOT necessarily include the file name.
631 * Sometimes we don't even have any command line options at all.
633 * We must quote and escape characters so that the argv array can be rebuilt
634 * from the command line:
635 * - spaces and tabs must be quoted
636 * 'a b' -> '"a b"'
637 * - quotes must be escaped
638 * '"' -> '\"'
639 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
640 * resulting in an odd number of '\' followed by a '"'
641 * '\"' -> '\\\"'
642 * '\\"' -> '\\\\\"'
643 * - '\'s that are not followed by a '"' can be left as is
644 * 'a\b' == 'a\b'
645 * 'a\\b' == 'a\\b'
647 static BOOL build_command_line( WCHAR **argv )
649 int len;
650 WCHAR **arg;
651 LPWSTR p;
652 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
654 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
656 len = 0;
657 for (arg = argv; *arg; arg++)
659 int has_space,bcount;
660 WCHAR* a;
662 has_space=0;
663 bcount=0;
664 a=*arg;
665 if( !*a ) has_space=1;
666 while (*a!='\0') {
667 if (*a=='\\') {
668 bcount++;
669 } else {
670 if (*a==' ' || *a=='\t') {
671 has_space=1;
672 } else if (*a=='"') {
673 /* doubling of '\' preceding a '"',
674 * plus escaping of said '"'
676 len+=2*bcount+1;
678 bcount=0;
680 a++;
682 len+=(a-*arg)+1 /* for the separating space */;
683 if (has_space)
684 len+=2; /* for the quotes */
687 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
688 return FALSE;
690 p = rupp->CommandLine.Buffer;
691 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
692 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
693 for (arg = argv; *arg; arg++)
695 int has_space,has_quote;
696 WCHAR* a;
698 /* Check for quotes and spaces in this argument */
699 has_space=has_quote=0;
700 a=*arg;
701 if( !*a ) has_space=1;
702 while (*a!='\0') {
703 if (*a==' ' || *a=='\t') {
704 has_space=1;
705 if (has_quote)
706 break;
707 } else if (*a=='"') {
708 has_quote=1;
709 if (has_space)
710 break;
712 a++;
715 /* Now transfer it to the command line */
716 if (has_space)
717 *p++='"';
718 if (has_quote) {
719 int bcount;
720 WCHAR* a;
722 bcount=0;
723 a=*arg;
724 while (*a!='\0') {
725 if (*a=='\\') {
726 *p++=*a;
727 bcount++;
728 } else {
729 if (*a=='"') {
730 int i;
732 /* Double all the '\\' preceding this '"', plus one */
733 for (i=0;i<=bcount;i++)
734 *p++='\\';
735 *p++='"';
736 } else {
737 *p++=*a;
739 bcount=0;
741 a++;
743 } else {
744 WCHAR* x = *arg;
745 while ((*p=*x++)) p++;
747 if (has_space)
748 *p++='"';
749 *p++=' ';
751 if (p > rupp->CommandLine.Buffer)
752 p--; /* remove last space */
753 *p = '\0';
755 return TRUE;
759 /***********************************************************************
760 * init_current_directory
762 * Initialize the current directory from the Unix cwd or the parent info.
764 static void init_current_directory( CURDIR *cur_dir )
766 UNICODE_STRING dir_str;
767 char *cwd;
768 int size;
770 /* if we received a cur dir from the parent, try this first */
772 if (cur_dir->DosPath.Length)
774 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
777 /* now try to get it from the Unix cwd */
779 for (size = 256; ; size *= 2)
781 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
782 if (getcwd( cwd, size )) break;
783 HeapFree( GetProcessHeap(), 0, cwd );
784 if (errno == ERANGE) continue;
785 cwd = NULL;
786 break;
789 if (cwd)
791 WCHAR *dirW;
792 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
793 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
795 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
796 RtlInitUnicodeString( &dir_str, dirW );
797 RtlSetCurrentDirectory_U( &dir_str );
798 RtlFreeUnicodeString( &dir_str );
802 if (!cur_dir->DosPath.Length) /* still not initialized */
804 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
805 "starting in the Windows directory.\n", cwd ? cwd : "" );
806 RtlInitUnicodeString( &dir_str, DIR_Windows );
807 RtlSetCurrentDirectory_U( &dir_str );
809 HeapFree( GetProcessHeap(), 0, cwd );
811 done:
812 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
813 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
817 /***********************************************************************
818 * init_windows_dirs
820 * Initialize the windows and system directories from the environment.
822 static void init_windows_dirs(void)
824 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
826 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
827 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
828 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
829 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
831 DWORD len;
832 WCHAR *buffer;
834 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
836 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
837 GetEnvironmentVariableW( windirW, buffer, len );
838 DIR_Windows = buffer;
840 else DIR_Windows = default_windirW;
842 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
844 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
845 GetEnvironmentVariableW( winsysdirW, buffer, len );
846 DIR_System = buffer;
848 else
850 len = strlenW( DIR_Windows );
851 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
852 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
853 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
854 DIR_System = buffer;
857 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
858 ERR( "directory %s could not be created, error %u\n",
859 debugstr_w(DIR_Windows), GetLastError() );
860 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
861 ERR( "directory %s could not be created, error %u\n",
862 debugstr_w(DIR_System), GetLastError() );
864 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
865 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
867 /* set the directories in ntdll too */
868 __wine_init_windows_dir( DIR_Windows, DIR_System );
872 /***********************************************************************
873 * start_wineboot
875 * Start the wineboot process if necessary. Return the event to wait on.
877 static HANDLE start_wineboot(void)
879 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
880 HANDLE event;
882 if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
884 ERR( "failed to create wineboot event, expect trouble\n" );
885 return 0;
887 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
889 static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
890 STARTUPINFOW si;
891 PROCESS_INFORMATION pi;
892 WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];
894 memset( &si, 0, sizeof(si) );
895 si.cb = sizeof(si);
896 si.dwFlags = STARTF_USESTDHANDLES;
897 si.hStdInput = 0;
898 si.hStdOutput = 0;
899 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
901 GetSystemDirectoryW( cmdline, MAX_PATH );
902 lstrcatW( cmdline, command_line );
903 if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
905 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
906 CloseHandle( pi.hThread );
907 CloseHandle( pi.hProcess );
910 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
912 return event;
916 /***********************************************************************
917 * start_process
919 * Startup routine of a new process. Runs on the new process stack.
921 static void start_process( void *arg )
923 __TRY
925 PEB *peb = NtCurrentTeb()->Peb;
926 IMAGE_NT_HEADERS *nt;
927 LPTHREAD_START_ROUTINE entry;
929 nt = RtlImageNtHeader( peb->ImageBaseAddress );
930 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
931 nt->OptionalHeader.AddressOfEntryPoint);
933 if (!nt->OptionalHeader.AddressOfEntryPoint)
935 ERR( "%s doesn't have an entry point, it cannot be executed\n",
936 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
937 ExitThread( 1 );
940 if (TRACE_ON(relay))
941 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
942 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
944 SetLastError( 0 ); /* clear error code */
945 if (peb->BeingDebugged) DbgBreakPoint();
946 ExitThread( entry( peb ) );
948 __EXCEPT(UnhandledExceptionFilter)
950 TerminateThread( GetCurrentThread(), GetExceptionCode() );
952 __ENDTRY
956 /***********************************************************************
957 * set_process_name
959 * Change the process name in the ps output.
961 static void set_process_name( int argc, char *argv[] )
963 #ifdef HAVE_SETPROCTITLE
964 setproctitle("-%s", argv[1]);
965 #endif
967 #ifdef HAVE_PRCTL
968 int i, offset;
969 char *p, *prctl_name = argv[1];
970 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
972 #ifndef PR_SET_NAME
973 # define PR_SET_NAME 15
974 #endif
976 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
977 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
979 if (prctl( PR_SET_NAME, prctl_name ) != -1)
981 offset = argv[1] - argv[0];
982 memmove( argv[1] - offset, argv[1], end - argv[1] );
983 memset( end - offset, 0, offset );
984 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
985 argv[i-1] = NULL;
987 else
988 #endif /* HAVE_PRCTL */
990 /* remove argv[0] */
991 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
996 /***********************************************************************
997 * __wine_kernel_init
999 * Wine initialisation: load and start the main exe file.
1001 void CDECL __wine_kernel_init(void)
1003 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1004 static const WCHAR dotW[] = {'.',0};
1005 static const WCHAR exeW[] = {'.','e','x','e',0};
1007 WCHAR *p, main_exe_name[MAX_PATH+1];
1008 PEB *peb = NtCurrentTeb()->Peb;
1009 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1010 HANDLE boot_event = 0;
1011 BOOL got_environment = TRUE;
1013 /* Initialize everything */
1015 setbuf(stdout,NULL);
1016 setbuf(stderr,NULL);
1017 kernel32_handle = GetModuleHandleW(kernel32W);
1019 LOCALE_Init();
1021 if (!params->Environment)
1023 /* Copy the parent environment */
1024 if (!build_initial_environment()) exit(1);
1026 /* convert old configuration to new format */
1027 convert_old_config();
1029 got_environment = set_registry_environment();
1030 set_additional_environment();
1033 init_windows_dirs();
1034 init_current_directory( &params->CurrentDirectory );
1036 set_process_name( __wine_main_argc, __wine_main_argv );
1037 set_library_wargv( __wine_main_argv );
1039 if (peb->ProcessParameters->ImagePathName.Buffer)
1041 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1043 else
1045 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1046 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1048 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1049 ExitProcess( GetLastError() );
1051 update_library_argv0( main_exe_name );
1052 if (!build_command_line( __wine_main_wargv )) goto error;
1053 boot_event = start_wineboot();
1056 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1057 p = strrchrW( main_exe_name, '.' );
1058 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1060 TRACE( "starting process name=%s argv[0]=%s\n",
1061 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1063 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1064 MODULE_get_dll_load_path(main_exe_name) );
1066 if (boot_event)
1068 if (WaitForSingleObject( boot_event, 30000 )) ERR( "boot event wait timed out\n" );
1069 CloseHandle( boot_event );
1070 /* if we didn't find environment section, try again now that wineboot has run */
1071 if (!got_environment)
1073 set_registry_environment();
1074 set_additional_environment();
1078 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1080 char msg[1024];
1081 DWORD error = GetLastError();
1083 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1084 if (error == ERROR_BAD_EXE_FORMAT ||
1085 error == ERROR_INVALID_ADDRESS ||
1086 error == ERROR_NOT_ENOUGH_MEMORY)
1088 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1089 /* if we get back here, it failed */
1091 else if (error == ERROR_MOD_NOT_FOUND)
1093 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1094 else p = main_exe_name;
1095 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1097 /* args 1 and 2 are --app-name full_path */
1098 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1099 debugstr_w(__wine_main_wargv[3]) );
1100 ExitProcess( ERROR_BAD_EXE_FORMAT );
1103 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1104 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1105 ExitProcess( error );
1108 LdrInitializeThunk( 0, 0, 0, 0 );
1109 /* switch to the new stack */
1110 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1112 error:
1113 ExitProcess( GetLastError() );
1117 /***********************************************************************
1118 * build_argv
1120 * Build an argv array from a command-line.
1121 * 'reserved' is the number of args to reserve before the first one.
1123 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1125 int argc;
1126 char** argv;
1127 char *arg,*s,*d,*cmdline;
1128 int in_quotes,bcount,len;
1130 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1131 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1132 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1134 argc=reserved+1;
1135 bcount=0;
1136 in_quotes=0;
1137 s=cmdline;
1138 while (1) {
1139 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1140 /* space */
1141 argc++;
1142 /* skip the remaining spaces */
1143 while (*s==' ' || *s=='\t') {
1144 s++;
1146 if (*s=='\0')
1147 break;
1148 bcount=0;
1149 continue;
1150 } else if (*s=='\\') {
1151 /* '\', count them */
1152 bcount++;
1153 } else if ((*s=='"') && ((bcount & 1)==0)) {
1154 /* unescaped '"' */
1155 in_quotes=!in_quotes;
1156 bcount=0;
1157 } else {
1158 /* a regular character */
1159 bcount=0;
1161 s++;
1163 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1165 HeapFree( GetProcessHeap(), 0, cmdline );
1166 return NULL;
1169 arg = d = s = (char *)(argv + argc);
1170 memcpy( d, cmdline, len );
1171 bcount=0;
1172 in_quotes=0;
1173 argc=reserved;
1174 while (*s) {
1175 if ((*s==' ' || *s=='\t') && !in_quotes) {
1176 /* Close the argument and copy it */
1177 *d=0;
1178 argv[argc++]=arg;
1180 /* skip the remaining spaces */
1181 do {
1182 s++;
1183 } while (*s==' ' || *s=='\t');
1185 /* Start with a new argument */
1186 arg=d=s;
1187 bcount=0;
1188 } else if (*s=='\\') {
1189 /* '\\' */
1190 *d++=*s++;
1191 bcount++;
1192 } else if (*s=='"') {
1193 /* '"' */
1194 if ((bcount & 1)==0) {
1195 /* Preceded by an even number of '\', this is half that
1196 * number of '\', plus a '"' which we discard.
1198 d-=bcount/2;
1199 s++;
1200 in_quotes=!in_quotes;
1201 } else {
1202 /* Preceded by an odd number of '\', this is half that
1203 * number of '\' followed by a '"'
1205 d=d-bcount/2-1;
1206 *d++='"';
1207 s++;
1209 bcount=0;
1210 } else {
1211 /* a regular character */
1212 *d++=*s++;
1213 bcount=0;
1216 if (*arg) {
1217 *d='\0';
1218 argv[argc++]=arg;
1220 argv[argc]=NULL;
1222 HeapFree( GetProcessHeap(), 0, cmdline );
1223 return argv;
1227 /***********************************************************************
1228 * build_envp
1230 * Build the environment of a new child process.
1232 static char **build_envp( const WCHAR *envW )
1234 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1236 const WCHAR *end;
1237 char **envp;
1238 char *env, *p;
1239 int count = 1, length;
1240 unsigned int i;
1242 for (end = envW; *end; count++) end += strlenW(end) + 1;
1243 end++;
1244 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1245 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1246 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1248 for (p = env; *p; p += strlen(p) + 1)
1249 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1251 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1253 if (!(p = getenv(unix_vars[i]))) continue;
1254 length += strlen(unix_vars[i]) + strlen(p) + 2;
1255 count++;
1258 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1260 char **envptr = envp;
1261 char *dst = (char *)(envp + count);
1263 /* some variables must not be modified, so we get them directly from the unix env */
1264 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1266 if (!(p = getenv(unix_vars[i]))) continue;
1267 *envptr++ = strcpy( dst, unix_vars[i] );
1268 strcat( dst, "=" );
1269 strcat( dst, p );
1270 dst += strlen(dst) + 1;
1273 /* now put the Windows environment strings */
1274 for (p = env; *p; p += strlen(p) + 1)
1276 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1277 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1278 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1279 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1280 if (is_special_env_var( p )) /* prefix it with "WINE" */
1282 *envptr++ = strcpy( dst, "WINE" );
1283 strcat( dst, p );
1285 else
1287 *envptr++ = strcpy( dst, p );
1289 dst += strlen(dst) + 1;
1291 *envptr = 0;
1293 HeapFree( GetProcessHeap(), 0, env );
1294 return envp;
1298 /***********************************************************************
1299 * fork_and_exec
1301 * Fork and exec a new Unix binary, checking for errors.
1303 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1304 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1306 int fd[2], stdin_fd = -1, stdout_fd = -1;
1307 int pid, err;
1308 char **argv, **envp;
1310 if (!env) env = GetEnvironmentStringsW();
1312 if (pipe(fd) == -1)
1314 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1315 return -1;
1317 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1319 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1321 HANDLE hstdin, hstdout;
1323 if (startup->dwFlags & STARTF_USESTDHANDLES)
1325 hstdin = startup->hStdInput;
1326 hstdout = startup->hStdOutput;
1328 else
1330 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1331 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1334 if (is_console_handle( hstdin ))
1335 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1336 if (is_console_handle( hstdout ))
1337 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1338 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1339 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1342 argv = build_argv( cmdline, 0 );
1343 envp = build_envp( env );
1345 if (!(pid = fork())) /* child */
1347 close( fd[0] );
1349 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1351 int pid;
1352 if (!(pid = fork()))
1354 int fd = open( "/dev/null", O_RDWR );
1355 setsid();
1356 /* close stdin and stdout */
1357 if (fd != -1)
1359 dup2( fd, 0 );
1360 dup2( fd, 1 );
1361 close( fd );
1364 else if (pid != -1) _exit(0); /* parent */
1366 else
1368 if (stdin_fd != -1)
1370 dup2( stdin_fd, 0 );
1371 close( stdin_fd );
1373 if (stdout_fd != -1)
1375 dup2( stdout_fd, 1 );
1376 close( stdout_fd );
1380 /* Reset signals that we previously set to SIG_IGN */
1381 signal( SIGPIPE, SIG_DFL );
1382 signal( SIGCHLD, SIG_DFL );
1384 if (newdir) chdir(newdir);
1386 if (argv && envp) execve( filename, argv, envp );
1387 err = errno;
1388 write( fd[1], &err, sizeof(err) );
1389 _exit(1);
1391 HeapFree( GetProcessHeap(), 0, argv );
1392 HeapFree( GetProcessHeap(), 0, envp );
1393 if (stdin_fd != -1) close( stdin_fd );
1394 if (stdout_fd != -1) close( stdout_fd );
1395 close( fd[1] );
1396 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1398 errno = err;
1399 pid = -1;
1401 if (pid == -1) FILE_SetDosError();
1402 close( fd[0] );
1403 return pid;
1407 /***********************************************************************
1408 * create_user_params
1410 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1411 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1412 const STARTUPINFOW *startup )
1414 RTL_USER_PROCESS_PARAMETERS *params;
1415 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1416 NTSTATUS status;
1417 WCHAR buffer[MAX_PATH];
1419 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1420 lstrcpynW( buffer, filename, MAX_PATH );
1421 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1422 lstrcpynW( buffer, filename, MAX_PATH );
1423 RtlInitUnicodeString( &image_str, buffer );
1425 RtlInitUnicodeString( &cmdline_str, cmdline );
1426 newdir.Buffer = NULL;
1427 if (cur_dir)
1429 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1431 /* skip \??\ prefix */
1432 curdir_str.Buffer = newdir.Buffer + 4;
1433 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1434 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1436 else cur_dir = NULL;
1438 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1439 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1440 if (startup->lpReserved2 && startup->cbReserved2)
1442 runtime.Length = 0;
1443 runtime.MaximumLength = startup->cbReserved2;
1444 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1447 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1448 cur_dir ? &curdir_str : NULL,
1449 &cmdline_str, env,
1450 startup->lpTitle ? &title : NULL,
1451 startup->lpDesktop ? &desktop : NULL,
1452 NULL,
1453 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1454 RtlFreeUnicodeString( &newdir );
1455 if (status != STATUS_SUCCESS)
1457 SetLastError( RtlNtStatusToDosError(status) );
1458 return NULL;
1461 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1462 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1464 if (startup->dwFlags & STARTF_USESTDHANDLES)
1466 params->hStdInput = startup->hStdInput;
1467 params->hStdOutput = startup->hStdOutput;
1468 params->hStdError = startup->hStdError;
1470 else
1472 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1473 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1474 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1476 params->dwX = startup->dwX;
1477 params->dwY = startup->dwY;
1478 params->dwXSize = startup->dwXSize;
1479 params->dwYSize = startup->dwYSize;
1480 params->dwXCountChars = startup->dwXCountChars;
1481 params->dwYCountChars = startup->dwYCountChars;
1482 params->dwFillAttribute = startup->dwFillAttribute;
1483 params->dwFlags = startup->dwFlags;
1484 params->wShowWindow = startup->wShowWindow;
1485 return params;
1489 /***********************************************************************
1490 * create_process
1492 * Create a new process. If hFile is a valid handle we have an exe
1493 * file, otherwise it is a Winelib app.
1495 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1496 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1497 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1498 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1499 void *res_start, void *res_end, int exec_only )
1501 BOOL ret, success = FALSE;
1502 HANDLE process_info, hstdin, hstdout;
1503 WCHAR *env_end;
1504 char *winedebug = NULL;
1505 char **argv;
1506 RTL_USER_PROCESS_PARAMETERS *params;
1507 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1508 pid_t pid;
1509 int err;
1511 if (!env) RtlAcquirePebLock();
1513 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1515 if (!env) RtlReleasePebLock();
1516 return FALSE;
1518 env_end = params->Environment;
1519 while (*env_end)
1521 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1522 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1524 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1525 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1526 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1528 env_end += strlenW(env_end) + 1;
1530 env_end++;
1532 /* create the socket for the new process */
1534 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1536 if (!env) RtlReleasePebLock();
1537 HeapFree( GetProcessHeap(), 0, winedebug );
1538 RtlDestroyProcessParameters( params );
1539 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1540 return FALSE;
1542 wine_server_send_fd( socketfd[1] );
1543 close( socketfd[1] );
1545 /* create the process on the server side */
1547 SERVER_START_REQ( new_process )
1549 req->inherit_all = inherit;
1550 req->create_flags = flags;
1551 req->socket_fd = socketfd[1];
1552 req->exe_file = wine_server_obj_handle( hFile );
1553 req->process_access = PROCESS_ALL_ACCESS;
1554 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1555 req->thread_access = THREAD_ALL_ACCESS;
1556 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1557 req->hstdin = wine_server_obj_handle( params->hStdInput );
1558 req->hstdout = wine_server_obj_handle( params->hStdOutput );
1559 req->hstderr = wine_server_obj_handle( params->hStdError );
1561 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1563 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1564 if (is_console_handle(params->hStdInput)) req->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1565 if (is_console_handle(params->hStdOutput)) req->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1566 if (is_console_handle(params->hStdError)) req->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1567 hstdin = hstdout = 0;
1569 else
1571 if (is_console_handle(params->hStdInput)) req->hstdin = console_handle_unmap(params->hStdInput);
1572 if (is_console_handle(params->hStdOutput)) req->hstdout = console_handle_unmap(params->hStdOutput);
1573 if (is_console_handle(params->hStdError)) req->hstderr = console_handle_unmap(params->hStdError);
1574 hstdin = wine_server_ptr_handle( req->hstdin );
1575 hstdout = wine_server_ptr_handle( req->hstdout );
1578 wine_server_add_data( req, params, params->Size );
1579 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1580 if ((ret = !wine_server_call_err( req )))
1582 info->dwProcessId = (DWORD)reply->pid;
1583 info->dwThreadId = (DWORD)reply->tid;
1584 info->hProcess = wine_server_ptr_handle( reply->phandle );
1585 info->hThread = wine_server_ptr_handle( reply->thandle );
1587 process_info = wine_server_ptr_handle( reply->info );
1589 SERVER_END_REQ;
1591 if (!env) RtlReleasePebLock();
1592 RtlDestroyProcessParameters( params );
1593 if (!ret)
1595 close( socketfd[0] );
1596 HeapFree( GetProcessHeap(), 0, winedebug );
1597 return FALSE;
1600 if (hstdin) wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1601 if (hstdout) wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1603 /* create the child process */
1604 argv = build_argv( cmd_line, 1 );
1606 if (exec_only || !(pid = fork())) /* child */
1608 char preloader_reserve[64], socket_env[64];
1610 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1612 if (!(pid = fork()))
1614 int fd = open( "/dev/null", O_RDWR );
1615 setsid();
1616 /* close stdin and stdout */
1617 if (fd != -1)
1619 dup2( fd, 0 );
1620 dup2( fd, 1 );
1621 close( fd );
1624 else if (pid != -1) _exit(0); /* parent */
1626 else
1628 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1629 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1632 if (stdin_fd != -1) close( stdin_fd );
1633 if (stdout_fd != -1) close( stdout_fd );
1635 /* Reset signals that we previously set to SIG_IGN */
1636 signal( SIGPIPE, SIG_DFL );
1637 signal( SIGCHLD, SIG_DFL );
1639 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1640 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1641 (unsigned long)res_start, (unsigned long)res_end );
1643 putenv( preloader_reserve );
1644 putenv( socket_env );
1645 if (winedebug) putenv( winedebug );
1646 if (unixdir) chdir(unixdir);
1648 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1649 _exit(1);
1652 /* this is the parent */
1654 if (stdin_fd != -1) close( stdin_fd );
1655 if (stdout_fd != -1) close( stdout_fd );
1656 close( socketfd[0] );
1657 HeapFree( GetProcessHeap(), 0, argv );
1658 HeapFree( GetProcessHeap(), 0, winedebug );
1659 if (pid == -1)
1661 FILE_SetDosError();
1662 goto error;
1665 /* wait for the new process info to be ready */
1667 WaitForSingleObject( process_info, INFINITE );
1668 SERVER_START_REQ( get_new_process_info )
1670 req->info = wine_server_obj_handle( process_info );
1671 wine_server_call( req );
1672 success = reply->success;
1673 err = reply->exit_code;
1675 SERVER_END_REQ;
1677 if (!success)
1679 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1680 goto error;
1682 CloseHandle( process_info );
1683 return success;
1685 error:
1686 CloseHandle( process_info );
1687 CloseHandle( info->hProcess );
1688 CloseHandle( info->hThread );
1689 info->hProcess = info->hThread = 0;
1690 info->dwProcessId = info->dwThreadId = 0;
1691 return FALSE;
1695 /***********************************************************************
1696 * create_vdm_process
1698 * Create a new VDM process for a 16-bit or DOS application.
1700 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1701 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1702 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1703 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1705 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1707 BOOL ret;
1708 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1709 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1711 if (!new_cmd_line)
1713 SetLastError( ERROR_OUTOFMEMORY );
1714 return FALSE;
1716 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1717 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1718 flags, startup, info, unixdir, NULL, NULL, exec_only );
1719 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1720 return ret;
1724 /***********************************************************************
1725 * create_cmd_process
1727 * Create a new cmd shell process for a .BAT file.
1729 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1730 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1731 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1732 LPPROCESS_INFORMATION info )
1735 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1736 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1737 WCHAR comspec[MAX_PATH];
1738 WCHAR *newcmdline;
1739 BOOL ret;
1741 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1742 return FALSE;
1743 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1744 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1745 return FALSE;
1747 strcpyW( newcmdline, comspec );
1748 strcatW( newcmdline, slashcW );
1749 strcatW( newcmdline, cmd_line );
1750 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1751 flags, env, cur_dir, startup, info );
1752 HeapFree( GetProcessHeap(), 0, newcmdline );
1753 return ret;
1757 /*************************************************************************
1758 * get_file_name
1760 * Helper for CreateProcess: retrieve the file name to load from the
1761 * app name and command line. Store the file name in buffer, and
1762 * return a possibly modified command line.
1763 * Also returns a handle to the opened file if it's a Windows binary.
1765 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1766 int buflen, HANDLE *handle )
1768 static const WCHAR quotesW[] = {'"','%','s','"',0};
1770 WCHAR *name, *pos, *ret = NULL;
1771 const WCHAR *p;
1772 BOOL got_space;
1774 /* if we have an app name, everything is easy */
1776 if (appname)
1778 /* use the unmodified app name as file name */
1779 lstrcpynW( buffer, appname, buflen );
1780 *handle = open_exe_file( buffer );
1781 if (!(ret = cmdline) || !cmdline[0])
1783 /* no command-line, create one */
1784 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1785 sprintfW( ret, quotesW, appname );
1787 return ret;
1790 if (!cmdline)
1792 SetLastError( ERROR_INVALID_PARAMETER );
1793 return NULL;
1796 /* first check for a quoted file name */
1798 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1800 int len = p - cmdline - 1;
1801 /* extract the quoted portion as file name */
1802 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1803 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1804 name[len] = 0;
1806 if (find_exe_file( name, buffer, buflen, handle ))
1807 ret = cmdline; /* no change necessary */
1808 goto done;
1811 /* now try the command-line word by word */
1813 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1814 return NULL;
1815 pos = name;
1816 p = cmdline;
1817 got_space = FALSE;
1819 while (*p)
1821 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1822 *pos = 0;
1823 if (find_exe_file( name, buffer, buflen, handle ))
1825 ret = cmdline;
1826 break;
1828 if (*p) got_space = TRUE;
1831 if (ret && got_space) /* now build a new command-line with quotes */
1833 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1834 goto done;
1835 sprintfW( ret, quotesW, name );
1836 strcatW( ret, p );
1839 done:
1840 HeapFree( GetProcessHeap(), 0, name );
1841 return ret;
1845 /**********************************************************************
1846 * CreateProcessA (KERNEL32.@)
1848 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1849 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1850 DWORD flags, LPVOID env, LPCSTR cur_dir,
1851 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1853 BOOL ret = FALSE;
1854 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1855 UNICODE_STRING desktopW, titleW;
1856 STARTUPINFOW infoW;
1858 desktopW.Buffer = NULL;
1859 titleW.Buffer = NULL;
1860 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1861 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1862 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1864 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1865 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1867 memcpy( &infoW, startup_info, sizeof(infoW) );
1868 infoW.lpDesktop = desktopW.Buffer;
1869 infoW.lpTitle = titleW.Buffer;
1871 if (startup_info->lpReserved)
1872 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1873 debugstr_a(startup_info->lpReserved));
1875 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1876 inherit, flags, env, cur_dirW, &infoW, info );
1877 done:
1878 HeapFree( GetProcessHeap(), 0, app_nameW );
1879 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1880 HeapFree( GetProcessHeap(), 0, cur_dirW );
1881 RtlFreeUnicodeString( &desktopW );
1882 RtlFreeUnicodeString( &titleW );
1883 return ret;
1887 /**********************************************************************
1888 * CreateProcessW (KERNEL32.@)
1890 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1891 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1892 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1893 LPPROCESS_INFORMATION info )
1895 BOOL retv = FALSE;
1896 HANDLE hFile = 0;
1897 char *unixdir = NULL;
1898 WCHAR name[MAX_PATH];
1899 WCHAR *tidy_cmdline, *p, *envW = env;
1900 void *res_start, *res_end;
1902 /* Process the AppName and/or CmdLine to get module name and path */
1904 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1906 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1907 return FALSE;
1908 if (hFile == INVALID_HANDLE_VALUE) goto done;
1910 /* Warn if unsupported features are used */
1912 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1913 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1914 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1915 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1916 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1918 if (cur_dir)
1920 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1922 SetLastError(ERROR_DIRECTORY);
1923 goto done;
1926 else
1928 WCHAR buf[MAX_PATH];
1929 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1932 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1934 char *p = env;
1935 DWORD lenW;
1937 while (*p) p += strlen(p) + 1;
1938 p++; /* final null */
1939 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1940 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1941 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1942 flags |= CREATE_UNICODE_ENVIRONMENT;
1945 info->hThread = info->hProcess = 0;
1946 info->dwProcessId = info->dwThreadId = 0;
1948 /* Determine executable type */
1950 if (!hFile) /* builtin exe */
1952 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1953 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1954 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1955 goto done;
1958 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1960 case BINARY_PE_EXE:
1961 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1962 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1963 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1964 break;
1965 case BINARY_OS216:
1966 case BINARY_WIN16:
1967 case BINARY_DOS:
1968 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1969 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1970 inherit, flags, startup_info, info, unixdir, FALSE );
1971 break;
1972 case BINARY_PE_DLL:
1973 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1974 SetLastError( ERROR_BAD_EXE_FORMAT );
1975 break;
1976 case BINARY_UNIX_LIB:
1977 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1978 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1979 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1980 break;
1981 case BINARY_UNKNOWN:
1982 /* check for .com or .bat extension */
1983 if ((p = strrchrW( name, '.' )))
1985 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1987 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1988 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1989 inherit, flags, startup_info, info, unixdir, FALSE );
1990 break;
1992 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1994 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1995 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1996 inherit, flags, startup_info, info );
1997 break;
2000 /* fall through */
2001 case BINARY_UNIX_EXE:
2003 /* unknown file, try as unix executable */
2004 char *unix_name;
2006 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2008 if ((unix_name = wine_get_unix_file_name( name )))
2010 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2011 HeapFree( GetProcessHeap(), 0, unix_name );
2014 break;
2016 CloseHandle( hFile );
2018 done:
2019 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2020 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2021 HeapFree( GetProcessHeap(), 0, unixdir );
2022 if (retv)
2023 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2024 return retv;
2028 /**********************************************************************
2029 * exec_process
2031 static void exec_process( LPCWSTR name )
2033 HANDLE hFile;
2034 WCHAR *p;
2035 void *res_start, *res_end;
2036 STARTUPINFOW startup_info;
2037 PROCESS_INFORMATION info;
2039 hFile = open_exe_file( name );
2040 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2042 memset( &startup_info, 0, sizeof(startup_info) );
2043 startup_info.cb = sizeof(startup_info);
2045 /* Determine executable type */
2047 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
2049 case BINARY_PE_EXE:
2050 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
2051 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2052 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
2053 break;
2054 case BINARY_UNIX_LIB:
2055 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2056 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2057 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
2058 break;
2059 case BINARY_UNKNOWN:
2060 /* check for .com or .pif extension */
2061 if (!(p = strrchrW( name, '.' ))) break;
2062 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2063 /* fall through */
2064 case BINARY_OS216:
2065 case BINARY_WIN16:
2066 case BINARY_DOS:
2067 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2068 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2069 FALSE, 0, &startup_info, &info, NULL, TRUE );
2070 break;
2071 default:
2072 break;
2074 CloseHandle( hFile );
2078 /***********************************************************************
2079 * wait_input_idle
2081 * Wrapper to call WaitForInputIdle USER function
2083 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2085 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2087 HMODULE mod = GetModuleHandleA( "user32.dll" );
2088 if (mod)
2090 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2091 if (ptr) return ptr( process, timeout );
2093 return 0;
2097 /***********************************************************************
2098 * WinExec (KERNEL32.@)
2100 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2102 PROCESS_INFORMATION info;
2103 STARTUPINFOA startup;
2104 char *cmdline;
2105 UINT ret;
2107 memset( &startup, 0, sizeof(startup) );
2108 startup.cb = sizeof(startup);
2109 startup.dwFlags = STARTF_USESHOWWINDOW;
2110 startup.wShowWindow = nCmdShow;
2112 /* cmdline needs to be writable for CreateProcess */
2113 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2114 strcpy( cmdline, lpCmdLine );
2116 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2117 0, NULL, NULL, &startup, &info ))
2119 /* Give 30 seconds to the app to come up */
2120 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2121 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2122 ret = 33;
2123 /* Close off the handles */
2124 CloseHandle( info.hThread );
2125 CloseHandle( info.hProcess );
2127 else if ((ret = GetLastError()) >= 32)
2129 FIXME("Strange error set by CreateProcess: %d\n", ret );
2130 ret = 11;
2132 HeapFree( GetProcessHeap(), 0, cmdline );
2133 return ret;
2137 /**********************************************************************
2138 * LoadModule (KERNEL32.@)
2140 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2142 LOADPARMS32 *params = paramBlock;
2143 PROCESS_INFORMATION info;
2144 STARTUPINFOA startup;
2145 HINSTANCE hInstance;
2146 LPSTR cmdline, p;
2147 char filename[MAX_PATH];
2148 BYTE len;
2150 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2152 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2153 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2154 return ULongToHandle(GetLastError());
2156 len = (BYTE)params->lpCmdLine[0];
2157 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2158 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2160 strcpy( cmdline, filename );
2161 p = cmdline + strlen(cmdline);
2162 *p++ = ' ';
2163 memcpy( p, params->lpCmdLine + 1, len );
2164 p[len] = 0;
2166 memset( &startup, 0, sizeof(startup) );
2167 startup.cb = sizeof(startup);
2168 if (params->lpCmdShow)
2170 startup.dwFlags = STARTF_USESHOWWINDOW;
2171 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2174 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2175 params->lpEnvAddress, NULL, &startup, &info ))
2177 /* Give 30 seconds to the app to come up */
2178 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2179 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2180 hInstance = (HINSTANCE)33;
2181 /* Close off the handles */
2182 CloseHandle( info.hThread );
2183 CloseHandle( info.hProcess );
2185 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2187 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2188 hInstance = (HINSTANCE)11;
2191 HeapFree( GetProcessHeap(), 0, cmdline );
2192 return hInstance;
2196 /******************************************************************************
2197 * TerminateProcess (KERNEL32.@)
2199 * Terminates a process.
2201 * PARAMS
2202 * handle [I] Process to terminate.
2203 * exit_code [I] Exit code.
2205 * RETURNS
2206 * Success: TRUE.
2207 * Failure: FALSE, check GetLastError().
2209 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2211 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2212 if (status) SetLastError( RtlNtStatusToDosError(status) );
2213 return !status;
2216 /***********************************************************************
2217 * ExitProcess (KERNEL32.@)
2219 * Exits the current process.
2221 * PARAMS
2222 * status [I] Status code to exit with.
2224 * RETURNS
2225 * Nothing.
2227 #ifdef __i386__
2228 __ASM_GLOBAL_FUNC( ExitProcess, /* Shrinker depend on this particular ExitProcess implementation */
2229 "pushl %ebp\n\t"
2230 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2231 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2232 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2233 "pushl 8(%ebp)\n\t"
2234 "call " __ASM_NAME("process_ExitProcess") "\n\t"
2235 "leave\n\t"
2236 "ret $4" )
2238 void WINAPI process_ExitProcess( DWORD status )
2240 LdrShutdownProcess();
2241 NtTerminateProcess(GetCurrentProcess(), status);
2242 exit(status);
2245 #else
2247 void WINAPI ExitProcess( DWORD status )
2249 LdrShutdownProcess();
2250 NtTerminateProcess(GetCurrentProcess(), status);
2251 exit(status);
2254 #endif
2256 /***********************************************************************
2257 * GetExitCodeProcess [KERNEL32.@]
2259 * Gets termination status of specified process.
2261 * PARAMS
2262 * hProcess [in] Handle to the process.
2263 * lpExitCode [out] Address to receive termination status.
2265 * RETURNS
2266 * Success: TRUE
2267 * Failure: FALSE
2269 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2271 NTSTATUS status;
2272 PROCESS_BASIC_INFORMATION pbi;
2274 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2275 sizeof(pbi), NULL);
2276 if (status == STATUS_SUCCESS)
2278 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2279 return TRUE;
2281 SetLastError( RtlNtStatusToDosError(status) );
2282 return FALSE;
2286 /***********************************************************************
2287 * SetErrorMode (KERNEL32.@)
2289 UINT WINAPI SetErrorMode( UINT mode )
2291 UINT old = process_error_mode;
2292 process_error_mode = mode;
2293 return old;
2296 /***********************************************************************
2297 * GetErrorMode (KERNEL32.@)
2299 UINT WINAPI GetErrorMode( void )
2301 return process_error_mode;
2304 /**********************************************************************
2305 * TlsAlloc [KERNEL32.@]
2307 * Allocates a thread local storage index.
2309 * RETURNS
2310 * Success: TLS index.
2311 * Failure: 0xFFFFFFFF
2313 DWORD WINAPI TlsAlloc( void )
2315 DWORD index;
2316 PEB * const peb = NtCurrentTeb()->Peb;
2318 RtlAcquirePebLock();
2319 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2320 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2321 else
2323 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2324 if (index != ~0U)
2326 if (!NtCurrentTeb()->TlsExpansionSlots &&
2327 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2328 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2330 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2331 index = ~0U;
2332 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2334 else
2336 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2337 index += TLS_MINIMUM_AVAILABLE;
2340 else SetLastError( ERROR_NO_MORE_ITEMS );
2342 RtlReleasePebLock();
2343 return index;
2347 /**********************************************************************
2348 * TlsFree [KERNEL32.@]
2350 * Releases a thread local storage index, making it available for reuse.
2352 * PARAMS
2353 * index [in] TLS index to free.
2355 * RETURNS
2356 * Success: TRUE
2357 * Failure: FALSE
2359 BOOL WINAPI TlsFree( DWORD index )
2361 BOOL ret;
2363 RtlAcquirePebLock();
2364 if (index >= TLS_MINIMUM_AVAILABLE)
2366 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2367 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2369 else
2371 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2372 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2374 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2375 else SetLastError( ERROR_INVALID_PARAMETER );
2376 RtlReleasePebLock();
2377 return TRUE;
2381 /**********************************************************************
2382 * TlsGetValue [KERNEL32.@]
2384 * Gets value in a thread's TLS slot.
2386 * PARAMS
2387 * index [in] TLS index to retrieve value for.
2389 * RETURNS
2390 * Success: Value stored in calling thread's TLS slot for index.
2391 * Failure: 0 and GetLastError() returns NO_ERROR.
2393 LPVOID WINAPI TlsGetValue( DWORD index )
2395 LPVOID ret;
2397 if (index < TLS_MINIMUM_AVAILABLE)
2399 ret = NtCurrentTeb()->TlsSlots[index];
2401 else
2403 index -= TLS_MINIMUM_AVAILABLE;
2404 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2406 SetLastError( ERROR_INVALID_PARAMETER );
2407 return NULL;
2409 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2410 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2412 SetLastError( ERROR_SUCCESS );
2413 return ret;
2417 /**********************************************************************
2418 * TlsSetValue [KERNEL32.@]
2420 * Stores a value in the thread's TLS slot.
2422 * PARAMS
2423 * index [in] TLS index to set value for.
2424 * value [in] Value to be stored.
2426 * RETURNS
2427 * Success: TRUE
2428 * Failure: FALSE
2430 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2432 if (index < TLS_MINIMUM_AVAILABLE)
2434 NtCurrentTeb()->TlsSlots[index] = value;
2436 else
2438 index -= TLS_MINIMUM_AVAILABLE;
2439 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2441 SetLastError( ERROR_INVALID_PARAMETER );
2442 return FALSE;
2444 if (!NtCurrentTeb()->TlsExpansionSlots &&
2445 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2446 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2448 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2449 return FALSE;
2451 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2453 return TRUE;
2457 /***********************************************************************
2458 * GetProcessFlags (KERNEL32.@)
2460 DWORD WINAPI GetProcessFlags( DWORD processid )
2462 IMAGE_NT_HEADERS *nt;
2463 DWORD flags = 0;
2465 if (processid && processid != GetCurrentProcessId()) return 0;
2467 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2469 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2470 flags |= PDB32_CONSOLE_PROC;
2472 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2473 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2474 return flags;
2478 /***********************************************************************
2479 * GetProcessDword (KERNEL.485)
2480 * GetProcessDword (KERNEL32.18)
2481 * 'Of course you cannot directly access Windows internal structures'
2483 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2485 DWORD x, y;
2486 STARTUPINFOW siw;
2488 TRACE("(%d, %d)\n", dwProcessID, offset );
2490 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2492 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2493 return 0;
2496 switch ( offset )
2498 case GPD_APP_COMPAT_FLAGS:
2499 return GetAppCompatFlags16(0);
2500 case GPD_LOAD_DONE_EVENT:
2501 return 0;
2502 case GPD_HINSTANCE16:
2503 return GetTaskDS16();
2504 case GPD_WINDOWS_VERSION:
2505 return GetExeVersion16();
2506 case GPD_THDB:
2507 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2508 case GPD_PDB:
2509 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2510 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2511 GetStartupInfoW(&siw);
2512 return HandleToULong(siw.hStdOutput);
2513 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2514 GetStartupInfoW(&siw);
2515 return HandleToULong(siw.hStdInput);
2516 case GPD_STARTF_SHOWWINDOW:
2517 GetStartupInfoW(&siw);
2518 return siw.wShowWindow;
2519 case GPD_STARTF_SIZE:
2520 GetStartupInfoW(&siw);
2521 x = siw.dwXSize;
2522 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2523 y = siw.dwYSize;
2524 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2525 return MAKELONG( x, y );
2526 case GPD_STARTF_POSITION:
2527 GetStartupInfoW(&siw);
2528 x = siw.dwX;
2529 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2530 y = siw.dwY;
2531 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2532 return MAKELONG( x, y );
2533 case GPD_STARTF_FLAGS:
2534 GetStartupInfoW(&siw);
2535 return siw.dwFlags;
2536 case GPD_PARENT:
2537 return 0;
2538 case GPD_FLAGS:
2539 return GetProcessFlags(0);
2540 case GPD_USERDATA:
2541 return process_dword;
2542 default:
2543 ERR("Unknown offset %d\n", offset );
2544 return 0;
2548 /***********************************************************************
2549 * SetProcessDword (KERNEL.484)
2550 * 'Of course you cannot directly access Windows internal structures'
2552 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2554 TRACE("(%d, %d)\n", dwProcessID, offset );
2556 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2558 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2559 return;
2562 switch ( offset )
2564 case GPD_APP_COMPAT_FLAGS:
2565 case GPD_LOAD_DONE_EVENT:
2566 case GPD_HINSTANCE16:
2567 case GPD_WINDOWS_VERSION:
2568 case GPD_THDB:
2569 case GPD_PDB:
2570 case GPD_STARTF_SHELLDATA:
2571 case GPD_STARTF_HOTKEY:
2572 case GPD_STARTF_SHOWWINDOW:
2573 case GPD_STARTF_SIZE:
2574 case GPD_STARTF_POSITION:
2575 case GPD_STARTF_FLAGS:
2576 case GPD_PARENT:
2577 case GPD_FLAGS:
2578 ERR("Not allowed to modify offset %d\n", offset );
2579 break;
2580 case GPD_USERDATA:
2581 process_dword = value;
2582 break;
2583 default:
2584 ERR("Unknown offset %d\n", offset );
2585 break;
2590 /***********************************************************************
2591 * ExitProcess (KERNEL.466)
2593 void WINAPI ExitProcess16( WORD status )
2595 DWORD count;
2596 ReleaseThunkLock( &count );
2597 ExitProcess( status );
2601 /*********************************************************************
2602 * OpenProcess (KERNEL32.@)
2604 * Opens a handle to a process.
2606 * PARAMS
2607 * access [I] Desired access rights assigned to the returned handle.
2608 * inherit [I] Determines whether or not child processes will inherit the handle.
2609 * id [I] Process identifier of the process to get a handle to.
2611 * RETURNS
2612 * Success: Valid handle to the specified process.
2613 * Failure: NULL, check GetLastError().
2615 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2617 NTSTATUS status;
2618 HANDLE handle;
2619 OBJECT_ATTRIBUTES attr;
2620 CLIENT_ID cid;
2622 cid.UniqueProcess = ULongToHandle(id);
2623 cid.UniqueThread = 0; /* FIXME ? */
2625 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2626 attr.RootDirectory = NULL;
2627 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2628 attr.SecurityDescriptor = NULL;
2629 attr.SecurityQualityOfService = NULL;
2630 attr.ObjectName = NULL;
2632 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2634 status = NtOpenProcess(&handle, access, &attr, &cid);
2635 if (status != STATUS_SUCCESS)
2637 SetLastError( RtlNtStatusToDosError(status) );
2638 return NULL;
2640 return handle;
2644 /*********************************************************************
2645 * MapProcessHandle (KERNEL.483)
2646 * GetProcessId (KERNEL32.@)
2648 * Gets the a unique identifier of a process.
2650 * PARAMS
2651 * hProcess [I] Handle to the process.
2653 * RETURNS
2654 * Success: TRUE.
2655 * Failure: FALSE, check GetLastError().
2657 * NOTES
2659 * The identifier is unique only on the machine and only until the process
2660 * exits (including system shutdown).
2662 DWORD WINAPI GetProcessId( HANDLE hProcess )
2664 NTSTATUS status;
2665 PROCESS_BASIC_INFORMATION pbi;
2667 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2668 sizeof(pbi), NULL);
2669 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2670 SetLastError( RtlNtStatusToDosError(status) );
2671 return 0;
2675 /*********************************************************************
2676 * CloseW32Handle (KERNEL.474)
2677 * CloseHandle (KERNEL32.@)
2679 * Closes a handle.
2681 * PARAMS
2682 * handle [I] Handle to close.
2684 * RETURNS
2685 * Success: TRUE.
2686 * Failure: FALSE, check GetLastError().
2688 BOOL WINAPI CloseHandle( HANDLE handle )
2690 NTSTATUS status;
2692 /* stdio handles need special treatment */
2693 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2694 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2695 (handle == (HANDLE)STD_ERROR_HANDLE))
2696 handle = GetStdHandle( HandleToULong(handle) );
2698 if (is_console_handle(handle))
2699 return CloseConsoleHandle(handle);
2701 status = NtClose( handle );
2702 if (status) SetLastError( RtlNtStatusToDosError(status) );
2703 return !status;
2707 /*********************************************************************
2708 * GetHandleInformation (KERNEL32.@)
2710 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2712 OBJECT_DATA_INFORMATION info;
2713 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2715 if (status) SetLastError( RtlNtStatusToDosError(status) );
2716 else if (flags)
2718 *flags = 0;
2719 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2720 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2722 return !status;
2726 /*********************************************************************
2727 * SetHandleInformation (KERNEL32.@)
2729 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2731 OBJECT_DATA_INFORMATION info;
2732 NTSTATUS status;
2734 /* if not setting both fields, retrieve current value first */
2735 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2736 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2738 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2740 SetLastError( RtlNtStatusToDosError(status) );
2741 return FALSE;
2744 if (mask & HANDLE_FLAG_INHERIT)
2745 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2746 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2747 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2749 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2750 if (status) SetLastError( RtlNtStatusToDosError(status) );
2751 return !status;
2755 /*********************************************************************
2756 * DuplicateHandle (KERNEL32.@)
2758 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2759 HANDLE dest_process, HANDLE *dest,
2760 DWORD access, BOOL inherit, DWORD options )
2762 NTSTATUS status;
2764 if (is_console_handle(source))
2766 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2767 if (source_process != dest_process ||
2768 source_process != GetCurrentProcess())
2770 SetLastError(ERROR_INVALID_PARAMETER);
2771 return FALSE;
2773 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2774 return (*dest != INVALID_HANDLE_VALUE);
2776 status = NtDuplicateObject( source_process, source, dest_process, dest,
2777 access, inherit ? OBJ_INHERIT : 0, options );
2778 if (status) SetLastError( RtlNtStatusToDosError(status) );
2779 return !status;
2783 /***********************************************************************
2784 * ConvertToGlobalHandle (KERNEL.476)
2785 * ConvertToGlobalHandle (KERNEL32.@)
2787 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2789 HANDLE ret = INVALID_HANDLE_VALUE;
2790 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2791 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2792 return ret;
2796 /***********************************************************************
2797 * SetHandleContext (KERNEL32.@)
2799 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2801 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2802 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2803 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2804 return FALSE;
2808 /***********************************************************************
2809 * GetHandleContext (KERNEL32.@)
2811 DWORD WINAPI GetHandleContext(HANDLE hnd)
2813 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2814 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2815 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2816 return 0;
2820 /***********************************************************************
2821 * CreateSocketHandle (KERNEL32.@)
2823 HANDLE WINAPI CreateSocketHandle(void)
2825 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2826 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2827 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2828 return INVALID_HANDLE_VALUE;
2832 /***********************************************************************
2833 * SetPriorityClass (KERNEL32.@)
2835 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2837 NTSTATUS status;
2838 PROCESS_PRIORITY_CLASS ppc;
2840 ppc.Foreground = FALSE;
2841 switch (priorityclass)
2843 case IDLE_PRIORITY_CLASS:
2844 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2845 case BELOW_NORMAL_PRIORITY_CLASS:
2846 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2847 case NORMAL_PRIORITY_CLASS:
2848 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2849 case ABOVE_NORMAL_PRIORITY_CLASS:
2850 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2851 case HIGH_PRIORITY_CLASS:
2852 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2853 case REALTIME_PRIORITY_CLASS:
2854 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2855 default:
2856 SetLastError(ERROR_INVALID_PARAMETER);
2857 return FALSE;
2860 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2861 &ppc, sizeof(ppc));
2863 if (status != STATUS_SUCCESS)
2865 SetLastError( RtlNtStatusToDosError(status) );
2866 return FALSE;
2868 return TRUE;
2872 /***********************************************************************
2873 * GetPriorityClass (KERNEL32.@)
2875 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2877 NTSTATUS status;
2878 PROCESS_BASIC_INFORMATION pbi;
2880 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2881 sizeof(pbi), NULL);
2882 if (status != STATUS_SUCCESS)
2884 SetLastError( RtlNtStatusToDosError(status) );
2885 return 0;
2887 switch (pbi.BasePriority)
2889 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2890 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2891 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2892 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2893 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2894 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2896 SetLastError( ERROR_INVALID_PARAMETER );
2897 return 0;
2901 /***********************************************************************
2902 * SetProcessAffinityMask (KERNEL32.@)
2904 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2906 NTSTATUS status;
2908 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2909 &affmask, sizeof(DWORD_PTR));
2910 if (status)
2912 SetLastError( RtlNtStatusToDosError(status) );
2913 return FALSE;
2915 return TRUE;
2919 /**********************************************************************
2920 * GetProcessAffinityMask (KERNEL32.@)
2922 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2923 PDWORD_PTR lpProcessAffinityMask,
2924 PDWORD_PTR lpSystemAffinityMask )
2926 PROCESS_BASIC_INFORMATION pbi;
2927 NTSTATUS status;
2929 status = NtQueryInformationProcess(hProcess,
2930 ProcessBasicInformation,
2931 &pbi, sizeof(pbi), NULL);
2932 if (status)
2934 SetLastError( RtlNtStatusToDosError(status) );
2935 return FALSE;
2937 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2938 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2939 return TRUE;
2943 /***********************************************************************
2944 * GetProcessVersion (KERNEL32.@)
2946 DWORD WINAPI GetProcessVersion( DWORD pid )
2948 HANDLE process;
2949 NTSTATUS status;
2950 PROCESS_BASIC_INFORMATION pbi;
2951 SIZE_T count;
2952 PEB peb;
2953 IMAGE_DOS_HEADER dos;
2954 IMAGE_NT_HEADERS nt;
2955 DWORD ver = 0;
2957 if (!pid || pid == GetCurrentProcessId())
2959 IMAGE_NT_HEADERS *nt;
2961 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2962 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2963 nt->OptionalHeader.MinorSubsystemVersion);
2964 return 0;
2967 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2968 if (!process) return 0;
2970 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2971 if (status) goto err;
2973 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2974 if (status || count != sizeof(peb)) goto err;
2976 memset(&dos, 0, sizeof(dos));
2977 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2978 if (status || count != sizeof(dos)) goto err;
2979 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2981 memset(&nt, 0, sizeof(nt));
2982 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2983 if (status || count != sizeof(nt)) goto err;
2984 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2986 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2988 err:
2989 CloseHandle(process);
2991 if (status != STATUS_SUCCESS)
2992 SetLastError(RtlNtStatusToDosError(status));
2994 return ver;
2998 /***********************************************************************
2999 * SetProcessWorkingSetSize [KERNEL32.@]
3000 * Sets the min/max working set sizes for a specified process.
3002 * PARAMS
3003 * hProcess [I] Handle to the process of interest
3004 * minset [I] Specifies minimum working set size
3005 * maxset [I] Specifies maximum working set size
3007 * RETURNS
3008 * Success: TRUE
3009 * Failure: FALSE
3011 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3012 SIZE_T maxset)
3014 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3015 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3016 /* Trim the working set to zero */
3017 /* Swap the process out of physical RAM */
3019 return TRUE;
3022 /***********************************************************************
3023 * GetProcessWorkingSetSize (KERNEL32.@)
3025 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3026 PSIZE_T maxset)
3028 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3029 /* 32 MB working set size */
3030 if (minset) *minset = 32*1024*1024;
3031 if (maxset) *maxset = 32*1024*1024;
3032 return TRUE;
3036 /***********************************************************************
3037 * SetProcessShutdownParameters (KERNEL32.@)
3039 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3041 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3042 shutdown_flags = flags;
3043 shutdown_priority = level;
3044 return TRUE;
3048 /***********************************************************************
3049 * GetProcessShutdownParameters (KERNEL32.@)
3052 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3054 *lpdwLevel = shutdown_priority;
3055 *lpdwFlags = shutdown_flags;
3056 return TRUE;
3060 /***********************************************************************
3061 * GetProcessPriorityBoost (KERNEL32.@)
3063 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3065 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3067 /* Report that no boost is present.. */
3068 *pDisablePriorityBoost = FALSE;
3070 return TRUE;
3073 /***********************************************************************
3074 * SetProcessPriorityBoost (KERNEL32.@)
3076 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3078 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3079 /* Say we can do it. I doubt the program will notice that we don't. */
3080 return TRUE;
3084 /***********************************************************************
3085 * ReadProcessMemory (KERNEL32.@)
3087 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3088 SIZE_T *bytes_read )
3090 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3091 if (status) SetLastError( RtlNtStatusToDosError(status) );
3092 return !status;
3096 /***********************************************************************
3097 * WriteProcessMemory (KERNEL32.@)
3099 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3100 SIZE_T *bytes_written )
3102 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3103 if (status) SetLastError( RtlNtStatusToDosError(status) );
3104 return !status;
3108 /****************************************************************************
3109 * FlushInstructionCache (KERNEL32.@)
3111 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3113 NTSTATUS status;
3114 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3115 if (status) SetLastError( RtlNtStatusToDosError(status) );
3116 return !status;
3120 /******************************************************************
3121 * GetProcessIoCounters (KERNEL32.@)
3123 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3125 NTSTATUS status;
3127 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3128 ioc, sizeof(*ioc), NULL);
3129 if (status) SetLastError( RtlNtStatusToDosError(status) );
3130 return !status;
3133 /******************************************************************
3134 * GetProcessHandleCount (KERNEL32.@)
3136 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3138 NTSTATUS status;
3140 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3141 cnt, sizeof(*cnt), NULL);
3142 if (status) SetLastError( RtlNtStatusToDosError(status) );
3143 return !status;
3146 /******************************************************************
3147 * QueryFullProcessImageNameW (KERNEL32.@)
3149 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3151 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3152 UNICODE_STRING *dynamic_buffer = NULL;
3153 UNICODE_STRING nt_path;
3154 UNICODE_STRING *result = NULL;
3155 NTSTATUS status;
3156 DWORD needed;
3158 RtlInitUnicodeStringEx(&nt_path, NULL);
3159 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3160 * as this is on Wine. */
3161 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer, sizeof(buffer), &needed);
3162 if (status == STATUS_INFO_LENGTH_MISMATCH)
3164 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed);
3165 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3166 result = dynamic_buffer;
3168 else
3169 result = (PUNICODE_STRING)buffer;
3171 if (status) goto cleanup;
3173 if (dwFlags & PROCESS_NAME_NATIVE)
3175 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3177 status = STATUS_OBJECT_PATH_NOT_FOUND;
3178 goto cleanup;
3180 result = &nt_path;
3183 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3185 status = STATUS_BUFFER_TOO_SMALL;
3186 goto cleanup;
3189 lstrcpynW(lpExeName, result->Buffer, result->Length/sizeof(WCHAR) + 1);
3190 *pdwSize = result->Length/sizeof(WCHAR);
3192 cleanup:
3193 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3194 RtlFreeUnicodeString(&nt_path);
3195 if (status) SetLastError( RtlNtStatusToDosError(status) );
3196 return !status;
3199 /***********************************************************************
3200 * ProcessIdToSessionId (KERNEL32.@)
3201 * This function is available on Terminal Server 4SP4 and Windows 2000
3203 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3205 /* According to MSDN, if the calling process is not in a terminal
3206 * services environment, then the sessionid returned is zero.
3208 *sessionid_ptr = 0;
3209 return TRUE;
3213 /***********************************************************************
3214 * RegisterServiceProcess (KERNEL.491)
3215 * RegisterServiceProcess (KERNEL32.@)
3217 * A service process calls this function to ensure that it continues to run
3218 * even after a user logged off.
3220 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3222 /* I don't think that Wine needs to do anything in this function */
3223 return 1; /* success */
3227 /**********************************************************************
3228 * IsWow64Process (KERNEL32.@)
3230 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3232 ULONG pbi;
3233 NTSTATUS status;
3235 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3237 if (status != STATUS_SUCCESS)
3239 SetLastError( RtlNtStatusToDosError( status ) );
3240 return FALSE;
3242 *Wow64Process = (pbi != 0);
3243 return TRUE;
3247 /***********************************************************************
3248 * GetCurrentProcess (KERNEL32.@)
3250 * Get a handle to the current process.
3252 * PARAMS
3253 * None.
3255 * RETURNS
3256 * A handle representing the current process.
3258 #undef GetCurrentProcess
3259 HANDLE WINAPI GetCurrentProcess(void)
3261 return (HANDLE)~(ULONG_PTR)0;
3264 /***********************************************************************
3265 * CmdBatNotification (KERNEL32.@)
3267 * Notifies the system that a batch file has started or finished.
3269 * PARAMS
3270 * bBatchRunning [I] TRUE if a batch file has started or
3271 * FALSE if a batch file has finished executing.
3273 * RETURNS
3274 * Unknown.
3276 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3278 FIXME("%d\n", bBatchRunning);
3279 return FALSE;
3283 /***********************************************************************
3284 * RegisterApplicationRestart (KERNEL32.@)
3286 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3288 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3290 return S_OK;