push 8742e928a3d078c1d2cecb5ceee0ffde3118cbb7
[wine/hacks.git] / dlls / kernel32 / process.c
blob72d829b51876720ba1d1e632dd953f9c1cb0da79
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 typedef struct
61 LPSTR lpEnvAddress;
62 LPSTR lpCmdLine;
63 LPSTR lpCmdShow;
64 DWORD dwReserved;
65 } LOADPARMS32;
67 static UINT process_error_mode;
69 static DWORD shutdown_flags = 0;
70 static DWORD shutdown_priority = 0x280;
71 static DWORD process_dword;
73 HMODULE kernel32_handle = 0;
75 const WCHAR *DIR_Windows = NULL;
76 const WCHAR *DIR_System = NULL;
78 /* Process flags */
79 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
80 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
81 #define PDB32_DOS_PROC 0x0010 /* Dos process */
82 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
83 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
84 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
86 static const WCHAR comW[] = {'.','c','o','m',0};
87 static const WCHAR batW[] = {'.','b','a','t',0};
88 static const WCHAR cmdW[] = {'.','c','m','d',0};
89 static const WCHAR pifW[] = {'.','p','i','f',0};
90 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
92 static void exec_process( LPCWSTR name );
94 extern void SHELL_LoadRegistry(void);
97 /***********************************************************************
98 * contains_path
100 static inline int contains_path( LPCWSTR name )
102 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
106 /***********************************************************************
107 * is_special_env_var
109 * Check if an environment variable needs to be handled specially when
110 * passed through the Unix environment (i.e. prefixed with "WINE").
112 static inline int is_special_env_var( const char *var )
114 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
115 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
116 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
117 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
121 /***************************************************************************
122 * get_builtin_path
124 * Get the path of a builtin module when the native file does not exist.
126 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
128 WCHAR *file_part;
129 UINT len = strlenW( DIR_System );
131 if (contains_path( libname ))
133 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
134 filename, &file_part ) > size * sizeof(WCHAR))
135 return FALSE; /* too long */
137 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
138 return FALSE;
139 while (filename[len] == '\\') len++;
140 if (filename + len != file_part) return FALSE;
142 else
144 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
145 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
146 file_part = filename + len;
147 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
148 strcpyW( file_part, libname );
150 if (ext && !strchrW( file_part, '.' ))
152 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
153 return FALSE; /* too long */
154 strcatW( file_part, ext );
156 return TRUE;
160 /***********************************************************************
161 * open_builtin_exe_file
163 * Open an exe file for a builtin exe.
165 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
166 int test_only, int *file_exists )
168 char exename[MAX_PATH];
169 WCHAR *p;
170 UINT i, len;
172 *file_exists = 0;
173 if ((p = strrchrW( name, '/' ))) name = p + 1;
174 if ((p = strrchrW( name, '\\' ))) name = p + 1;
176 /* we don't want to depend on the current codepage here */
177 len = strlenW( name ) + 1;
178 if (len >= sizeof(exename)) return NULL;
179 for (i = 0; i < len; i++)
181 if (name[i] > 127) return NULL;
182 exename[i] = (char)name[i];
183 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
185 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
189 /***********************************************************************
190 * open_exe_file
192 * Open a specific exe file, taking load order into account.
193 * Returns the file handle or 0 for a builtin exe.
195 static HANDLE open_exe_file( const WCHAR *name )
197 HANDLE handle;
199 TRACE("looking for %s\n", debugstr_w(name) );
201 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
202 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
204 WCHAR buffer[MAX_PATH];
205 /* file doesn't exist, check for builtin */
206 if (!contains_path( name )) goto error;
207 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
208 handle = 0;
210 return handle;
212 error:
213 SetLastError( ERROR_FILE_NOT_FOUND );
214 return INVALID_HANDLE_VALUE;
218 /***********************************************************************
219 * find_exe_file
221 * Open an exe file, and return the full name and file handle.
222 * Returns FALSE if file could not be found.
223 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
224 * If file is a builtin exe, returns TRUE and sets handle to 0.
226 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
228 static const WCHAR exeW[] = {'.','e','x','e',0};
229 int file_exists;
231 TRACE("looking for %s\n", debugstr_w(name) );
233 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
234 !get_builtin_path( name, exeW, buffer, buflen ))
236 /* no builtin found, try native without extension in case it is a Unix app */
238 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
240 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
241 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
242 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
243 return TRUE;
245 return FALSE;
248 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
249 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
250 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
251 return TRUE;
253 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
254 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
255 if (file_exists)
257 *handle = 0;
258 return TRUE;
261 return FALSE;
265 /***********************************************************************
266 * build_initial_environment
268 * Build the Win32 environment from the Unix environment
270 static BOOL build_initial_environment( char **environ )
272 SIZE_T size = 1;
273 char **e;
274 WCHAR *p, *endptr;
275 void *ptr;
277 /* Compute the total size of the Unix environment */
278 for (e = environ; *e; e++)
280 if (is_special_env_var( *e )) continue;
281 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
283 size *= sizeof(WCHAR);
285 /* Now allocate the environment */
286 ptr = NULL;
287 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
288 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
289 return FALSE;
291 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
292 endptr = p + size / sizeof(WCHAR);
294 /* And fill it with the Unix environment */
295 for (e = environ; *e; e++)
297 char *str = *e;
299 /* skip Unix special variables and use the Wine variants instead */
300 if (!strncmp( str, "WINE", 4 ))
302 if (is_special_env_var( str + 4 )) str += 4;
303 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
305 else if (is_special_env_var( str )) continue; /* skip it */
307 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
308 p += strlenW(p) + 1;
310 *p = 0;
311 return TRUE;
315 /***********************************************************************
316 * set_registry_variables
318 * Set environment variables by enumerating the values of a key;
319 * helper for set_registry_environment().
320 * Note that Windows happily truncates the value if it's too big.
322 static void set_registry_variables( HANDLE hkey, ULONG type )
324 UNICODE_STRING env_name, env_value;
325 NTSTATUS status;
326 DWORD size;
327 int index;
328 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
329 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
331 for (index = 0; ; index++)
333 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
334 buffer, sizeof(buffer), &size );
335 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
336 break;
337 if (info->Type != type)
338 continue;
339 env_name.Buffer = info->Name;
340 env_name.Length = env_name.MaximumLength = info->NameLength;
341 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
342 env_value.Length = env_value.MaximumLength = info->DataLength;
343 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
344 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
345 if (info->Type == REG_EXPAND_SZ)
347 WCHAR buf_expanded[1024];
348 UNICODE_STRING env_expanded;
349 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
350 env_expanded.Buffer=buf_expanded;
351 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
352 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
353 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
355 else
357 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
363 /***********************************************************************
364 * set_registry_environment
366 * Set the environment variables specified in the registry.
368 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
369 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
370 * on the order in which the variables are processed. But on Windows it
371 * does not really matter since they only use %SystemDrive% and
372 * %SystemRoot% which are predefined. But Wine defines these in the
373 * registry, so we need two passes.
375 static BOOL set_registry_environment(void)
377 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
378 'S','y','s','t','e','m','\\',
379 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
380 'C','o','n','t','r','o','l','\\',
381 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
382 'E','n','v','i','r','o','n','m','e','n','t',0};
383 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
385 OBJECT_ATTRIBUTES attr;
386 UNICODE_STRING nameW;
387 HANDLE hkey;
388 BOOL ret = FALSE;
390 attr.Length = sizeof(attr);
391 attr.RootDirectory = 0;
392 attr.ObjectName = &nameW;
393 attr.Attributes = 0;
394 attr.SecurityDescriptor = NULL;
395 attr.SecurityQualityOfService = NULL;
397 /* first the system environment variables */
398 RtlInitUnicodeString( &nameW, env_keyW );
399 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
401 set_registry_variables( hkey, REG_SZ );
402 set_registry_variables( hkey, REG_EXPAND_SZ );
403 NtClose( hkey );
404 ret = TRUE;
407 /* then the ones for the current user */
408 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
409 RtlInitUnicodeString( &nameW, envW );
410 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
412 set_registry_variables( hkey, REG_SZ );
413 set_registry_variables( hkey, REG_EXPAND_SZ );
414 NtClose( hkey );
416 NtClose( attr.RootDirectory );
417 return ret;
421 /***********************************************************************
422 * get_reg_value
424 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
426 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
427 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
428 DWORD len, size = sizeof(buffer);
429 WCHAR *ret = NULL;
430 UNICODE_STRING nameW;
432 RtlInitUnicodeString( &nameW, name );
433 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
434 return NULL;
436 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
437 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
439 if (info->Type == REG_EXPAND_SZ)
441 UNICODE_STRING value, expanded;
443 value.MaximumLength = len * sizeof(WCHAR);
444 value.Buffer = (WCHAR *)info->Data;
445 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
446 value.Length = len * sizeof(WCHAR);
447 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
448 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
449 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
450 else RtlFreeUnicodeString( &expanded );
452 else if (info->Type == REG_SZ)
454 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
456 memcpy( ret, info->Data, len * sizeof(WCHAR) );
457 ret[len] = 0;
460 return ret;
464 /***********************************************************************
465 * set_additional_environment
467 * Set some additional environment variables not specified in the registry.
469 static void set_additional_environment(void)
471 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
472 'S','o','f','t','w','a','r','e','\\',
473 'M','i','c','r','o','s','o','f','t','\\',
474 'W','i','n','d','o','w','s',' ','N','T','\\',
475 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
476 'P','r','o','f','i','l','e','L','i','s','t',0};
477 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
478 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
479 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
480 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
481 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
482 OBJECT_ATTRIBUTES attr;
483 UNICODE_STRING nameW;
484 WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
485 HANDLE hkey;
486 const char *name = wine_get_user_name();
487 DWORD len;
489 /* set the USERNAME variable */
491 len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
492 if (len)
494 user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
495 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
496 SetEnvironmentVariableW( usernameW, user_name );
499 /* set the USERPROFILE and ALLUSERSPROFILE variables */
501 attr.Length = sizeof(attr);
502 attr.RootDirectory = 0;
503 attr.ObjectName = &nameW;
504 attr.Attributes = 0;
505 attr.SecurityDescriptor = NULL;
506 attr.SecurityQualityOfService = NULL;
507 RtlInitUnicodeString( &nameW, profile_keyW );
508 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
510 profile_dir = get_reg_value( hkey, profiles_valueW );
511 all_users_dir = get_reg_value( hkey, all_users_valueW );
512 NtClose( hkey );
515 if (profile_dir)
517 WCHAR *value, *p;
519 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
520 len += strlenW(profile_dir) + 1;
521 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
522 strcpyW( value, profile_dir );
523 p = value + strlenW(value);
524 if (p > value && p[-1] != '\\') *p++ = '\\';
525 strcpyW( p, user_name );
526 SetEnvironmentVariableW( userprofileW, value );
527 if (all_users_dir)
529 strcpyW( p, all_users_dir );
530 SetEnvironmentVariableW( allusersW, value );
532 HeapFree( GetProcessHeap(), 0, value );
535 HeapFree( GetProcessHeap(), 0, all_users_dir );
536 HeapFree( GetProcessHeap(), 0, profile_dir );
537 HeapFree( GetProcessHeap(), 0, user_name );
540 /***********************************************************************
541 * set_library_wargv
543 * Set the Wine library Unicode argv global variables.
545 static void set_library_wargv( char **argv )
547 int argc;
548 char *q;
549 WCHAR *p;
550 WCHAR **wargv;
551 DWORD total = 0;
553 for (argc = 0; argv[argc]; argc++)
554 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
556 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
557 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
558 p = (WCHAR *)(wargv + argc + 1);
559 for (argc = 0; argv[argc]; argc++)
561 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
562 wargv[argc] = p;
563 p += reslen;
564 total -= reslen;
566 wargv[argc] = NULL;
568 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
570 for (argc = 0; wargv[argc]; argc++)
571 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
573 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
574 q = (char *)(argv + argc + 1);
575 for (argc = 0; wargv[argc]; argc++)
577 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
578 argv[argc] = q;
579 q += reslen;
580 total -= reslen;
582 argv[argc] = NULL;
584 __wine_main_argc = argc;
585 __wine_main_argv = argv;
586 __wine_main_wargv = wargv;
590 /***********************************************************************
591 * build_command_line
593 * Build the command line of a process from the argv array.
595 * Note that it does NOT necessarily include the file name.
596 * Sometimes we don't even have any command line options at all.
598 * We must quote and escape characters so that the argv array can be rebuilt
599 * from the command line:
600 * - spaces and tabs must be quoted
601 * 'a b' -> '"a b"'
602 * - quotes must be escaped
603 * '"' -> '\"'
604 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
605 * resulting in an odd number of '\' followed by a '"'
606 * '\"' -> '\\\"'
607 * '\\"' -> '\\\\\"'
608 * - '\'s that are not followed by a '"' can be left as is
609 * 'a\b' == 'a\b'
610 * 'a\\b' == 'a\\b'
612 static BOOL build_command_line( WCHAR **argv )
614 int len;
615 WCHAR **arg;
616 LPWSTR p;
617 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
619 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
621 len = 0;
622 for (arg = argv; *arg; arg++)
624 int has_space,bcount;
625 WCHAR* a;
627 has_space=0;
628 bcount=0;
629 a=*arg;
630 if( !*a ) has_space=1;
631 while (*a!='\0') {
632 if (*a=='\\') {
633 bcount++;
634 } else {
635 if (*a==' ' || *a=='\t') {
636 has_space=1;
637 } else if (*a=='"') {
638 /* doubling of '\' preceding a '"',
639 * plus escaping of said '"'
641 len+=2*bcount+1;
643 bcount=0;
645 a++;
647 len+=(a-*arg)+1 /* for the separating space */;
648 if (has_space)
649 len+=2; /* for the quotes */
652 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
653 return FALSE;
655 p = rupp->CommandLine.Buffer;
656 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
657 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
658 for (arg = argv; *arg; arg++)
660 int has_space,has_quote;
661 WCHAR* a;
663 /* Check for quotes and spaces in this argument */
664 has_space=has_quote=0;
665 a=*arg;
666 if( !*a ) has_space=1;
667 while (*a!='\0') {
668 if (*a==' ' || *a=='\t') {
669 has_space=1;
670 if (has_quote)
671 break;
672 } else if (*a=='"') {
673 has_quote=1;
674 if (has_space)
675 break;
677 a++;
680 /* Now transfer it to the command line */
681 if (has_space)
682 *p++='"';
683 if (has_quote) {
684 int bcount;
685 WCHAR* a;
687 bcount=0;
688 a=*arg;
689 while (*a!='\0') {
690 if (*a=='\\') {
691 *p++=*a;
692 bcount++;
693 } else {
694 if (*a=='"') {
695 int i;
697 /* Double all the '\\' preceding this '"', plus one */
698 for (i=0;i<=bcount;i++)
699 *p++='\\';
700 *p++='"';
701 } else {
702 *p++=*a;
704 bcount=0;
706 a++;
708 } else {
709 WCHAR* x = *arg;
710 while ((*p=*x++)) p++;
712 if (has_space)
713 *p++='"';
714 *p++=' ';
716 if (p > rupp->CommandLine.Buffer)
717 p--; /* remove last space */
718 *p = '\0';
720 return TRUE;
724 /***********************************************************************
725 * init_current_directory
727 * Initialize the current directory from the Unix cwd or the parent info.
729 static void init_current_directory( CURDIR *cur_dir )
731 UNICODE_STRING dir_str;
732 char *cwd;
733 int size;
735 /* if we received a cur dir from the parent, try this first */
737 if (cur_dir->DosPath.Length)
739 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
742 /* now try to get it from the Unix cwd */
744 for (size = 256; ; size *= 2)
746 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
747 if (getcwd( cwd, size )) break;
748 HeapFree( GetProcessHeap(), 0, cwd );
749 if (errno == ERANGE) continue;
750 cwd = NULL;
751 break;
754 if (cwd)
756 WCHAR *dirW;
757 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
758 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
760 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
761 RtlInitUnicodeString( &dir_str, dirW );
762 RtlSetCurrentDirectory_U( &dir_str );
763 RtlFreeUnicodeString( &dir_str );
767 if (!cur_dir->DosPath.Length) /* still not initialized */
769 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
770 "starting in the Windows directory.\n", cwd ? cwd : "" );
771 RtlInitUnicodeString( &dir_str, DIR_Windows );
772 RtlSetCurrentDirectory_U( &dir_str );
774 HeapFree( GetProcessHeap(), 0, cwd );
776 done:
777 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
778 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
782 /***********************************************************************
783 * init_windows_dirs
785 * Initialize the windows and system directories from the environment.
787 static void init_windows_dirs(void)
789 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
791 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
792 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
793 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
794 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
796 DWORD len;
797 WCHAR *buffer;
799 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
801 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
802 GetEnvironmentVariableW( windirW, buffer, len );
803 DIR_Windows = buffer;
805 else DIR_Windows = default_windirW;
807 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
809 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
810 GetEnvironmentVariableW( winsysdirW, buffer, len );
811 DIR_System = buffer;
813 else
815 len = strlenW( DIR_Windows );
816 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
817 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
818 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
819 DIR_System = buffer;
822 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
823 ERR( "directory %s could not be created, error %u\n",
824 debugstr_w(DIR_Windows), GetLastError() );
825 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
826 ERR( "directory %s could not be created, error %u\n",
827 debugstr_w(DIR_System), GetLastError() );
829 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
830 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
832 /* set the directories in ntdll too */
833 __wine_init_windows_dir( DIR_Windows, DIR_System );
837 /***********************************************************************
838 * start_wineboot
840 * Start the wineboot process if necessary. Return the event to wait on.
842 static HANDLE start_wineboot(void)
844 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
845 HANDLE event;
847 if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
849 ERR( "failed to create wineboot event, expect trouble\n" );
850 return 0;
852 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
854 static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
855 STARTUPINFOW si;
856 PROCESS_INFORMATION pi;
857 WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];
859 memset( &si, 0, sizeof(si) );
860 si.cb = sizeof(si);
861 si.dwFlags = STARTF_USESTDHANDLES;
862 si.hStdInput = 0;
863 si.hStdOutput = 0;
864 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
866 GetSystemDirectoryW( cmdline, MAX_PATH );
867 lstrcatW( cmdline, command_line );
868 if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
870 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
871 CloseHandle( pi.hThread );
872 CloseHandle( pi.hProcess );
875 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
877 return event;
881 /***********************************************************************
882 * start_process
884 * Startup routine of a new process. Runs on the new process stack.
886 static void start_process( void *arg )
888 __TRY
890 PEB *peb = NtCurrentTeb()->Peb;
891 IMAGE_NT_HEADERS *nt;
892 LPTHREAD_START_ROUTINE entry;
894 nt = RtlImageNtHeader( peb->ImageBaseAddress );
895 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
896 nt->OptionalHeader.AddressOfEntryPoint);
898 if (TRACE_ON(relay))
899 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
900 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
902 SetLastError( 0 ); /* clear error code */
903 if (peb->BeingDebugged) DbgBreakPoint();
904 ExitThread( entry( peb ) );
906 __EXCEPT(UnhandledExceptionFilter)
908 TerminateThread( GetCurrentThread(), GetExceptionCode() );
910 __ENDTRY
914 /***********************************************************************
915 * set_process_name
917 * Change the process name in the ps output.
919 static void set_process_name( int argc, char *argv[] )
921 #ifdef HAVE_SETPROCTITLE
922 setproctitle("-%s", argv[1]);
923 #endif
925 #ifdef HAVE_PRCTL
926 int i, offset;
927 char *p, *prctl_name = argv[1];
928 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
930 #ifndef PR_SET_NAME
931 # define PR_SET_NAME 15
932 #endif
934 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
935 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
937 if (prctl( PR_SET_NAME, prctl_name ) != -1)
939 offset = argv[1] - argv[0];
940 memmove( argv[1] - offset, argv[1], end - argv[1] );
941 memset( end - offset, 0, offset );
942 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
943 argv[i-1] = NULL;
945 else
946 #endif /* HAVE_PRCTL */
948 /* remove argv[0] */
949 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
954 /***********************************************************************
955 * __wine_kernel_init
957 * Wine initialisation: load and start the main exe file.
959 void __wine_kernel_init(void)
961 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
962 static const WCHAR dotW[] = {'.',0};
963 static const WCHAR exeW[] = {'.','e','x','e',0};
965 WCHAR *p, main_exe_name[MAX_PATH+1];
966 PEB *peb = NtCurrentTeb()->Peb;
967 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
968 HANDLE boot_event = 0;
969 BOOL got_environment = TRUE;
971 /* Initialize everything */
973 PTHREAD_Init();
975 setbuf(stdout,NULL);
976 setbuf(stderr,NULL);
977 kernel32_handle = GetModuleHandleW(kernel32W);
979 LOCALE_Init();
981 if (!params->Environment)
983 /* Copy the parent environment */
984 if (!build_initial_environment( __wine_main_environ )) exit(1);
986 /* convert old configuration to new format */
987 convert_old_config();
989 got_environment = set_registry_environment();
990 set_additional_environment();
993 init_windows_dirs();
994 init_current_directory( &params->CurrentDirectory );
996 set_process_name( __wine_main_argc, __wine_main_argv );
997 set_library_wargv( __wine_main_argv );
999 if (peb->ProcessParameters->ImagePathName.Buffer)
1001 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1003 else
1005 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1006 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1008 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1009 ExitProcess( GetLastError() );
1011 if (!build_command_line( __wine_main_wargv )) goto error;
1012 boot_event = start_wineboot();
1015 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1016 p = strrchrW( main_exe_name, '.' );
1017 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1019 TRACE( "starting process name=%s argv[0]=%s\n",
1020 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1022 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1023 MODULE_get_dll_load_path(main_exe_name) );
1025 if (boot_event)
1027 if (WaitForSingleObject( boot_event, 30000 )) WARN( "boot event wait timed out\n" );
1028 CloseHandle( boot_event );
1029 /* if we didn't find environment section, try again now that wineboot has run */
1030 if (!got_environment)
1032 set_registry_environment();
1033 set_additional_environment();
1037 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1039 char msg[1024];
1040 DWORD error = GetLastError();
1042 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1043 if (error == ERROR_BAD_EXE_FORMAT ||
1044 error == ERROR_INVALID_ADDRESS ||
1045 error == ERROR_NOT_ENOUGH_MEMORY)
1047 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1048 /* if we get back here, it failed */
1051 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1052 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1053 ExitProcess( error );
1056 LdrInitializeThunk( 0, 0, 0, 0 );
1057 /* switch to the new stack */
1058 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1060 error:
1061 ExitProcess( GetLastError() );
1065 /***********************************************************************
1066 * build_argv
1068 * Build an argv array from a command-line.
1069 * 'reserved' is the number of args to reserve before the first one.
1071 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1073 int argc;
1074 char** argv;
1075 char *arg,*s,*d,*cmdline;
1076 int in_quotes,bcount,len;
1078 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1079 if (!(cmdline = malloc(len))) return NULL;
1080 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1082 argc=reserved+1;
1083 bcount=0;
1084 in_quotes=0;
1085 s=cmdline;
1086 while (1) {
1087 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1088 /* space */
1089 argc++;
1090 /* skip the remaining spaces */
1091 while (*s==' ' || *s=='\t') {
1092 s++;
1094 if (*s=='\0')
1095 break;
1096 bcount=0;
1097 continue;
1098 } else if (*s=='\\') {
1099 /* '\', count them */
1100 bcount++;
1101 } else if ((*s=='"') && ((bcount & 1)==0)) {
1102 /* unescaped '"' */
1103 in_quotes=!in_quotes;
1104 bcount=0;
1105 } else {
1106 /* a regular character */
1107 bcount=0;
1109 s++;
1111 argv=malloc(argc*sizeof(*argv));
1112 if (!argv)
1113 return NULL;
1115 arg=d=s=cmdline;
1116 bcount=0;
1117 in_quotes=0;
1118 argc=reserved;
1119 while (*s) {
1120 if ((*s==' ' || *s=='\t') && !in_quotes) {
1121 /* Close the argument and copy it */
1122 *d=0;
1123 argv[argc++]=arg;
1125 /* skip the remaining spaces */
1126 do {
1127 s++;
1128 } while (*s==' ' || *s=='\t');
1130 /* Start with a new argument */
1131 arg=d=s;
1132 bcount=0;
1133 } else if (*s=='\\') {
1134 /* '\\' */
1135 *d++=*s++;
1136 bcount++;
1137 } else if (*s=='"') {
1138 /* '"' */
1139 if ((bcount & 1)==0) {
1140 /* Preceded by an even number of '\', this is half that
1141 * number of '\', plus a '"' which we discard.
1143 d-=bcount/2;
1144 s++;
1145 in_quotes=!in_quotes;
1146 } else {
1147 /* Preceded by an odd number of '\', this is half that
1148 * number of '\' followed by a '"'
1150 d=d-bcount/2-1;
1151 *d++='"';
1152 s++;
1154 bcount=0;
1155 } else {
1156 /* a regular character */
1157 *d++=*s++;
1158 bcount=0;
1161 if (*arg) {
1162 *d='\0';
1163 argv[argc++]=arg;
1165 argv[argc]=NULL;
1167 return argv;
1171 /***********************************************************************
1172 * alloc_env_string
1174 * Allocate an environment string; helper for build_envp
1176 static char *alloc_env_string( const char *name, const char *value )
1178 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1179 strcpy( ret, name );
1180 strcat( ret, value );
1181 return ret;
1184 /***********************************************************************
1185 * build_envp
1187 * Build the environment of a new child process.
1189 static char **build_envp( const WCHAR *envW )
1191 const WCHAR *end;
1192 char **envp;
1193 char *env, *p;
1194 int count = 0, length;
1196 for (end = envW; *end; count++) end += strlenW(end) + 1;
1197 end++;
1198 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1199 if (!(env = malloc( length ))) return NULL;
1200 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1202 count += 4;
1204 if ((envp = malloc( count * sizeof(*envp) )))
1206 char **envptr = envp;
1208 /* some variables must not be modified, so we get them directly from the unix env */
1209 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1210 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1211 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1212 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1213 /* now put the Windows environment strings */
1214 for (p = env; *p; p += strlen(p) + 1)
1216 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1217 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1218 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1219 if (is_special_env_var( p )) /* prefix it with "WINE" */
1220 *envptr++ = alloc_env_string( "WINE", p );
1221 else
1222 *envptr++ = p;
1224 *envptr = 0;
1226 return envp;
1230 /***********************************************************************
1231 * fork_and_exec
1233 * Fork and exec a new Unix binary, checking for errors.
1235 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1236 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1238 int fd[2], stdin_fd = -1, stdout_fd = -1;
1239 int pid, err;
1241 if (!env) env = GetEnvironmentStringsW();
1243 if (pipe(fd) == -1)
1245 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1246 return -1;
1248 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1250 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1252 HANDLE hstdin, hstdout;
1254 if (startup->dwFlags & STARTF_USESTDHANDLES)
1256 hstdin = startup->hStdInput;
1257 hstdout = startup->hStdOutput;
1259 else
1261 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1262 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1265 if (is_console_handle( hstdin )) hstdin = console_handle_unmap( hstdin );
1266 if (is_console_handle( hstdout )) hstdout = console_handle_unmap( hstdout );
1267 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1268 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1271 if (!(pid = fork())) /* child */
1273 char **argv = build_argv( cmdline, 0 );
1274 char **envp = build_envp( env );
1275 close( fd[0] );
1277 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1279 int pid;
1280 if (!(pid = fork()))
1282 int fd = open( "/dev/null", O_RDWR );
1283 setsid();
1284 /* close stdin and stdout */
1285 if (fd != -1)
1287 dup2( fd, 0 );
1288 dup2( fd, 1 );
1289 close( fd );
1292 else if (pid != -1) _exit(0); /* parent */
1294 else
1296 if (stdin_fd != -1)
1298 dup2( stdin_fd, 0 );
1299 close( stdin_fd );
1301 if (stdout_fd != -1)
1303 dup2( stdout_fd, 1 );
1304 close( stdout_fd );
1308 /* Reset signals that we previously set to SIG_IGN */
1309 signal( SIGPIPE, SIG_DFL );
1310 signal( SIGCHLD, SIG_DFL );
1312 if (newdir) chdir(newdir);
1314 if (argv && envp) execve( filename, argv, envp );
1315 err = errno;
1316 write( fd[1], &err, sizeof(err) );
1317 _exit(1);
1319 if (stdin_fd != -1) close( stdin_fd );
1320 if (stdout_fd != -1) close( stdout_fd );
1321 close( fd[1] );
1322 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1324 errno = err;
1325 pid = -1;
1327 if (pid == -1) FILE_SetDosError();
1328 close( fd[0] );
1329 return pid;
1333 /***********************************************************************
1334 * create_user_params
1336 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1337 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1338 const STARTUPINFOW *startup )
1340 RTL_USER_PROCESS_PARAMETERS *params;
1341 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1342 NTSTATUS status;
1343 WCHAR buffer[MAX_PATH];
1345 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1346 lstrcpynW( buffer, filename, MAX_PATH );
1347 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1348 lstrcpynW( buffer, filename, MAX_PATH );
1349 RtlInitUnicodeString( &image_str, buffer );
1351 RtlInitUnicodeString( &cmdline_str, cmdline );
1352 newdir.Buffer = NULL;
1353 if (cur_dir)
1355 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1357 /* skip \??\ prefix */
1358 curdir_str.Buffer = newdir.Buffer + 4;
1359 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1360 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1362 else cur_dir = NULL;
1364 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1365 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1366 if (startup->lpReserved2 && startup->cbReserved2)
1368 runtime.Length = 0;
1369 runtime.MaximumLength = startup->cbReserved2;
1370 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1373 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1374 cur_dir ? &curdir_str : NULL,
1375 &cmdline_str, env,
1376 startup->lpTitle ? &title : NULL,
1377 startup->lpDesktop ? &desktop : NULL,
1378 NULL,
1379 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1380 RtlFreeUnicodeString( &newdir );
1381 if (status != STATUS_SUCCESS)
1383 SetLastError( RtlNtStatusToDosError(status) );
1384 return NULL;
1387 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1388 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1390 if (startup->dwFlags & STARTF_USESTDHANDLES)
1392 params->hStdInput = startup->hStdInput;
1393 params->hStdOutput = startup->hStdOutput;
1394 params->hStdError = startup->hStdError;
1396 else
1398 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1399 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1400 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1402 params->dwX = startup->dwX;
1403 params->dwY = startup->dwY;
1404 params->dwXSize = startup->dwXSize;
1405 params->dwYSize = startup->dwYSize;
1406 params->dwXCountChars = startup->dwXCountChars;
1407 params->dwYCountChars = startup->dwYCountChars;
1408 params->dwFillAttribute = startup->dwFillAttribute;
1409 params->dwFlags = startup->dwFlags;
1410 params->wShowWindow = startup->wShowWindow;
1411 return params;
1415 /***********************************************************************
1416 * create_process
1418 * Create a new process. If hFile is a valid handle we have an exe
1419 * file, otherwise it is a Winelib app.
1421 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1422 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1423 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1424 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1425 void *res_start, void *res_end, int exec_only )
1427 BOOL ret, success = FALSE;
1428 HANDLE process_info, hstdin, hstdout;
1429 WCHAR *env_end;
1430 char *winedebug = NULL;
1431 RTL_USER_PROCESS_PARAMETERS *params;
1432 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1433 pid_t pid;
1434 int err;
1436 if (!env) RtlAcquirePebLock();
1438 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1440 if (!env) RtlReleasePebLock();
1441 return FALSE;
1443 env_end = params->Environment;
1444 while (*env_end)
1446 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1447 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1449 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1450 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1451 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1453 env_end += strlenW(env_end) + 1;
1455 env_end++;
1457 /* create the socket for the new process */
1459 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1461 if (!env) RtlReleasePebLock();
1462 HeapFree( GetProcessHeap(), 0, winedebug );
1463 RtlDestroyProcessParameters( params );
1464 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1465 return FALSE;
1467 wine_server_send_fd( socketfd[1] );
1468 close( socketfd[1] );
1470 /* create the process on the server side */
1472 SERVER_START_REQ( new_process )
1474 req->inherit_all = inherit;
1475 req->create_flags = flags;
1476 req->socket_fd = socketfd[1];
1477 req->exe_file = hFile;
1478 req->process_access = PROCESS_ALL_ACCESS;
1479 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1480 req->thread_access = THREAD_ALL_ACCESS;
1481 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1482 req->hstdin = params->hStdInput;
1483 req->hstdout = params->hStdOutput;
1484 req->hstderr = params->hStdError;
1486 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1488 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1489 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1490 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1491 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1492 hstdin = hstdout = 0;
1494 else
1496 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1497 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1498 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1499 hstdin = req->hstdin;
1500 hstdout = req->hstdout;
1503 wine_server_add_data( req, params, params->Size );
1504 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1505 if ((ret = !wine_server_call_err( req )))
1507 info->dwProcessId = (DWORD)reply->pid;
1508 info->dwThreadId = (DWORD)reply->tid;
1509 info->hProcess = reply->phandle;
1510 info->hThread = reply->thandle;
1512 process_info = reply->info;
1514 SERVER_END_REQ;
1516 if (!env) RtlReleasePebLock();
1517 RtlDestroyProcessParameters( params );
1518 if (!ret)
1520 close( socketfd[0] );
1521 HeapFree( GetProcessHeap(), 0, winedebug );
1522 return FALSE;
1525 if (hstdin) wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1526 if (hstdout) wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1528 /* create the child process */
1530 if (exec_only || !(pid = fork())) /* child */
1532 char preloader_reserve[64], socket_env[64];
1533 char **argv = build_argv( cmd_line, 1 );
1535 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1537 if (!(pid = fork()))
1539 int fd = open( "/dev/null", O_RDWR );
1540 setsid();
1541 /* close stdin and stdout */
1542 if (fd != -1)
1544 dup2( fd, 0 );
1545 dup2( fd, 1 );
1546 close( fd );
1549 else if (pid != -1) _exit(0); /* parent */
1551 else
1553 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1554 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1557 if (stdin_fd != -1) close( stdin_fd );
1558 if (stdout_fd != -1) close( stdout_fd );
1560 /* Reset signals that we previously set to SIG_IGN */
1561 signal( SIGPIPE, SIG_DFL );
1562 signal( SIGCHLD, SIG_DFL );
1564 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1565 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1566 (unsigned long)res_start, (unsigned long)res_end );
1568 putenv( preloader_reserve );
1569 putenv( socket_env );
1570 if (winedebug) putenv( winedebug );
1571 if (unixdir) chdir(unixdir);
1573 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1574 _exit(1);
1577 /* this is the parent */
1579 if (stdin_fd != -1) close( stdin_fd );
1580 if (stdout_fd != -1) close( stdout_fd );
1581 close( socketfd[0] );
1582 HeapFree( GetProcessHeap(), 0, winedebug );
1583 if (pid == -1)
1585 FILE_SetDosError();
1586 goto error;
1589 /* wait for the new process info to be ready */
1591 WaitForSingleObject( process_info, INFINITE );
1592 SERVER_START_REQ( get_new_process_info )
1594 req->info = process_info;
1595 wine_server_call( req );
1596 success = reply->success;
1597 err = reply->exit_code;
1599 SERVER_END_REQ;
1601 if (!success)
1603 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1604 goto error;
1606 CloseHandle( process_info );
1607 return success;
1609 error:
1610 CloseHandle( process_info );
1611 CloseHandle( info->hProcess );
1612 CloseHandle( info->hThread );
1613 info->hProcess = info->hThread = 0;
1614 info->dwProcessId = info->dwThreadId = 0;
1615 return FALSE;
1619 /***********************************************************************
1620 * create_vdm_process
1622 * Create a new VDM process for a 16-bit or DOS application.
1624 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1625 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1626 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1627 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1629 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1631 BOOL ret;
1632 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1633 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1635 if (!new_cmd_line)
1637 SetLastError( ERROR_OUTOFMEMORY );
1638 return FALSE;
1640 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1641 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1642 flags, startup, info, unixdir, NULL, NULL, exec_only );
1643 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1644 return ret;
1648 /***********************************************************************
1649 * create_cmd_process
1651 * Create a new cmd shell process for a .BAT file.
1653 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1654 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1655 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1656 LPPROCESS_INFORMATION info )
1659 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1660 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1661 WCHAR comspec[MAX_PATH];
1662 WCHAR *newcmdline;
1663 BOOL ret;
1665 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1666 return FALSE;
1667 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1668 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1669 return FALSE;
1671 strcpyW( newcmdline, comspec );
1672 strcatW( newcmdline, slashcW );
1673 strcatW( newcmdline, cmd_line );
1674 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1675 flags, env, cur_dir, startup, info );
1676 HeapFree( GetProcessHeap(), 0, newcmdline );
1677 return ret;
1681 /*************************************************************************
1682 * get_file_name
1684 * Helper for CreateProcess: retrieve the file name to load from the
1685 * app name and command line. Store the file name in buffer, and
1686 * return a possibly modified command line.
1687 * Also returns a handle to the opened file if it's a Windows binary.
1689 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1690 int buflen, HANDLE *handle )
1692 static const WCHAR quotesW[] = {'"','%','s','"',0};
1694 WCHAR *name, *pos, *ret = NULL;
1695 const WCHAR *p;
1696 BOOL got_space;
1698 /* if we have an app name, everything is easy */
1700 if (appname)
1702 /* use the unmodified app name as file name */
1703 lstrcpynW( buffer, appname, buflen );
1704 *handle = open_exe_file( buffer );
1705 if (!(ret = cmdline) || !cmdline[0])
1707 /* no command-line, create one */
1708 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1709 sprintfW( ret, quotesW, appname );
1711 return ret;
1714 if (!cmdline)
1716 SetLastError( ERROR_INVALID_PARAMETER );
1717 return NULL;
1720 /* first check for a quoted file name */
1722 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1724 int len = p - cmdline - 1;
1725 /* extract the quoted portion as file name */
1726 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1727 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1728 name[len] = 0;
1730 if (find_exe_file( name, buffer, buflen, handle ))
1731 ret = cmdline; /* no change necessary */
1732 goto done;
1735 /* now try the command-line word by word */
1737 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1738 return NULL;
1739 pos = name;
1740 p = cmdline;
1741 got_space = FALSE;
1743 while (*p)
1745 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1746 *pos = 0;
1747 if (find_exe_file( name, buffer, buflen, handle ))
1749 ret = cmdline;
1750 break;
1752 if (*p) got_space = TRUE;
1755 if (ret && got_space) /* now build a new command-line with quotes */
1757 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1758 goto done;
1759 sprintfW( ret, quotesW, name );
1760 strcatW( ret, p );
1763 done:
1764 HeapFree( GetProcessHeap(), 0, name );
1765 return ret;
1769 /**********************************************************************
1770 * CreateProcessA (KERNEL32.@)
1772 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1773 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1774 DWORD flags, LPVOID env, LPCSTR cur_dir,
1775 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1777 BOOL ret = FALSE;
1778 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1779 UNICODE_STRING desktopW, titleW;
1780 STARTUPINFOW infoW;
1782 desktopW.Buffer = NULL;
1783 titleW.Buffer = NULL;
1784 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1785 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1786 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1788 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1789 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1791 memcpy( &infoW, startup_info, sizeof(infoW) );
1792 infoW.lpDesktop = desktopW.Buffer;
1793 infoW.lpTitle = titleW.Buffer;
1795 if (startup_info->lpReserved)
1796 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1797 debugstr_a(startup_info->lpReserved));
1799 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1800 inherit, flags, env, cur_dirW, &infoW, info );
1801 done:
1802 HeapFree( GetProcessHeap(), 0, app_nameW );
1803 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1804 HeapFree( GetProcessHeap(), 0, cur_dirW );
1805 RtlFreeUnicodeString( &desktopW );
1806 RtlFreeUnicodeString( &titleW );
1807 return ret;
1811 /**********************************************************************
1812 * CreateProcessW (KERNEL32.@)
1814 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1815 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1816 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1817 LPPROCESS_INFORMATION info )
1819 BOOL retv = FALSE;
1820 HANDLE hFile = 0;
1821 char *unixdir = NULL;
1822 WCHAR name[MAX_PATH];
1823 WCHAR *tidy_cmdline, *p, *envW = env;
1824 void *res_start, *res_end;
1826 /* Process the AppName and/or CmdLine to get module name and path */
1828 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1830 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1831 return FALSE;
1832 if (hFile == INVALID_HANDLE_VALUE) goto done;
1834 /* Warn if unsupported features are used */
1836 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1837 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1838 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1839 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1840 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1842 if (cur_dir)
1844 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1846 SetLastError(ERROR_DIRECTORY);
1847 goto done;
1850 else
1852 WCHAR buf[MAX_PATH];
1853 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1856 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1858 char *p = env;
1859 DWORD lenW;
1861 while (*p) p += strlen(p) + 1;
1862 p++; /* final null */
1863 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1864 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1865 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1866 flags |= CREATE_UNICODE_ENVIRONMENT;
1869 info->hThread = info->hProcess = 0;
1870 info->dwProcessId = info->dwThreadId = 0;
1872 /* Determine executable type */
1874 if (!hFile) /* builtin exe */
1876 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1877 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1878 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1879 goto done;
1882 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1884 case BINARY_PE_EXE:
1885 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1886 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1887 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1888 break;
1889 case BINARY_OS216:
1890 case BINARY_WIN16:
1891 case BINARY_DOS:
1892 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1893 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1894 inherit, flags, startup_info, info, unixdir, FALSE );
1895 break;
1896 case BINARY_PE_DLL:
1897 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1898 SetLastError( ERROR_BAD_EXE_FORMAT );
1899 break;
1900 case BINARY_UNIX_LIB:
1901 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1902 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1903 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1904 break;
1905 case BINARY_UNKNOWN:
1906 /* check for .com or .bat extension */
1907 if ((p = strrchrW( name, '.' )))
1909 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1911 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1912 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1913 inherit, flags, startup_info, info, unixdir, FALSE );
1914 break;
1916 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1918 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1919 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1920 inherit, flags, startup_info, info );
1921 break;
1924 /* fall through */
1925 case BINARY_UNIX_EXE:
1927 /* unknown file, try as unix executable */
1928 char *unix_name;
1930 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1932 if ((unix_name = wine_get_unix_file_name( name )))
1934 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
1935 HeapFree( GetProcessHeap(), 0, unix_name );
1938 break;
1940 CloseHandle( hFile );
1942 done:
1943 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1944 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1945 HeapFree( GetProcessHeap(), 0, unixdir );
1946 if (retv)
1947 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
1948 return retv;
1952 /**********************************************************************
1953 * exec_process
1955 static void exec_process( LPCWSTR name )
1957 HANDLE hFile;
1958 WCHAR *p;
1959 void *res_start, *res_end;
1960 STARTUPINFOW startup_info;
1961 PROCESS_INFORMATION info;
1963 hFile = open_exe_file( name );
1964 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
1966 memset( &startup_info, 0, sizeof(startup_info) );
1967 startup_info.cb = sizeof(startup_info);
1969 /* Determine executable type */
1971 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1973 case BINARY_PE_EXE:
1974 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1975 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1976 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
1977 break;
1978 case BINARY_UNIX_LIB:
1979 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1980 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1981 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
1982 break;
1983 case BINARY_UNKNOWN:
1984 /* check for .com or .pif extension */
1985 if (!(p = strrchrW( name, '.' ))) break;
1986 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
1987 /* fall through */
1988 case BINARY_OS216:
1989 case BINARY_WIN16:
1990 case BINARY_DOS:
1991 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1992 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1993 FALSE, 0, &startup_info, &info, NULL, TRUE );
1994 break;
1995 default:
1996 break;
1998 CloseHandle( hFile );
2002 /***********************************************************************
2003 * wait_input_idle
2005 * Wrapper to call WaitForInputIdle USER function
2007 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2009 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2011 HMODULE mod = GetModuleHandleA( "user32.dll" );
2012 if (mod)
2014 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2015 if (ptr) return ptr( process, timeout );
2017 return 0;
2021 /***********************************************************************
2022 * WinExec (KERNEL32.@)
2024 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2026 PROCESS_INFORMATION info;
2027 STARTUPINFOA startup;
2028 char *cmdline;
2029 UINT ret;
2031 memset( &startup, 0, sizeof(startup) );
2032 startup.cb = sizeof(startup);
2033 startup.dwFlags = STARTF_USESHOWWINDOW;
2034 startup.wShowWindow = nCmdShow;
2036 /* cmdline needs to be writable for CreateProcess */
2037 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2038 strcpy( cmdline, lpCmdLine );
2040 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2041 0, NULL, NULL, &startup, &info ))
2043 /* Give 30 seconds to the app to come up */
2044 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2045 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2046 ret = 33;
2047 /* Close off the handles */
2048 CloseHandle( info.hThread );
2049 CloseHandle( info.hProcess );
2051 else if ((ret = GetLastError()) >= 32)
2053 FIXME("Strange error set by CreateProcess: %d\n", ret );
2054 ret = 11;
2056 HeapFree( GetProcessHeap(), 0, cmdline );
2057 return ret;
2061 /**********************************************************************
2062 * LoadModule (KERNEL32.@)
2064 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2066 LOADPARMS32 *params = paramBlock;
2067 PROCESS_INFORMATION info;
2068 STARTUPINFOA startup;
2069 HINSTANCE hInstance;
2070 LPSTR cmdline, p;
2071 char filename[MAX_PATH];
2072 BYTE len;
2074 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2076 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2077 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2078 return ULongToHandle(GetLastError());
2080 len = (BYTE)params->lpCmdLine[0];
2081 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2082 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2084 strcpy( cmdline, filename );
2085 p = cmdline + strlen(cmdline);
2086 *p++ = ' ';
2087 memcpy( p, params->lpCmdLine + 1, len );
2088 p[len] = 0;
2090 memset( &startup, 0, sizeof(startup) );
2091 startup.cb = sizeof(startup);
2092 if (params->lpCmdShow)
2094 startup.dwFlags = STARTF_USESHOWWINDOW;
2095 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2098 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2099 params->lpEnvAddress, NULL, &startup, &info ))
2101 /* Give 30 seconds to the app to come up */
2102 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2103 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2104 hInstance = (HINSTANCE)33;
2105 /* Close off the handles */
2106 CloseHandle( info.hThread );
2107 CloseHandle( info.hProcess );
2109 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2111 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2112 hInstance = (HINSTANCE)11;
2115 HeapFree( GetProcessHeap(), 0, cmdline );
2116 return hInstance;
2120 /******************************************************************************
2121 * TerminateProcess (KERNEL32.@)
2123 * Terminates a process.
2125 * PARAMS
2126 * handle [I] Process to terminate.
2127 * exit_code [I] Exit code.
2129 * RETURNS
2130 * Success: TRUE.
2131 * Failure: FALSE, check GetLastError().
2133 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2135 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2136 if (status) SetLastError( RtlNtStatusToDosError(status) );
2137 return !status;
2140 /***********************************************************************
2141 * ExitProcess (KERNEL32.@)
2143 * Exits the current process.
2145 * PARAMS
2146 * status [I] Status code to exit with.
2148 * RETURNS
2149 * Nothing.
2151 #ifdef __i386__
2152 __ASM_GLOBAL_FUNC( ExitProcess, /* Shrinker depend on this particular ExitProcess implementation */
2153 "pushl %ebp\n\t"
2154 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2155 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2156 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2157 "pushl 8(%ebp)\n\t"
2158 "call " __ASM_NAME("process_ExitProcess") "\n\t"
2159 "leave\n\t"
2160 "ret $4" )
2162 void WINAPI process_ExitProcess( DWORD status )
2164 LdrShutdownProcess();
2165 NtTerminateProcess(GetCurrentProcess(), status);
2166 exit(status);
2169 #else
2171 void WINAPI ExitProcess( DWORD status )
2173 LdrShutdownProcess();
2174 NtTerminateProcess(GetCurrentProcess(), status);
2175 exit(status);
2178 #endif
2180 /***********************************************************************
2181 * GetExitCodeProcess [KERNEL32.@]
2183 * Gets termination status of specified process.
2185 * PARAMS
2186 * hProcess [in] Handle to the process.
2187 * lpExitCode [out] Address to receive termination status.
2189 * RETURNS
2190 * Success: TRUE
2191 * Failure: FALSE
2193 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2195 NTSTATUS status;
2196 PROCESS_BASIC_INFORMATION pbi;
2198 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2199 sizeof(pbi), NULL);
2200 if (status == STATUS_SUCCESS)
2202 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2203 return TRUE;
2205 SetLastError( RtlNtStatusToDosError(status) );
2206 return FALSE;
2210 /***********************************************************************
2211 * SetErrorMode (KERNEL32.@)
2213 UINT WINAPI SetErrorMode( UINT mode )
2215 UINT old = process_error_mode;
2216 process_error_mode = mode;
2217 return old;
2221 /**********************************************************************
2222 * TlsAlloc [KERNEL32.@]
2224 * Allocates a thread local storage index.
2226 * RETURNS
2227 * Success: TLS index.
2228 * Failure: 0xFFFFFFFF
2230 DWORD WINAPI TlsAlloc( void )
2232 DWORD index;
2233 PEB * const peb = NtCurrentTeb()->Peb;
2235 RtlAcquirePebLock();
2236 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2237 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2238 else
2240 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2241 if (index != ~0U)
2243 if (!NtCurrentTeb()->TlsExpansionSlots &&
2244 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2245 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2247 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2248 index = ~0U;
2249 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2251 else
2253 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2254 index += TLS_MINIMUM_AVAILABLE;
2257 else SetLastError( ERROR_NO_MORE_ITEMS );
2259 RtlReleasePebLock();
2260 return index;
2264 /**********************************************************************
2265 * TlsFree [KERNEL32.@]
2267 * Releases a thread local storage index, making it available for reuse.
2269 * PARAMS
2270 * index [in] TLS index to free.
2272 * RETURNS
2273 * Success: TRUE
2274 * Failure: FALSE
2276 BOOL WINAPI TlsFree( DWORD index )
2278 BOOL ret;
2280 RtlAcquirePebLock();
2281 if (index >= TLS_MINIMUM_AVAILABLE)
2283 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2284 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2286 else
2288 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2289 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2291 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2292 else SetLastError( ERROR_INVALID_PARAMETER );
2293 RtlReleasePebLock();
2294 return TRUE;
2298 /**********************************************************************
2299 * TlsGetValue [KERNEL32.@]
2301 * Gets value in a thread's TLS slot.
2303 * PARAMS
2304 * index [in] TLS index to retrieve value for.
2306 * RETURNS
2307 * Success: Value stored in calling thread's TLS slot for index.
2308 * Failure: 0 and GetLastError() returns NO_ERROR.
2310 LPVOID WINAPI TlsGetValue( DWORD index )
2312 LPVOID ret;
2314 if (index < TLS_MINIMUM_AVAILABLE)
2316 ret = NtCurrentTeb()->TlsSlots[index];
2318 else
2320 index -= TLS_MINIMUM_AVAILABLE;
2321 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2323 SetLastError( ERROR_INVALID_PARAMETER );
2324 return NULL;
2326 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2327 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2329 SetLastError( ERROR_SUCCESS );
2330 return ret;
2334 /**********************************************************************
2335 * TlsSetValue [KERNEL32.@]
2337 * Stores a value in the thread's TLS slot.
2339 * PARAMS
2340 * index [in] TLS index to set value for.
2341 * value [in] Value to be stored.
2343 * RETURNS
2344 * Success: TRUE
2345 * Failure: FALSE
2347 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2349 if (index < TLS_MINIMUM_AVAILABLE)
2351 NtCurrentTeb()->TlsSlots[index] = value;
2353 else
2355 index -= TLS_MINIMUM_AVAILABLE;
2356 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2358 SetLastError( ERROR_INVALID_PARAMETER );
2359 return FALSE;
2361 if (!NtCurrentTeb()->TlsExpansionSlots &&
2362 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2363 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2365 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2366 return FALSE;
2368 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2370 return TRUE;
2374 /***********************************************************************
2375 * GetProcessFlags (KERNEL32.@)
2377 DWORD WINAPI GetProcessFlags( DWORD processid )
2379 IMAGE_NT_HEADERS *nt;
2380 DWORD flags = 0;
2382 if (processid && processid != GetCurrentProcessId()) return 0;
2384 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2386 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2387 flags |= PDB32_CONSOLE_PROC;
2389 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2390 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2391 return flags;
2395 /***********************************************************************
2396 * GetProcessDword (KERNEL.485)
2397 * GetProcessDword (KERNEL32.18)
2398 * 'Of course you cannot directly access Windows internal structures'
2400 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2402 DWORD x, y;
2403 STARTUPINFOW siw;
2405 TRACE("(%d, %d)\n", dwProcessID, offset );
2407 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2409 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2410 return 0;
2413 switch ( offset )
2415 case GPD_APP_COMPAT_FLAGS:
2416 return GetAppCompatFlags16(0);
2417 case GPD_LOAD_DONE_EVENT:
2418 return 0;
2419 case GPD_HINSTANCE16:
2420 return GetTaskDS16();
2421 case GPD_WINDOWS_VERSION:
2422 return GetExeVersion16();
2423 case GPD_THDB:
2424 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2425 case GPD_PDB:
2426 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2427 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2428 GetStartupInfoW(&siw);
2429 return HandleToULong(siw.hStdOutput);
2430 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2431 GetStartupInfoW(&siw);
2432 return HandleToULong(siw.hStdInput);
2433 case GPD_STARTF_SHOWWINDOW:
2434 GetStartupInfoW(&siw);
2435 return siw.wShowWindow;
2436 case GPD_STARTF_SIZE:
2437 GetStartupInfoW(&siw);
2438 x = siw.dwXSize;
2439 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2440 y = siw.dwYSize;
2441 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2442 return MAKELONG( x, y );
2443 case GPD_STARTF_POSITION:
2444 GetStartupInfoW(&siw);
2445 x = siw.dwX;
2446 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2447 y = siw.dwY;
2448 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2449 return MAKELONG( x, y );
2450 case GPD_STARTF_FLAGS:
2451 GetStartupInfoW(&siw);
2452 return siw.dwFlags;
2453 case GPD_PARENT:
2454 return 0;
2455 case GPD_FLAGS:
2456 return GetProcessFlags(0);
2457 case GPD_USERDATA:
2458 return process_dword;
2459 default:
2460 ERR("Unknown offset %d\n", offset );
2461 return 0;
2465 /***********************************************************************
2466 * SetProcessDword (KERNEL.484)
2467 * 'Of course you cannot directly access Windows internal structures'
2469 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2471 TRACE("(%d, %d)\n", dwProcessID, offset );
2473 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2475 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2476 return;
2479 switch ( offset )
2481 case GPD_APP_COMPAT_FLAGS:
2482 case GPD_LOAD_DONE_EVENT:
2483 case GPD_HINSTANCE16:
2484 case GPD_WINDOWS_VERSION:
2485 case GPD_THDB:
2486 case GPD_PDB:
2487 case GPD_STARTF_SHELLDATA:
2488 case GPD_STARTF_HOTKEY:
2489 case GPD_STARTF_SHOWWINDOW:
2490 case GPD_STARTF_SIZE:
2491 case GPD_STARTF_POSITION:
2492 case GPD_STARTF_FLAGS:
2493 case GPD_PARENT:
2494 case GPD_FLAGS:
2495 ERR("Not allowed to modify offset %d\n", offset );
2496 break;
2497 case GPD_USERDATA:
2498 process_dword = value;
2499 break;
2500 default:
2501 ERR("Unknown offset %d\n", offset );
2502 break;
2507 /***********************************************************************
2508 * ExitProcess (KERNEL.466)
2510 void WINAPI ExitProcess16( WORD status )
2512 DWORD count;
2513 ReleaseThunkLock( &count );
2514 ExitProcess( status );
2518 /*********************************************************************
2519 * OpenProcess (KERNEL32.@)
2521 * Opens a handle to a process.
2523 * PARAMS
2524 * access [I] Desired access rights assigned to the returned handle.
2525 * inherit [I] Determines whether or not child processes will inherit the handle.
2526 * id [I] Process identifier of the process to get a handle to.
2528 * RETURNS
2529 * Success: Valid handle to the specified process.
2530 * Failure: NULL, check GetLastError().
2532 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2534 NTSTATUS status;
2535 HANDLE handle;
2536 OBJECT_ATTRIBUTES attr;
2537 CLIENT_ID cid;
2539 cid.UniqueProcess = ULongToHandle(id);
2540 cid.UniqueThread = 0; /* FIXME ? */
2542 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2543 attr.RootDirectory = NULL;
2544 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2545 attr.SecurityDescriptor = NULL;
2546 attr.SecurityQualityOfService = NULL;
2547 attr.ObjectName = NULL;
2549 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2551 status = NtOpenProcess(&handle, access, &attr, &cid);
2552 if (status != STATUS_SUCCESS)
2554 SetLastError( RtlNtStatusToDosError(status) );
2555 return NULL;
2557 return handle;
2561 /*********************************************************************
2562 * MapProcessHandle (KERNEL.483)
2563 * GetProcessId (KERNEL32.@)
2565 * Gets the a unique identifier of a process.
2567 * PARAMS
2568 * hProcess [I] Handle to the process.
2570 * RETURNS
2571 * Success: TRUE.
2572 * Failure: FALSE, check GetLastError().
2574 * NOTES
2576 * The identifier is unique only on the machine and only until the process
2577 * exits (including system shutdown).
2579 DWORD WINAPI GetProcessId( HANDLE hProcess )
2581 NTSTATUS status;
2582 PROCESS_BASIC_INFORMATION pbi;
2584 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2585 sizeof(pbi), NULL);
2586 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2587 SetLastError( RtlNtStatusToDosError(status) );
2588 return 0;
2592 /*********************************************************************
2593 * CloseW32Handle (KERNEL.474)
2594 * CloseHandle (KERNEL32.@)
2596 * Closes a handle.
2598 * PARAMS
2599 * handle [I] Handle to close.
2601 * RETURNS
2602 * Success: TRUE.
2603 * Failure: FALSE, check GetLastError().
2605 BOOL WINAPI CloseHandle( HANDLE handle )
2607 NTSTATUS status;
2609 /* stdio handles need special treatment */
2610 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2611 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2612 (handle == (HANDLE)STD_ERROR_HANDLE))
2613 handle = GetStdHandle( HandleToULong(handle) );
2615 if (is_console_handle(handle))
2616 return CloseConsoleHandle(handle);
2618 status = NtClose( handle );
2619 if (status) SetLastError( RtlNtStatusToDosError(status) );
2620 return !status;
2624 /*********************************************************************
2625 * GetHandleInformation (KERNEL32.@)
2627 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2629 OBJECT_DATA_INFORMATION info;
2630 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2632 if (status) SetLastError( RtlNtStatusToDosError(status) );
2633 else if (flags)
2635 *flags = 0;
2636 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2637 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2639 return !status;
2643 /*********************************************************************
2644 * SetHandleInformation (KERNEL32.@)
2646 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2648 OBJECT_DATA_INFORMATION info;
2649 NTSTATUS status;
2651 /* if not setting both fields, retrieve current value first */
2652 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2653 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2655 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2657 SetLastError( RtlNtStatusToDosError(status) );
2658 return FALSE;
2661 if (mask & HANDLE_FLAG_INHERIT)
2662 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2663 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2664 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2666 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2667 if (status) SetLastError( RtlNtStatusToDosError(status) );
2668 return !status;
2672 /*********************************************************************
2673 * DuplicateHandle (KERNEL32.@)
2675 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2676 HANDLE dest_process, HANDLE *dest,
2677 DWORD access, BOOL inherit, DWORD options )
2679 NTSTATUS status;
2681 if (is_console_handle(source))
2683 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2684 if (source_process != dest_process ||
2685 source_process != GetCurrentProcess())
2687 SetLastError(ERROR_INVALID_PARAMETER);
2688 return FALSE;
2690 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2691 return (*dest != INVALID_HANDLE_VALUE);
2693 status = NtDuplicateObject( source_process, source, dest_process, dest,
2694 access, inherit ? OBJ_INHERIT : 0, options );
2695 if (status) SetLastError( RtlNtStatusToDosError(status) );
2696 return !status;
2700 /***********************************************************************
2701 * ConvertToGlobalHandle (KERNEL.476)
2702 * ConvertToGlobalHandle (KERNEL32.@)
2704 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2706 HANDLE ret = INVALID_HANDLE_VALUE;
2707 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2708 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2709 return ret;
2713 /***********************************************************************
2714 * SetHandleContext (KERNEL32.@)
2716 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2718 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2719 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2720 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2721 return FALSE;
2725 /***********************************************************************
2726 * GetHandleContext (KERNEL32.@)
2728 DWORD WINAPI GetHandleContext(HANDLE hnd)
2730 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2731 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2732 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2733 return 0;
2737 /***********************************************************************
2738 * CreateSocketHandle (KERNEL32.@)
2740 HANDLE WINAPI CreateSocketHandle(void)
2742 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2743 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2744 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2745 return INVALID_HANDLE_VALUE;
2749 /***********************************************************************
2750 * SetPriorityClass (KERNEL32.@)
2752 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2754 NTSTATUS status;
2755 PROCESS_PRIORITY_CLASS ppc;
2757 ppc.Foreground = FALSE;
2758 switch (priorityclass)
2760 case IDLE_PRIORITY_CLASS:
2761 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2762 case BELOW_NORMAL_PRIORITY_CLASS:
2763 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2764 case NORMAL_PRIORITY_CLASS:
2765 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2766 case ABOVE_NORMAL_PRIORITY_CLASS:
2767 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2768 case HIGH_PRIORITY_CLASS:
2769 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2770 case REALTIME_PRIORITY_CLASS:
2771 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2772 default:
2773 SetLastError(ERROR_INVALID_PARAMETER);
2774 return FALSE;
2777 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2778 &ppc, sizeof(ppc));
2780 if (status != STATUS_SUCCESS)
2782 SetLastError( RtlNtStatusToDosError(status) );
2783 return FALSE;
2785 return TRUE;
2789 /***********************************************************************
2790 * GetPriorityClass (KERNEL32.@)
2792 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2794 NTSTATUS status;
2795 PROCESS_BASIC_INFORMATION pbi;
2797 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2798 sizeof(pbi), NULL);
2799 if (status != STATUS_SUCCESS)
2801 SetLastError( RtlNtStatusToDosError(status) );
2802 return 0;
2804 switch (pbi.BasePriority)
2806 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2807 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2808 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2809 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2810 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2811 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2813 SetLastError( ERROR_INVALID_PARAMETER );
2814 return 0;
2818 /***********************************************************************
2819 * SetProcessAffinityMask (KERNEL32.@)
2821 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2823 NTSTATUS status;
2825 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2826 &affmask, sizeof(DWORD_PTR));
2827 if (status)
2829 SetLastError( RtlNtStatusToDosError(status) );
2830 return FALSE;
2832 return TRUE;
2836 /**********************************************************************
2837 * GetProcessAffinityMask (KERNEL32.@)
2839 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2840 PDWORD_PTR lpProcessAffinityMask,
2841 PDWORD_PTR lpSystemAffinityMask )
2843 PROCESS_BASIC_INFORMATION pbi;
2844 NTSTATUS status;
2846 status = NtQueryInformationProcess(hProcess,
2847 ProcessBasicInformation,
2848 &pbi, sizeof(pbi), NULL);
2849 if (status)
2851 SetLastError( RtlNtStatusToDosError(status) );
2852 return FALSE;
2854 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2855 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2856 return TRUE;
2860 /***********************************************************************
2861 * GetProcessVersion (KERNEL32.@)
2863 DWORD WINAPI GetProcessVersion( DWORD pid )
2865 HANDLE process;
2866 NTSTATUS status;
2867 PROCESS_BASIC_INFORMATION pbi;
2868 SIZE_T count;
2869 PEB peb;
2870 IMAGE_DOS_HEADER dos;
2871 IMAGE_NT_HEADERS nt;
2872 DWORD ver = 0;
2874 if (!pid || pid == GetCurrentProcessId())
2876 IMAGE_NT_HEADERS *nt;
2878 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2879 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2880 nt->OptionalHeader.MinorSubsystemVersion);
2881 return 0;
2884 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2885 if (!process) return 0;
2887 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2888 if (status) goto err;
2890 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2891 if (status || count != sizeof(peb)) goto err;
2893 memset(&dos, 0, sizeof(dos));
2894 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2895 if (status || count != sizeof(dos)) goto err;
2896 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2898 memset(&nt, 0, sizeof(nt));
2899 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2900 if (status || count != sizeof(nt)) goto err;
2901 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2903 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2905 err:
2906 CloseHandle(process);
2908 if (status != STATUS_SUCCESS)
2909 SetLastError(RtlNtStatusToDosError(status));
2911 return ver;
2915 /***********************************************************************
2916 * SetProcessWorkingSetSize [KERNEL32.@]
2917 * Sets the min/max working set sizes for a specified process.
2919 * PARAMS
2920 * hProcess [I] Handle to the process of interest
2921 * minset [I] Specifies minimum working set size
2922 * maxset [I] Specifies maximum working set size
2924 * RETURNS
2925 * Success: TRUE
2926 * Failure: FALSE
2928 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2929 SIZE_T maxset)
2931 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2932 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2933 /* Trim the working set to zero */
2934 /* Swap the process out of physical RAM */
2936 return TRUE;
2939 /***********************************************************************
2940 * GetProcessWorkingSetSize (KERNEL32.@)
2942 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2943 PSIZE_T maxset)
2945 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2946 /* 32 MB working set size */
2947 if (minset) *minset = 32*1024*1024;
2948 if (maxset) *maxset = 32*1024*1024;
2949 return TRUE;
2953 /***********************************************************************
2954 * SetProcessShutdownParameters (KERNEL32.@)
2956 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2958 FIXME("(%08x, %08x): partial stub.\n", level, flags);
2959 shutdown_flags = flags;
2960 shutdown_priority = level;
2961 return TRUE;
2965 /***********************************************************************
2966 * GetProcessShutdownParameters (KERNEL32.@)
2969 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2971 *lpdwLevel = shutdown_priority;
2972 *lpdwFlags = shutdown_flags;
2973 return TRUE;
2977 /***********************************************************************
2978 * GetProcessPriorityBoost (KERNEL32.@)
2980 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2982 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2984 /* Report that no boost is present.. */
2985 *pDisablePriorityBoost = FALSE;
2987 return TRUE;
2990 /***********************************************************************
2991 * SetProcessPriorityBoost (KERNEL32.@)
2993 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2995 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2996 /* Say we can do it. I doubt the program will notice that we don't. */
2997 return TRUE;
3001 /***********************************************************************
3002 * ReadProcessMemory (KERNEL32.@)
3004 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3005 SIZE_T *bytes_read )
3007 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3008 if (status) SetLastError( RtlNtStatusToDosError(status) );
3009 return !status;
3013 /***********************************************************************
3014 * WriteProcessMemory (KERNEL32.@)
3016 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3017 SIZE_T *bytes_written )
3019 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3020 if (status) SetLastError( RtlNtStatusToDosError(status) );
3021 return !status;
3025 /****************************************************************************
3026 * FlushInstructionCache (KERNEL32.@)
3028 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3030 NTSTATUS status;
3031 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3032 if (status) SetLastError( RtlNtStatusToDosError(status) );
3033 return !status;
3037 /******************************************************************
3038 * GetProcessIoCounters (KERNEL32.@)
3040 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3042 NTSTATUS status;
3044 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3045 ioc, sizeof(*ioc), NULL);
3046 if (status) SetLastError( RtlNtStatusToDosError(status) );
3047 return !status;
3050 /******************************************************************
3051 * GetProcessHandleCount (KERNEL32.@)
3053 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3055 NTSTATUS status;
3057 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3058 cnt, sizeof(*cnt), NULL);
3059 if (status) SetLastError( RtlNtStatusToDosError(status) );
3060 return !status;
3063 /***********************************************************************
3064 * ProcessIdToSessionId (KERNEL32.@)
3065 * This function is available on Terminal Server 4SP4 and Windows 2000
3067 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3069 /* According to MSDN, if the calling process is not in a terminal
3070 * services environment, then the sessionid returned is zero.
3072 *sessionid_ptr = 0;
3073 return TRUE;
3077 /***********************************************************************
3078 * RegisterServiceProcess (KERNEL.491)
3079 * RegisterServiceProcess (KERNEL32.@)
3081 * A service process calls this function to ensure that it continues to run
3082 * even after a user logged off.
3084 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3086 /* I don't think that Wine needs to do anything in this function */
3087 return 1; /* success */
3091 /**********************************************************************
3092 * IsWow64Process (KERNEL32.@)
3094 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3096 ULONG pbi;
3097 NTSTATUS status;
3099 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3101 if (status != STATUS_SUCCESS)
3103 SetLastError( RtlNtStatusToDosError( status ) );
3104 return FALSE;
3106 *Wow64Process = (pbi != 0);
3107 return TRUE;
3111 /***********************************************************************
3112 * GetCurrentProcess (KERNEL32.@)
3114 * Get a handle to the current process.
3116 * PARAMS
3117 * None.
3119 * RETURNS
3120 * A handle representing the current process.
3122 #undef GetCurrentProcess
3123 HANDLE WINAPI GetCurrentProcess(void)
3125 return (HANDLE)0xffffffff;
3128 /***********************************************************************
3129 * CmdBatNotification (KERNEL32.@)
3131 * Notifies the system that a batch file has started or finished.
3133 * PARAMS
3134 * bBatchRunning [I] TRUE if a batch file has started or
3135 * FALSE if a batch file has finished executing.
3137 * RETURNS
3138 * Unknown.
3140 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3142 FIXME("%d\n", bBatchRunning);
3143 return FALSE;
3147 /***********************************************************************
3148 * RegisterApplicationRestart (KERNEL32.@)
3150 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3152 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3154 return S_OK;