kernel32: Print a nicer error message when 16-bit/DOS apps cannot be launched.
[wine/multimedia.git] / dlls / kernel32 / process.c
blob405bfc7d5b5893a34daa934d1f4145f2bcfe7158
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 );
498 else WARN( "user name %s not convertible.\n", debugstr_a(name) );
500 /* set the USERPROFILE and ALLUSERSPROFILE variables */
502 attr.Length = sizeof(attr);
503 attr.RootDirectory = 0;
504 attr.ObjectName = &nameW;
505 attr.Attributes = 0;
506 attr.SecurityDescriptor = NULL;
507 attr.SecurityQualityOfService = NULL;
508 RtlInitUnicodeString( &nameW, profile_keyW );
509 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
511 profile_dir = get_reg_value( hkey, profiles_valueW );
512 all_users_dir = get_reg_value( hkey, all_users_valueW );
513 NtClose( hkey );
516 if (profile_dir)
518 WCHAR *value, *p;
520 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
521 len += strlenW(profile_dir) + 1;
522 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
523 strcpyW( value, profile_dir );
524 p = value + strlenW(value);
525 if (p > value && p[-1] != '\\') *p++ = '\\';
526 if (user_name) {
527 strcpyW( p, user_name );
528 SetEnvironmentVariableW( userprofileW, value );
530 if (all_users_dir)
532 strcpyW( p, all_users_dir );
533 SetEnvironmentVariableW( allusersW, value );
535 HeapFree( GetProcessHeap(), 0, value );
538 HeapFree( GetProcessHeap(), 0, all_users_dir );
539 HeapFree( GetProcessHeap(), 0, profile_dir );
540 HeapFree( GetProcessHeap(), 0, user_name );
543 /***********************************************************************
544 * set_library_wargv
546 * Set the Wine library Unicode argv global variables.
548 static void set_library_wargv( char **argv )
550 int argc;
551 char *q;
552 WCHAR *p;
553 WCHAR **wargv;
554 DWORD total = 0;
556 for (argc = 0; argv[argc]; argc++)
557 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
559 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
560 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
561 p = (WCHAR *)(wargv + argc + 1);
562 for (argc = 0; argv[argc]; argc++)
564 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
565 wargv[argc] = p;
566 p += reslen;
567 total -= reslen;
569 wargv[argc] = NULL;
571 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
573 for (argc = 0; wargv[argc]; argc++)
574 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
576 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
577 q = (char *)(argv + argc + 1);
578 for (argc = 0; wargv[argc]; argc++)
580 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
581 argv[argc] = q;
582 q += reslen;
583 total -= reslen;
585 argv[argc] = NULL;
587 __wine_main_argc = argc;
588 __wine_main_argv = argv;
589 __wine_main_wargv = wargv;
593 /***********************************************************************
594 * build_command_line
596 * Build the command line of a process from the argv array.
598 * Note that it does NOT necessarily include the file name.
599 * Sometimes we don't even have any command line options at all.
601 * We must quote and escape characters so that the argv array can be rebuilt
602 * from the command line:
603 * - spaces and tabs must be quoted
604 * 'a b' -> '"a b"'
605 * - quotes must be escaped
606 * '"' -> '\"'
607 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
608 * resulting in an odd number of '\' followed by a '"'
609 * '\"' -> '\\\"'
610 * '\\"' -> '\\\\\"'
611 * - '\'s that are not followed by a '"' can be left as is
612 * 'a\b' == 'a\b'
613 * 'a\\b' == 'a\\b'
615 static BOOL build_command_line( WCHAR **argv )
617 int len;
618 WCHAR **arg;
619 LPWSTR p;
620 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
622 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
624 len = 0;
625 for (arg = argv; *arg; arg++)
627 int has_space,bcount;
628 WCHAR* a;
630 has_space=0;
631 bcount=0;
632 a=*arg;
633 if( !*a ) has_space=1;
634 while (*a!='\0') {
635 if (*a=='\\') {
636 bcount++;
637 } else {
638 if (*a==' ' || *a=='\t') {
639 has_space=1;
640 } else if (*a=='"') {
641 /* doubling of '\' preceding a '"',
642 * plus escaping of said '"'
644 len+=2*bcount+1;
646 bcount=0;
648 a++;
650 len+=(a-*arg)+1 /* for the separating space */;
651 if (has_space)
652 len+=2; /* for the quotes */
655 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
656 return FALSE;
658 p = rupp->CommandLine.Buffer;
659 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
660 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
661 for (arg = argv; *arg; arg++)
663 int has_space,has_quote;
664 WCHAR* a;
666 /* Check for quotes and spaces in this argument */
667 has_space=has_quote=0;
668 a=*arg;
669 if( !*a ) has_space=1;
670 while (*a!='\0') {
671 if (*a==' ' || *a=='\t') {
672 has_space=1;
673 if (has_quote)
674 break;
675 } else if (*a=='"') {
676 has_quote=1;
677 if (has_space)
678 break;
680 a++;
683 /* Now transfer it to the command line */
684 if (has_space)
685 *p++='"';
686 if (has_quote) {
687 int bcount;
688 WCHAR* a;
690 bcount=0;
691 a=*arg;
692 while (*a!='\0') {
693 if (*a=='\\') {
694 *p++=*a;
695 bcount++;
696 } else {
697 if (*a=='"') {
698 int i;
700 /* Double all the '\\' preceding this '"', plus one */
701 for (i=0;i<=bcount;i++)
702 *p++='\\';
703 *p++='"';
704 } else {
705 *p++=*a;
707 bcount=0;
709 a++;
711 } else {
712 WCHAR* x = *arg;
713 while ((*p=*x++)) p++;
715 if (has_space)
716 *p++='"';
717 *p++=' ';
719 if (p > rupp->CommandLine.Buffer)
720 p--; /* remove last space */
721 *p = '\0';
723 return TRUE;
727 /***********************************************************************
728 * init_current_directory
730 * Initialize the current directory from the Unix cwd or the parent info.
732 static void init_current_directory( CURDIR *cur_dir )
734 UNICODE_STRING dir_str;
735 char *cwd;
736 int size;
738 /* if we received a cur dir from the parent, try this first */
740 if (cur_dir->DosPath.Length)
742 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
745 /* now try to get it from the Unix cwd */
747 for (size = 256; ; size *= 2)
749 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
750 if (getcwd( cwd, size )) break;
751 HeapFree( GetProcessHeap(), 0, cwd );
752 if (errno == ERANGE) continue;
753 cwd = NULL;
754 break;
757 if (cwd)
759 WCHAR *dirW;
760 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
761 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
763 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
764 RtlInitUnicodeString( &dir_str, dirW );
765 RtlSetCurrentDirectory_U( &dir_str );
766 RtlFreeUnicodeString( &dir_str );
770 if (!cur_dir->DosPath.Length) /* still not initialized */
772 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
773 "starting in the Windows directory.\n", cwd ? cwd : "" );
774 RtlInitUnicodeString( &dir_str, DIR_Windows );
775 RtlSetCurrentDirectory_U( &dir_str );
777 HeapFree( GetProcessHeap(), 0, cwd );
779 done:
780 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
781 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
785 /***********************************************************************
786 * init_windows_dirs
788 * Initialize the windows and system directories from the environment.
790 static void init_windows_dirs(void)
792 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
794 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
795 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
796 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
797 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
799 DWORD len;
800 WCHAR *buffer;
802 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
804 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
805 GetEnvironmentVariableW( windirW, buffer, len );
806 DIR_Windows = buffer;
808 else DIR_Windows = default_windirW;
810 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
812 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
813 GetEnvironmentVariableW( winsysdirW, buffer, len );
814 DIR_System = buffer;
816 else
818 len = strlenW( DIR_Windows );
819 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
820 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
821 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
822 DIR_System = buffer;
825 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
826 ERR( "directory %s could not be created, error %u\n",
827 debugstr_w(DIR_Windows), GetLastError() );
828 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
829 ERR( "directory %s could not be created, error %u\n",
830 debugstr_w(DIR_System), GetLastError() );
832 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
833 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
835 /* set the directories in ntdll too */
836 __wine_init_windows_dir( DIR_Windows, DIR_System );
840 /***********************************************************************
841 * start_wineboot
843 * Start the wineboot process if necessary. Return the event to wait on.
845 static HANDLE start_wineboot(void)
847 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
848 HANDLE event;
850 if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
852 ERR( "failed to create wineboot event, expect trouble\n" );
853 return 0;
855 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
857 static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
858 STARTUPINFOW si;
859 PROCESS_INFORMATION pi;
860 WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];
862 memset( &si, 0, sizeof(si) );
863 si.cb = sizeof(si);
864 si.dwFlags = STARTF_USESTDHANDLES;
865 si.hStdInput = 0;
866 si.hStdOutput = 0;
867 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
869 GetSystemDirectoryW( cmdline, MAX_PATH );
870 lstrcatW( cmdline, command_line );
871 if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
873 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
874 CloseHandle( pi.hThread );
875 CloseHandle( pi.hProcess );
878 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
880 return event;
884 /***********************************************************************
885 * start_process
887 * Startup routine of a new process. Runs on the new process stack.
889 static void start_process( void *arg )
891 __TRY
893 PEB *peb = NtCurrentTeb()->Peb;
894 IMAGE_NT_HEADERS *nt;
895 LPTHREAD_START_ROUTINE entry;
897 nt = RtlImageNtHeader( peb->ImageBaseAddress );
898 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
899 nt->OptionalHeader.AddressOfEntryPoint);
901 if (TRACE_ON(relay))
902 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
903 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
905 SetLastError( 0 ); /* clear error code */
906 if (peb->BeingDebugged) DbgBreakPoint();
907 ExitThread( entry( peb ) );
909 __EXCEPT(UnhandledExceptionFilter)
911 TerminateThread( GetCurrentThread(), GetExceptionCode() );
913 __ENDTRY
917 /***********************************************************************
918 * set_process_name
920 * Change the process name in the ps output.
922 static void set_process_name( int argc, char *argv[] )
924 #ifdef HAVE_SETPROCTITLE
925 setproctitle("-%s", argv[1]);
926 #endif
928 #ifdef HAVE_PRCTL
929 int i, offset;
930 char *p, *prctl_name = argv[1];
931 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
933 #ifndef PR_SET_NAME
934 # define PR_SET_NAME 15
935 #endif
937 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
938 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
940 if (prctl( PR_SET_NAME, prctl_name ) != -1)
942 offset = argv[1] - argv[0];
943 memmove( argv[1] - offset, argv[1], end - argv[1] );
944 memset( end - offset, 0, offset );
945 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
946 argv[i-1] = NULL;
948 else
949 #endif /* HAVE_PRCTL */
951 /* remove argv[0] */
952 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
957 /***********************************************************************
958 * __wine_kernel_init
960 * Wine initialisation: load and start the main exe file.
962 void CDECL __wine_kernel_init(void)
964 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
965 static const WCHAR dotW[] = {'.',0};
966 static const WCHAR exeW[] = {'.','e','x','e',0};
968 WCHAR *p, main_exe_name[MAX_PATH+1];
969 PEB *peb = NtCurrentTeb()->Peb;
970 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
971 HANDLE boot_event = 0;
972 BOOL got_environment = TRUE;
974 /* Initialize everything */
976 setbuf(stdout,NULL);
977 setbuf(stderr,NULL);
978 kernel32_handle = GetModuleHandleW(kernel32W);
980 LOCALE_Init();
982 if (!params->Environment)
984 /* Copy the parent environment */
985 if (!build_initial_environment( __wine_main_environ )) exit(1);
987 /* convert old configuration to new format */
988 convert_old_config();
990 got_environment = set_registry_environment();
991 set_additional_environment();
994 init_windows_dirs();
995 init_current_directory( &params->CurrentDirectory );
997 set_process_name( __wine_main_argc, __wine_main_argv );
998 set_library_wargv( __wine_main_argv );
1000 if (peb->ProcessParameters->ImagePathName.Buffer)
1002 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1004 else
1006 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1007 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1009 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1010 ExitProcess( GetLastError() );
1012 if (!build_command_line( __wine_main_wargv )) goto error;
1013 boot_event = start_wineboot();
1016 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1017 p = strrchrW( main_exe_name, '.' );
1018 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1020 TRACE( "starting process name=%s argv[0]=%s\n",
1021 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1023 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1024 MODULE_get_dll_load_path(main_exe_name) );
1026 if (boot_event)
1028 if (WaitForSingleObject( boot_event, 30000 )) ERR( "boot event wait timed out\n" );
1029 CloseHandle( boot_event );
1030 /* if we didn't find environment section, try again now that wineboot has run */
1031 if (!got_environment)
1033 set_registry_environment();
1034 set_additional_environment();
1038 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1040 char msg[1024];
1041 DWORD error = GetLastError();
1043 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1044 if (error == ERROR_BAD_EXE_FORMAT ||
1045 error == ERROR_INVALID_ADDRESS ||
1046 error == ERROR_NOT_ENOUGH_MEMORY)
1048 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1049 /* if we get back here, it failed */
1051 else if (error == ERROR_MOD_NOT_FOUND)
1053 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1054 else p = main_exe_name;
1055 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1057 /* args 1 and 2 are --app-name full_path */
1058 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1059 debugstr_w(__wine_main_wargv[3]) );
1060 ExitProcess( ERROR_BAD_EXE_FORMAT );
1063 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1064 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1065 ExitProcess( error );
1068 LdrInitializeThunk( 0, 0, 0, 0 );
1069 /* switch to the new stack */
1070 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1072 error:
1073 ExitProcess( GetLastError() );
1077 /***********************************************************************
1078 * build_argv
1080 * Build an argv array from a command-line.
1081 * 'reserved' is the number of args to reserve before the first one.
1083 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1085 int argc;
1086 char** argv;
1087 char *arg,*s,*d,*cmdline;
1088 int in_quotes,bcount,len;
1090 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1091 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1092 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1094 argc=reserved+1;
1095 bcount=0;
1096 in_quotes=0;
1097 s=cmdline;
1098 while (1) {
1099 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1100 /* space */
1101 argc++;
1102 /* skip the remaining spaces */
1103 while (*s==' ' || *s=='\t') {
1104 s++;
1106 if (*s=='\0')
1107 break;
1108 bcount=0;
1109 continue;
1110 } else if (*s=='\\') {
1111 /* '\', count them */
1112 bcount++;
1113 } else if ((*s=='"') && ((bcount & 1)==0)) {
1114 /* unescaped '"' */
1115 in_quotes=!in_quotes;
1116 bcount=0;
1117 } else {
1118 /* a regular character */
1119 bcount=0;
1121 s++;
1123 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1125 HeapFree( GetProcessHeap(), 0, cmdline );
1126 return NULL;
1129 arg = d = s = (char *)(argv + argc);
1130 memcpy( d, cmdline, len );
1131 bcount=0;
1132 in_quotes=0;
1133 argc=reserved;
1134 while (*s) {
1135 if ((*s==' ' || *s=='\t') && !in_quotes) {
1136 /* Close the argument and copy it */
1137 *d=0;
1138 argv[argc++]=arg;
1140 /* skip the remaining spaces */
1141 do {
1142 s++;
1143 } while (*s==' ' || *s=='\t');
1145 /* Start with a new argument */
1146 arg=d=s;
1147 bcount=0;
1148 } else if (*s=='\\') {
1149 /* '\\' */
1150 *d++=*s++;
1151 bcount++;
1152 } else if (*s=='"') {
1153 /* '"' */
1154 if ((bcount & 1)==0) {
1155 /* Preceded by an even number of '\', this is half that
1156 * number of '\', plus a '"' which we discard.
1158 d-=bcount/2;
1159 s++;
1160 in_quotes=!in_quotes;
1161 } else {
1162 /* Preceded by an odd number of '\', this is half that
1163 * number of '\' followed by a '"'
1165 d=d-bcount/2-1;
1166 *d++='"';
1167 s++;
1169 bcount=0;
1170 } else {
1171 /* a regular character */
1172 *d++=*s++;
1173 bcount=0;
1176 if (*arg) {
1177 *d='\0';
1178 argv[argc++]=arg;
1180 argv[argc]=NULL;
1182 HeapFree( GetProcessHeap(), 0, cmdline );
1183 return argv;
1187 /***********************************************************************
1188 * build_envp
1190 * Build the environment of a new child process.
1192 static char **build_envp( const WCHAR *envW )
1194 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1196 const WCHAR *end;
1197 char **envp;
1198 char *env, *p;
1199 int count = 1, length;
1200 unsigned int i;
1202 for (end = envW; *end; count++) end += strlenW(end) + 1;
1203 end++;
1204 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1205 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1206 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1208 for (p = env; *p; p += strlen(p) + 1)
1209 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1211 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1213 if (!(p = getenv(unix_vars[i]))) continue;
1214 length += strlen(unix_vars[i]) + strlen(p) + 2;
1215 count++;
1218 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1220 char **envptr = envp;
1221 char *dst = (char *)(envp + count);
1223 /* some variables must not be modified, so we get them directly from the unix env */
1224 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1226 if (!(p = getenv(unix_vars[i]))) continue;
1227 *envptr++ = strcpy( dst, unix_vars[i] );
1228 strcat( dst, "=" );
1229 strcat( dst, p );
1230 dst += strlen(dst) + 1;
1233 /* now put the Windows environment strings */
1234 for (p = env; *p; p += strlen(p) + 1)
1236 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1237 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1238 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1239 if (is_special_env_var( p )) /* prefix it with "WINE" */
1241 *envptr++ = strcpy( dst, "WINE" );
1242 strcat( dst, p );
1244 else
1246 *envptr++ = strcpy( dst, p );
1248 dst += strlen(dst) + 1;
1250 *envptr = 0;
1252 HeapFree( GetProcessHeap(), 0, env );
1253 return envp;
1257 /***********************************************************************
1258 * fork_and_exec
1260 * Fork and exec a new Unix binary, checking for errors.
1262 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1263 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1265 int fd[2], stdin_fd = -1, stdout_fd = -1;
1266 int pid, err;
1267 char **argv, **envp;
1269 if (!env) env = GetEnvironmentStringsW();
1271 if (pipe(fd) == -1)
1273 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1274 return -1;
1276 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1278 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1280 HANDLE hstdin, hstdout;
1282 if (startup->dwFlags & STARTF_USESTDHANDLES)
1284 hstdin = startup->hStdInput;
1285 hstdout = startup->hStdOutput;
1287 else
1289 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1290 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1293 if (is_console_handle( hstdin ))
1294 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1295 if (is_console_handle( hstdout ))
1296 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1297 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1298 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1301 argv = build_argv( cmdline, 0 );
1302 envp = build_envp( env );
1304 if (!(pid = fork())) /* child */
1306 close( fd[0] );
1308 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1310 int pid;
1311 if (!(pid = fork()))
1313 int fd = open( "/dev/null", O_RDWR );
1314 setsid();
1315 /* close stdin and stdout */
1316 if (fd != -1)
1318 dup2( fd, 0 );
1319 dup2( fd, 1 );
1320 close( fd );
1323 else if (pid != -1) _exit(0); /* parent */
1325 else
1327 if (stdin_fd != -1)
1329 dup2( stdin_fd, 0 );
1330 close( stdin_fd );
1332 if (stdout_fd != -1)
1334 dup2( stdout_fd, 1 );
1335 close( stdout_fd );
1339 /* Reset signals that we previously set to SIG_IGN */
1340 signal( SIGPIPE, SIG_DFL );
1341 signal( SIGCHLD, SIG_DFL );
1343 if (newdir) chdir(newdir);
1345 if (argv && envp) execve( filename, argv, envp );
1346 err = errno;
1347 write( fd[1], &err, sizeof(err) );
1348 _exit(1);
1350 HeapFree( GetProcessHeap(), 0, argv );
1351 HeapFree( GetProcessHeap(), 0, envp );
1352 if (stdin_fd != -1) close( stdin_fd );
1353 if (stdout_fd != -1) close( stdout_fd );
1354 close( fd[1] );
1355 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1357 errno = err;
1358 pid = -1;
1360 if (pid == -1) FILE_SetDosError();
1361 close( fd[0] );
1362 return pid;
1366 /***********************************************************************
1367 * create_user_params
1369 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1370 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1371 const STARTUPINFOW *startup )
1373 RTL_USER_PROCESS_PARAMETERS *params;
1374 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1375 NTSTATUS status;
1376 WCHAR buffer[MAX_PATH];
1378 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1379 lstrcpynW( buffer, filename, MAX_PATH );
1380 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1381 lstrcpynW( buffer, filename, MAX_PATH );
1382 RtlInitUnicodeString( &image_str, buffer );
1384 RtlInitUnicodeString( &cmdline_str, cmdline );
1385 newdir.Buffer = NULL;
1386 if (cur_dir)
1388 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1390 /* skip \??\ prefix */
1391 curdir_str.Buffer = newdir.Buffer + 4;
1392 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1393 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1395 else cur_dir = NULL;
1397 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1398 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1399 if (startup->lpReserved2 && startup->cbReserved2)
1401 runtime.Length = 0;
1402 runtime.MaximumLength = startup->cbReserved2;
1403 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1406 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1407 cur_dir ? &curdir_str : NULL,
1408 &cmdline_str, env,
1409 startup->lpTitle ? &title : NULL,
1410 startup->lpDesktop ? &desktop : NULL,
1411 NULL,
1412 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1413 RtlFreeUnicodeString( &newdir );
1414 if (status != STATUS_SUCCESS)
1416 SetLastError( RtlNtStatusToDosError(status) );
1417 return NULL;
1420 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1421 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1423 if (startup->dwFlags & STARTF_USESTDHANDLES)
1425 params->hStdInput = startup->hStdInput;
1426 params->hStdOutput = startup->hStdOutput;
1427 params->hStdError = startup->hStdError;
1429 else
1431 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1432 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1433 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1435 params->dwX = startup->dwX;
1436 params->dwY = startup->dwY;
1437 params->dwXSize = startup->dwXSize;
1438 params->dwYSize = startup->dwYSize;
1439 params->dwXCountChars = startup->dwXCountChars;
1440 params->dwYCountChars = startup->dwYCountChars;
1441 params->dwFillAttribute = startup->dwFillAttribute;
1442 params->dwFlags = startup->dwFlags;
1443 params->wShowWindow = startup->wShowWindow;
1444 return params;
1448 /***********************************************************************
1449 * create_process
1451 * Create a new process. If hFile is a valid handle we have an exe
1452 * file, otherwise it is a Winelib app.
1454 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1455 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1456 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1457 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1458 void *res_start, void *res_end, int exec_only )
1460 BOOL ret, success = FALSE;
1461 HANDLE process_info, hstdin, hstdout;
1462 WCHAR *env_end;
1463 char *winedebug = NULL;
1464 char **argv;
1465 RTL_USER_PROCESS_PARAMETERS *params;
1466 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1467 pid_t pid;
1468 int err;
1470 if (!env) RtlAcquirePebLock();
1472 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1474 if (!env) RtlReleasePebLock();
1475 return FALSE;
1477 env_end = params->Environment;
1478 while (*env_end)
1480 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1481 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1483 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1484 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1485 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1487 env_end += strlenW(env_end) + 1;
1489 env_end++;
1491 /* create the socket for the new process */
1493 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1495 if (!env) RtlReleasePebLock();
1496 HeapFree( GetProcessHeap(), 0, winedebug );
1497 RtlDestroyProcessParameters( params );
1498 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1499 return FALSE;
1501 wine_server_send_fd( socketfd[1] );
1502 close( socketfd[1] );
1504 /* create the process on the server side */
1506 SERVER_START_REQ( new_process )
1508 req->inherit_all = inherit;
1509 req->create_flags = flags;
1510 req->socket_fd = socketfd[1];
1511 req->exe_file = wine_server_obj_handle( hFile );
1512 req->process_access = PROCESS_ALL_ACCESS;
1513 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1514 req->thread_access = THREAD_ALL_ACCESS;
1515 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1516 req->hstdin = wine_server_obj_handle( params->hStdInput );
1517 req->hstdout = wine_server_obj_handle( params->hStdOutput );
1518 req->hstderr = wine_server_obj_handle( params->hStdError );
1520 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1522 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1523 if (is_console_handle(params->hStdInput)) req->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1524 if (is_console_handle(params->hStdOutput)) req->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1525 if (is_console_handle(params->hStdError)) req->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1526 hstdin = hstdout = 0;
1528 else
1530 if (is_console_handle(params->hStdInput)) req->hstdin = console_handle_unmap(params->hStdInput);
1531 if (is_console_handle(params->hStdOutput)) req->hstdout = console_handle_unmap(params->hStdOutput);
1532 if (is_console_handle(params->hStdError)) req->hstderr = console_handle_unmap(params->hStdError);
1533 hstdin = wine_server_ptr_handle( req->hstdin );
1534 hstdout = wine_server_ptr_handle( req->hstdout );
1537 wine_server_add_data( req, params, params->Size );
1538 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1539 if ((ret = !wine_server_call_err( req )))
1541 info->dwProcessId = (DWORD)reply->pid;
1542 info->dwThreadId = (DWORD)reply->tid;
1543 info->hProcess = wine_server_ptr_handle( reply->phandle );
1544 info->hThread = wine_server_ptr_handle( reply->thandle );
1546 process_info = wine_server_ptr_handle( reply->info );
1548 SERVER_END_REQ;
1550 if (!env) RtlReleasePebLock();
1551 RtlDestroyProcessParameters( params );
1552 if (!ret)
1554 close( socketfd[0] );
1555 HeapFree( GetProcessHeap(), 0, winedebug );
1556 return FALSE;
1559 if (hstdin) wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1560 if (hstdout) wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1562 /* create the child process */
1563 argv = build_argv( cmd_line, 1 );
1565 if (exec_only || !(pid = fork())) /* child */
1567 char preloader_reserve[64], socket_env[64];
1569 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1571 if (!(pid = fork()))
1573 int fd = open( "/dev/null", O_RDWR );
1574 setsid();
1575 /* close stdin and stdout */
1576 if (fd != -1)
1578 dup2( fd, 0 );
1579 dup2( fd, 1 );
1580 close( fd );
1583 else if (pid != -1) _exit(0); /* parent */
1585 else
1587 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1588 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1591 if (stdin_fd != -1) close( stdin_fd );
1592 if (stdout_fd != -1) close( stdout_fd );
1594 /* Reset signals that we previously set to SIG_IGN */
1595 signal( SIGPIPE, SIG_DFL );
1596 signal( SIGCHLD, SIG_DFL );
1598 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1599 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1600 (unsigned long)res_start, (unsigned long)res_end );
1602 putenv( preloader_reserve );
1603 putenv( socket_env );
1604 if (winedebug) putenv( winedebug );
1605 if (unixdir) chdir(unixdir);
1607 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1608 _exit(1);
1611 /* this is the parent */
1613 if (stdin_fd != -1) close( stdin_fd );
1614 if (stdout_fd != -1) close( stdout_fd );
1615 close( socketfd[0] );
1616 HeapFree( GetProcessHeap(), 0, argv );
1617 HeapFree( GetProcessHeap(), 0, winedebug );
1618 if (pid == -1)
1620 FILE_SetDosError();
1621 goto error;
1624 /* wait for the new process info to be ready */
1626 WaitForSingleObject( process_info, INFINITE );
1627 SERVER_START_REQ( get_new_process_info )
1629 req->info = wine_server_obj_handle( process_info );
1630 wine_server_call( req );
1631 success = reply->success;
1632 err = reply->exit_code;
1634 SERVER_END_REQ;
1636 if (!success)
1638 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1639 goto error;
1641 CloseHandle( process_info );
1642 return success;
1644 error:
1645 CloseHandle( process_info );
1646 CloseHandle( info->hProcess );
1647 CloseHandle( info->hThread );
1648 info->hProcess = info->hThread = 0;
1649 info->dwProcessId = info->dwThreadId = 0;
1650 return FALSE;
1654 /***********************************************************************
1655 * create_vdm_process
1657 * Create a new VDM process for a 16-bit or DOS application.
1659 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1660 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1661 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1662 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1664 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1666 BOOL ret;
1667 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1668 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1670 if (!new_cmd_line)
1672 SetLastError( ERROR_OUTOFMEMORY );
1673 return FALSE;
1675 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1676 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1677 flags, startup, info, unixdir, NULL, NULL, exec_only );
1678 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1679 return ret;
1683 /***********************************************************************
1684 * create_cmd_process
1686 * Create a new cmd shell process for a .BAT file.
1688 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1689 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1690 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1691 LPPROCESS_INFORMATION info )
1694 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1695 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1696 WCHAR comspec[MAX_PATH];
1697 WCHAR *newcmdline;
1698 BOOL ret;
1700 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1701 return FALSE;
1702 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1703 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1704 return FALSE;
1706 strcpyW( newcmdline, comspec );
1707 strcatW( newcmdline, slashcW );
1708 strcatW( newcmdline, cmd_line );
1709 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1710 flags, env, cur_dir, startup, info );
1711 HeapFree( GetProcessHeap(), 0, newcmdline );
1712 return ret;
1716 /*************************************************************************
1717 * get_file_name
1719 * Helper for CreateProcess: retrieve the file name to load from the
1720 * app name and command line. Store the file name in buffer, and
1721 * return a possibly modified command line.
1722 * Also returns a handle to the opened file if it's a Windows binary.
1724 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1725 int buflen, HANDLE *handle )
1727 static const WCHAR quotesW[] = {'"','%','s','"',0};
1729 WCHAR *name, *pos, *ret = NULL;
1730 const WCHAR *p;
1731 BOOL got_space;
1733 /* if we have an app name, everything is easy */
1735 if (appname)
1737 /* use the unmodified app name as file name */
1738 lstrcpynW( buffer, appname, buflen );
1739 *handle = open_exe_file( buffer );
1740 if (!(ret = cmdline) || !cmdline[0])
1742 /* no command-line, create one */
1743 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1744 sprintfW( ret, quotesW, appname );
1746 return ret;
1749 if (!cmdline)
1751 SetLastError( ERROR_INVALID_PARAMETER );
1752 return NULL;
1755 /* first check for a quoted file name */
1757 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1759 int len = p - cmdline - 1;
1760 /* extract the quoted portion as file name */
1761 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1762 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1763 name[len] = 0;
1765 if (find_exe_file( name, buffer, buflen, handle ))
1766 ret = cmdline; /* no change necessary */
1767 goto done;
1770 /* now try the command-line word by word */
1772 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1773 return NULL;
1774 pos = name;
1775 p = cmdline;
1776 got_space = FALSE;
1778 while (*p)
1780 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1781 *pos = 0;
1782 if (find_exe_file( name, buffer, buflen, handle ))
1784 ret = cmdline;
1785 break;
1787 if (*p) got_space = TRUE;
1790 if (ret && got_space) /* now build a new command-line with quotes */
1792 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1793 goto done;
1794 sprintfW( ret, quotesW, name );
1795 strcatW( ret, p );
1798 done:
1799 HeapFree( GetProcessHeap(), 0, name );
1800 return ret;
1804 /**********************************************************************
1805 * CreateProcessA (KERNEL32.@)
1807 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1808 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1809 DWORD flags, LPVOID env, LPCSTR cur_dir,
1810 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1812 BOOL ret = FALSE;
1813 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1814 UNICODE_STRING desktopW, titleW;
1815 STARTUPINFOW infoW;
1817 desktopW.Buffer = NULL;
1818 titleW.Buffer = NULL;
1819 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1820 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1821 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1823 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1824 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1826 memcpy( &infoW, startup_info, sizeof(infoW) );
1827 infoW.lpDesktop = desktopW.Buffer;
1828 infoW.lpTitle = titleW.Buffer;
1830 if (startup_info->lpReserved)
1831 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1832 debugstr_a(startup_info->lpReserved));
1834 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1835 inherit, flags, env, cur_dirW, &infoW, info );
1836 done:
1837 HeapFree( GetProcessHeap(), 0, app_nameW );
1838 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1839 HeapFree( GetProcessHeap(), 0, cur_dirW );
1840 RtlFreeUnicodeString( &desktopW );
1841 RtlFreeUnicodeString( &titleW );
1842 return ret;
1846 /**********************************************************************
1847 * CreateProcessW (KERNEL32.@)
1849 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1850 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1851 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1852 LPPROCESS_INFORMATION info )
1854 BOOL retv = FALSE;
1855 HANDLE hFile = 0;
1856 char *unixdir = NULL;
1857 WCHAR name[MAX_PATH];
1858 WCHAR *tidy_cmdline, *p, *envW = env;
1859 void *res_start, *res_end;
1861 /* Process the AppName and/or CmdLine to get module name and path */
1863 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1865 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1866 return FALSE;
1867 if (hFile == INVALID_HANDLE_VALUE) goto done;
1869 /* Warn if unsupported features are used */
1871 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1872 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1873 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1874 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1875 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1877 if (cur_dir)
1879 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1881 SetLastError(ERROR_DIRECTORY);
1882 goto done;
1885 else
1887 WCHAR buf[MAX_PATH];
1888 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1891 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1893 char *p = env;
1894 DWORD lenW;
1896 while (*p) p += strlen(p) + 1;
1897 p++; /* final null */
1898 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1899 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1900 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1901 flags |= CREATE_UNICODE_ENVIRONMENT;
1904 info->hThread = info->hProcess = 0;
1905 info->dwProcessId = info->dwThreadId = 0;
1907 /* Determine executable type */
1909 if (!hFile) /* builtin exe */
1911 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1912 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1913 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1914 goto done;
1917 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1919 case BINARY_PE_EXE:
1920 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1921 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1922 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1923 break;
1924 case BINARY_OS216:
1925 case BINARY_WIN16:
1926 case BINARY_DOS:
1927 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1928 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1929 inherit, flags, startup_info, info, unixdir, FALSE );
1930 break;
1931 case BINARY_PE_DLL:
1932 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1933 SetLastError( ERROR_BAD_EXE_FORMAT );
1934 break;
1935 case BINARY_UNIX_LIB:
1936 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1937 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1938 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1939 break;
1940 case BINARY_UNKNOWN:
1941 /* check for .com or .bat extension */
1942 if ((p = strrchrW( name, '.' )))
1944 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1946 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1947 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1948 inherit, flags, startup_info, info, unixdir, FALSE );
1949 break;
1951 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1953 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1954 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1955 inherit, flags, startup_info, info );
1956 break;
1959 /* fall through */
1960 case BINARY_UNIX_EXE:
1962 /* unknown file, try as unix executable */
1963 char *unix_name;
1965 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1967 if ((unix_name = wine_get_unix_file_name( name )))
1969 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
1970 HeapFree( GetProcessHeap(), 0, unix_name );
1973 break;
1975 CloseHandle( hFile );
1977 done:
1978 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1979 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1980 HeapFree( GetProcessHeap(), 0, unixdir );
1981 if (retv)
1982 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
1983 return retv;
1987 /**********************************************************************
1988 * exec_process
1990 static void exec_process( LPCWSTR name )
1992 HANDLE hFile;
1993 WCHAR *p;
1994 void *res_start, *res_end;
1995 STARTUPINFOW startup_info;
1996 PROCESS_INFORMATION info;
1998 hFile = open_exe_file( name );
1999 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2001 memset( &startup_info, 0, sizeof(startup_info) );
2002 startup_info.cb = sizeof(startup_info);
2004 /* Determine executable type */
2006 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
2008 case BINARY_PE_EXE:
2009 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
2010 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2011 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
2012 break;
2013 case BINARY_UNIX_LIB:
2014 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2015 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2016 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
2017 break;
2018 case BINARY_UNKNOWN:
2019 /* check for .com or .pif extension */
2020 if (!(p = strrchrW( name, '.' ))) break;
2021 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2022 /* fall through */
2023 case BINARY_OS216:
2024 case BINARY_WIN16:
2025 case BINARY_DOS:
2026 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2027 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2028 FALSE, 0, &startup_info, &info, NULL, TRUE );
2029 break;
2030 default:
2031 break;
2033 CloseHandle( hFile );
2037 /***********************************************************************
2038 * wait_input_idle
2040 * Wrapper to call WaitForInputIdle USER function
2042 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2044 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2046 HMODULE mod = GetModuleHandleA( "user32.dll" );
2047 if (mod)
2049 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2050 if (ptr) return ptr( process, timeout );
2052 return 0;
2056 /***********************************************************************
2057 * WinExec (KERNEL32.@)
2059 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2061 PROCESS_INFORMATION info;
2062 STARTUPINFOA startup;
2063 char *cmdline;
2064 UINT ret;
2066 memset( &startup, 0, sizeof(startup) );
2067 startup.cb = sizeof(startup);
2068 startup.dwFlags = STARTF_USESHOWWINDOW;
2069 startup.wShowWindow = nCmdShow;
2071 /* cmdline needs to be writable for CreateProcess */
2072 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2073 strcpy( cmdline, lpCmdLine );
2075 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2076 0, NULL, NULL, &startup, &info ))
2078 /* Give 30 seconds to the app to come up */
2079 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2080 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2081 ret = 33;
2082 /* Close off the handles */
2083 CloseHandle( info.hThread );
2084 CloseHandle( info.hProcess );
2086 else if ((ret = GetLastError()) >= 32)
2088 FIXME("Strange error set by CreateProcess: %d\n", ret );
2089 ret = 11;
2091 HeapFree( GetProcessHeap(), 0, cmdline );
2092 return ret;
2096 /**********************************************************************
2097 * LoadModule (KERNEL32.@)
2099 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2101 LOADPARMS32 *params = paramBlock;
2102 PROCESS_INFORMATION info;
2103 STARTUPINFOA startup;
2104 HINSTANCE hInstance;
2105 LPSTR cmdline, p;
2106 char filename[MAX_PATH];
2107 BYTE len;
2109 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2111 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2112 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2113 return ULongToHandle(GetLastError());
2115 len = (BYTE)params->lpCmdLine[0];
2116 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2117 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2119 strcpy( cmdline, filename );
2120 p = cmdline + strlen(cmdline);
2121 *p++ = ' ';
2122 memcpy( p, params->lpCmdLine + 1, len );
2123 p[len] = 0;
2125 memset( &startup, 0, sizeof(startup) );
2126 startup.cb = sizeof(startup);
2127 if (params->lpCmdShow)
2129 startup.dwFlags = STARTF_USESHOWWINDOW;
2130 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2133 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2134 params->lpEnvAddress, NULL, &startup, &info ))
2136 /* Give 30 seconds to the app to come up */
2137 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2138 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2139 hInstance = (HINSTANCE)33;
2140 /* Close off the handles */
2141 CloseHandle( info.hThread );
2142 CloseHandle( info.hProcess );
2144 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2146 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2147 hInstance = (HINSTANCE)11;
2150 HeapFree( GetProcessHeap(), 0, cmdline );
2151 return hInstance;
2155 /******************************************************************************
2156 * TerminateProcess (KERNEL32.@)
2158 * Terminates a process.
2160 * PARAMS
2161 * handle [I] Process to terminate.
2162 * exit_code [I] Exit code.
2164 * RETURNS
2165 * Success: TRUE.
2166 * Failure: FALSE, check GetLastError().
2168 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2170 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2171 if (status) SetLastError( RtlNtStatusToDosError(status) );
2172 return !status;
2175 /***********************************************************************
2176 * ExitProcess (KERNEL32.@)
2178 * Exits the current process.
2180 * PARAMS
2181 * status [I] Status code to exit with.
2183 * RETURNS
2184 * Nothing.
2186 #ifdef __i386__
2187 __ASM_GLOBAL_FUNC( ExitProcess, /* Shrinker depend on this particular ExitProcess implementation */
2188 "pushl %ebp\n\t"
2189 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2190 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2191 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2192 "pushl 8(%ebp)\n\t"
2193 "call " __ASM_NAME("process_ExitProcess") "\n\t"
2194 "leave\n\t"
2195 "ret $4" )
2197 void WINAPI process_ExitProcess( DWORD status )
2199 LdrShutdownProcess();
2200 NtTerminateProcess(GetCurrentProcess(), status);
2201 exit(status);
2204 #else
2206 void WINAPI ExitProcess( DWORD status )
2208 LdrShutdownProcess();
2209 NtTerminateProcess(GetCurrentProcess(), status);
2210 exit(status);
2213 #endif
2215 /***********************************************************************
2216 * GetExitCodeProcess [KERNEL32.@]
2218 * Gets termination status of specified process.
2220 * PARAMS
2221 * hProcess [in] Handle to the process.
2222 * lpExitCode [out] Address to receive termination status.
2224 * RETURNS
2225 * Success: TRUE
2226 * Failure: FALSE
2228 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2230 NTSTATUS status;
2231 PROCESS_BASIC_INFORMATION pbi;
2233 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2234 sizeof(pbi), NULL);
2235 if (status == STATUS_SUCCESS)
2237 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2238 return TRUE;
2240 SetLastError( RtlNtStatusToDosError(status) );
2241 return FALSE;
2245 /***********************************************************************
2246 * SetErrorMode (KERNEL32.@)
2248 UINT WINAPI SetErrorMode( UINT mode )
2250 UINT old = process_error_mode;
2251 process_error_mode = mode;
2252 return old;
2255 /***********************************************************************
2256 * GetErrorMode (KERNEL32.@)
2258 UINT WINAPI GetErrorMode( void )
2260 return process_error_mode;
2263 /**********************************************************************
2264 * TlsAlloc [KERNEL32.@]
2266 * Allocates a thread local storage index.
2268 * RETURNS
2269 * Success: TLS index.
2270 * Failure: 0xFFFFFFFF
2272 DWORD WINAPI TlsAlloc( void )
2274 DWORD index;
2275 PEB * const peb = NtCurrentTeb()->Peb;
2277 RtlAcquirePebLock();
2278 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2279 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2280 else
2282 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2283 if (index != ~0U)
2285 if (!NtCurrentTeb()->TlsExpansionSlots &&
2286 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2287 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2289 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2290 index = ~0U;
2291 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2293 else
2295 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2296 index += TLS_MINIMUM_AVAILABLE;
2299 else SetLastError( ERROR_NO_MORE_ITEMS );
2301 RtlReleasePebLock();
2302 return index;
2306 /**********************************************************************
2307 * TlsFree [KERNEL32.@]
2309 * Releases a thread local storage index, making it available for reuse.
2311 * PARAMS
2312 * index [in] TLS index to free.
2314 * RETURNS
2315 * Success: TRUE
2316 * Failure: FALSE
2318 BOOL WINAPI TlsFree( DWORD index )
2320 BOOL ret;
2322 RtlAcquirePebLock();
2323 if (index >= TLS_MINIMUM_AVAILABLE)
2325 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2326 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2328 else
2330 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2331 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2333 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2334 else SetLastError( ERROR_INVALID_PARAMETER );
2335 RtlReleasePebLock();
2336 return TRUE;
2340 /**********************************************************************
2341 * TlsGetValue [KERNEL32.@]
2343 * Gets value in a thread's TLS slot.
2345 * PARAMS
2346 * index [in] TLS index to retrieve value for.
2348 * RETURNS
2349 * Success: Value stored in calling thread's TLS slot for index.
2350 * Failure: 0 and GetLastError() returns NO_ERROR.
2352 LPVOID WINAPI TlsGetValue( DWORD index )
2354 LPVOID ret;
2356 if (index < TLS_MINIMUM_AVAILABLE)
2358 ret = NtCurrentTeb()->TlsSlots[index];
2360 else
2362 index -= TLS_MINIMUM_AVAILABLE;
2363 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2365 SetLastError( ERROR_INVALID_PARAMETER );
2366 return NULL;
2368 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2369 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2371 SetLastError( ERROR_SUCCESS );
2372 return ret;
2376 /**********************************************************************
2377 * TlsSetValue [KERNEL32.@]
2379 * Stores a value in the thread's TLS slot.
2381 * PARAMS
2382 * index [in] TLS index to set value for.
2383 * value [in] Value to be stored.
2385 * RETURNS
2386 * Success: TRUE
2387 * Failure: FALSE
2389 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2391 if (index < TLS_MINIMUM_AVAILABLE)
2393 NtCurrentTeb()->TlsSlots[index] = value;
2395 else
2397 index -= TLS_MINIMUM_AVAILABLE;
2398 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2400 SetLastError( ERROR_INVALID_PARAMETER );
2401 return FALSE;
2403 if (!NtCurrentTeb()->TlsExpansionSlots &&
2404 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2405 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2407 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2408 return FALSE;
2410 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2412 return TRUE;
2416 /***********************************************************************
2417 * GetProcessFlags (KERNEL32.@)
2419 DWORD WINAPI GetProcessFlags( DWORD processid )
2421 IMAGE_NT_HEADERS *nt;
2422 DWORD flags = 0;
2424 if (processid && processid != GetCurrentProcessId()) return 0;
2426 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2428 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2429 flags |= PDB32_CONSOLE_PROC;
2431 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2432 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2433 return flags;
2437 /***********************************************************************
2438 * GetProcessDword (KERNEL.485)
2439 * GetProcessDword (KERNEL32.18)
2440 * 'Of course you cannot directly access Windows internal structures'
2442 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2444 DWORD x, y;
2445 STARTUPINFOW siw;
2447 TRACE("(%d, %d)\n", dwProcessID, offset );
2449 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2451 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2452 return 0;
2455 switch ( offset )
2457 case GPD_APP_COMPAT_FLAGS:
2458 return GetAppCompatFlags16(0);
2459 case GPD_LOAD_DONE_EVENT:
2460 return 0;
2461 case GPD_HINSTANCE16:
2462 return GetTaskDS16();
2463 case GPD_WINDOWS_VERSION:
2464 return GetExeVersion16();
2465 case GPD_THDB:
2466 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2467 case GPD_PDB:
2468 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2469 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2470 GetStartupInfoW(&siw);
2471 return HandleToULong(siw.hStdOutput);
2472 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2473 GetStartupInfoW(&siw);
2474 return HandleToULong(siw.hStdInput);
2475 case GPD_STARTF_SHOWWINDOW:
2476 GetStartupInfoW(&siw);
2477 return siw.wShowWindow;
2478 case GPD_STARTF_SIZE:
2479 GetStartupInfoW(&siw);
2480 x = siw.dwXSize;
2481 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2482 y = siw.dwYSize;
2483 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2484 return MAKELONG( x, y );
2485 case GPD_STARTF_POSITION:
2486 GetStartupInfoW(&siw);
2487 x = siw.dwX;
2488 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2489 y = siw.dwY;
2490 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2491 return MAKELONG( x, y );
2492 case GPD_STARTF_FLAGS:
2493 GetStartupInfoW(&siw);
2494 return siw.dwFlags;
2495 case GPD_PARENT:
2496 return 0;
2497 case GPD_FLAGS:
2498 return GetProcessFlags(0);
2499 case GPD_USERDATA:
2500 return process_dword;
2501 default:
2502 ERR("Unknown offset %d\n", offset );
2503 return 0;
2507 /***********************************************************************
2508 * SetProcessDword (KERNEL.484)
2509 * 'Of course you cannot directly access Windows internal structures'
2511 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2513 TRACE("(%d, %d)\n", dwProcessID, offset );
2515 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2517 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2518 return;
2521 switch ( offset )
2523 case GPD_APP_COMPAT_FLAGS:
2524 case GPD_LOAD_DONE_EVENT:
2525 case GPD_HINSTANCE16:
2526 case GPD_WINDOWS_VERSION:
2527 case GPD_THDB:
2528 case GPD_PDB:
2529 case GPD_STARTF_SHELLDATA:
2530 case GPD_STARTF_HOTKEY:
2531 case GPD_STARTF_SHOWWINDOW:
2532 case GPD_STARTF_SIZE:
2533 case GPD_STARTF_POSITION:
2534 case GPD_STARTF_FLAGS:
2535 case GPD_PARENT:
2536 case GPD_FLAGS:
2537 ERR("Not allowed to modify offset %d\n", offset );
2538 break;
2539 case GPD_USERDATA:
2540 process_dword = value;
2541 break;
2542 default:
2543 ERR("Unknown offset %d\n", offset );
2544 break;
2549 /***********************************************************************
2550 * ExitProcess (KERNEL.466)
2552 void WINAPI ExitProcess16( WORD status )
2554 DWORD count;
2555 ReleaseThunkLock( &count );
2556 ExitProcess( status );
2560 /*********************************************************************
2561 * OpenProcess (KERNEL32.@)
2563 * Opens a handle to a process.
2565 * PARAMS
2566 * access [I] Desired access rights assigned to the returned handle.
2567 * inherit [I] Determines whether or not child processes will inherit the handle.
2568 * id [I] Process identifier of the process to get a handle to.
2570 * RETURNS
2571 * Success: Valid handle to the specified process.
2572 * Failure: NULL, check GetLastError().
2574 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2576 NTSTATUS status;
2577 HANDLE handle;
2578 OBJECT_ATTRIBUTES attr;
2579 CLIENT_ID cid;
2581 cid.UniqueProcess = ULongToHandle(id);
2582 cid.UniqueThread = 0; /* FIXME ? */
2584 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2585 attr.RootDirectory = NULL;
2586 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2587 attr.SecurityDescriptor = NULL;
2588 attr.SecurityQualityOfService = NULL;
2589 attr.ObjectName = NULL;
2591 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2593 status = NtOpenProcess(&handle, access, &attr, &cid);
2594 if (status != STATUS_SUCCESS)
2596 SetLastError( RtlNtStatusToDosError(status) );
2597 return NULL;
2599 return handle;
2603 /*********************************************************************
2604 * MapProcessHandle (KERNEL.483)
2605 * GetProcessId (KERNEL32.@)
2607 * Gets the a unique identifier of a process.
2609 * PARAMS
2610 * hProcess [I] Handle to the process.
2612 * RETURNS
2613 * Success: TRUE.
2614 * Failure: FALSE, check GetLastError().
2616 * NOTES
2618 * The identifier is unique only on the machine and only until the process
2619 * exits (including system shutdown).
2621 DWORD WINAPI GetProcessId( HANDLE hProcess )
2623 NTSTATUS status;
2624 PROCESS_BASIC_INFORMATION pbi;
2626 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2627 sizeof(pbi), NULL);
2628 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2629 SetLastError( RtlNtStatusToDosError(status) );
2630 return 0;
2634 /*********************************************************************
2635 * CloseW32Handle (KERNEL.474)
2636 * CloseHandle (KERNEL32.@)
2638 * Closes a handle.
2640 * PARAMS
2641 * handle [I] Handle to close.
2643 * RETURNS
2644 * Success: TRUE.
2645 * Failure: FALSE, check GetLastError().
2647 BOOL WINAPI CloseHandle( HANDLE handle )
2649 NTSTATUS status;
2651 /* stdio handles need special treatment */
2652 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2653 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2654 (handle == (HANDLE)STD_ERROR_HANDLE))
2655 handle = GetStdHandle( HandleToULong(handle) );
2657 if (is_console_handle(handle))
2658 return CloseConsoleHandle(handle);
2660 status = NtClose( handle );
2661 if (status) SetLastError( RtlNtStatusToDosError(status) );
2662 return !status;
2666 /*********************************************************************
2667 * GetHandleInformation (KERNEL32.@)
2669 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2671 OBJECT_DATA_INFORMATION info;
2672 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2674 if (status) SetLastError( RtlNtStatusToDosError(status) );
2675 else if (flags)
2677 *flags = 0;
2678 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2679 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2681 return !status;
2685 /*********************************************************************
2686 * SetHandleInformation (KERNEL32.@)
2688 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2690 OBJECT_DATA_INFORMATION info;
2691 NTSTATUS status;
2693 /* if not setting both fields, retrieve current value first */
2694 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2695 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2697 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2699 SetLastError( RtlNtStatusToDosError(status) );
2700 return FALSE;
2703 if (mask & HANDLE_FLAG_INHERIT)
2704 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2705 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2706 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2708 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2709 if (status) SetLastError( RtlNtStatusToDosError(status) );
2710 return !status;
2714 /*********************************************************************
2715 * DuplicateHandle (KERNEL32.@)
2717 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2718 HANDLE dest_process, HANDLE *dest,
2719 DWORD access, BOOL inherit, DWORD options )
2721 NTSTATUS status;
2723 if (is_console_handle(source))
2725 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2726 if (source_process != dest_process ||
2727 source_process != GetCurrentProcess())
2729 SetLastError(ERROR_INVALID_PARAMETER);
2730 return FALSE;
2732 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2733 return (*dest != INVALID_HANDLE_VALUE);
2735 status = NtDuplicateObject( source_process, source, dest_process, dest,
2736 access, inherit ? OBJ_INHERIT : 0, options );
2737 if (status) SetLastError( RtlNtStatusToDosError(status) );
2738 return !status;
2742 /***********************************************************************
2743 * ConvertToGlobalHandle (KERNEL.476)
2744 * ConvertToGlobalHandle (KERNEL32.@)
2746 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2748 HANDLE ret = INVALID_HANDLE_VALUE;
2749 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2750 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2751 return ret;
2755 /***********************************************************************
2756 * SetHandleContext (KERNEL32.@)
2758 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2760 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2761 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2762 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2763 return FALSE;
2767 /***********************************************************************
2768 * GetHandleContext (KERNEL32.@)
2770 DWORD WINAPI GetHandleContext(HANDLE hnd)
2772 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2773 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2774 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2775 return 0;
2779 /***********************************************************************
2780 * CreateSocketHandle (KERNEL32.@)
2782 HANDLE WINAPI CreateSocketHandle(void)
2784 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2785 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2786 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2787 return INVALID_HANDLE_VALUE;
2791 /***********************************************************************
2792 * SetPriorityClass (KERNEL32.@)
2794 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2796 NTSTATUS status;
2797 PROCESS_PRIORITY_CLASS ppc;
2799 ppc.Foreground = FALSE;
2800 switch (priorityclass)
2802 case IDLE_PRIORITY_CLASS:
2803 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2804 case BELOW_NORMAL_PRIORITY_CLASS:
2805 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2806 case NORMAL_PRIORITY_CLASS:
2807 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2808 case ABOVE_NORMAL_PRIORITY_CLASS:
2809 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2810 case HIGH_PRIORITY_CLASS:
2811 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2812 case REALTIME_PRIORITY_CLASS:
2813 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2814 default:
2815 SetLastError(ERROR_INVALID_PARAMETER);
2816 return FALSE;
2819 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2820 &ppc, sizeof(ppc));
2822 if (status != STATUS_SUCCESS)
2824 SetLastError( RtlNtStatusToDosError(status) );
2825 return FALSE;
2827 return TRUE;
2831 /***********************************************************************
2832 * GetPriorityClass (KERNEL32.@)
2834 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2836 NTSTATUS status;
2837 PROCESS_BASIC_INFORMATION pbi;
2839 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2840 sizeof(pbi), NULL);
2841 if (status != STATUS_SUCCESS)
2843 SetLastError( RtlNtStatusToDosError(status) );
2844 return 0;
2846 switch (pbi.BasePriority)
2848 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2849 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2850 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2851 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2852 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2853 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2855 SetLastError( ERROR_INVALID_PARAMETER );
2856 return 0;
2860 /***********************************************************************
2861 * SetProcessAffinityMask (KERNEL32.@)
2863 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2865 NTSTATUS status;
2867 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2868 &affmask, sizeof(DWORD_PTR));
2869 if (status)
2871 SetLastError( RtlNtStatusToDosError(status) );
2872 return FALSE;
2874 return TRUE;
2878 /**********************************************************************
2879 * GetProcessAffinityMask (KERNEL32.@)
2881 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2882 PDWORD_PTR lpProcessAffinityMask,
2883 PDWORD_PTR lpSystemAffinityMask )
2885 PROCESS_BASIC_INFORMATION pbi;
2886 NTSTATUS status;
2888 status = NtQueryInformationProcess(hProcess,
2889 ProcessBasicInformation,
2890 &pbi, sizeof(pbi), NULL);
2891 if (status)
2893 SetLastError( RtlNtStatusToDosError(status) );
2894 return FALSE;
2896 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2897 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2898 return TRUE;
2902 /***********************************************************************
2903 * GetProcessVersion (KERNEL32.@)
2905 DWORD WINAPI GetProcessVersion( DWORD pid )
2907 HANDLE process;
2908 NTSTATUS status;
2909 PROCESS_BASIC_INFORMATION pbi;
2910 SIZE_T count;
2911 PEB peb;
2912 IMAGE_DOS_HEADER dos;
2913 IMAGE_NT_HEADERS nt;
2914 DWORD ver = 0;
2916 if (!pid || pid == GetCurrentProcessId())
2918 IMAGE_NT_HEADERS *nt;
2920 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2921 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2922 nt->OptionalHeader.MinorSubsystemVersion);
2923 return 0;
2926 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2927 if (!process) return 0;
2929 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2930 if (status) goto err;
2932 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2933 if (status || count != sizeof(peb)) goto err;
2935 memset(&dos, 0, sizeof(dos));
2936 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2937 if (status || count != sizeof(dos)) goto err;
2938 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2940 memset(&nt, 0, sizeof(nt));
2941 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2942 if (status || count != sizeof(nt)) goto err;
2943 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2945 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2947 err:
2948 CloseHandle(process);
2950 if (status != STATUS_SUCCESS)
2951 SetLastError(RtlNtStatusToDosError(status));
2953 return ver;
2957 /***********************************************************************
2958 * SetProcessWorkingSetSize [KERNEL32.@]
2959 * Sets the min/max working set sizes for a specified process.
2961 * PARAMS
2962 * hProcess [I] Handle to the process of interest
2963 * minset [I] Specifies minimum working set size
2964 * maxset [I] Specifies maximum working set size
2966 * RETURNS
2967 * Success: TRUE
2968 * Failure: FALSE
2970 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2971 SIZE_T maxset)
2973 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2974 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2975 /* Trim the working set to zero */
2976 /* Swap the process out of physical RAM */
2978 return TRUE;
2981 /***********************************************************************
2982 * GetProcessWorkingSetSize (KERNEL32.@)
2984 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2985 PSIZE_T maxset)
2987 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2988 /* 32 MB working set size */
2989 if (minset) *minset = 32*1024*1024;
2990 if (maxset) *maxset = 32*1024*1024;
2991 return TRUE;
2995 /***********************************************************************
2996 * SetProcessShutdownParameters (KERNEL32.@)
2998 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3000 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3001 shutdown_flags = flags;
3002 shutdown_priority = level;
3003 return TRUE;
3007 /***********************************************************************
3008 * GetProcessShutdownParameters (KERNEL32.@)
3011 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3013 *lpdwLevel = shutdown_priority;
3014 *lpdwFlags = shutdown_flags;
3015 return TRUE;
3019 /***********************************************************************
3020 * GetProcessPriorityBoost (KERNEL32.@)
3022 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3024 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3026 /* Report that no boost is present.. */
3027 *pDisablePriorityBoost = FALSE;
3029 return TRUE;
3032 /***********************************************************************
3033 * SetProcessPriorityBoost (KERNEL32.@)
3035 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3037 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3038 /* Say we can do it. I doubt the program will notice that we don't. */
3039 return TRUE;
3043 /***********************************************************************
3044 * ReadProcessMemory (KERNEL32.@)
3046 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3047 SIZE_T *bytes_read )
3049 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3050 if (status) SetLastError( RtlNtStatusToDosError(status) );
3051 return !status;
3055 /***********************************************************************
3056 * WriteProcessMemory (KERNEL32.@)
3058 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3059 SIZE_T *bytes_written )
3061 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3062 if (status) SetLastError( RtlNtStatusToDosError(status) );
3063 return !status;
3067 /****************************************************************************
3068 * FlushInstructionCache (KERNEL32.@)
3070 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3072 NTSTATUS status;
3073 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3074 if (status) SetLastError( RtlNtStatusToDosError(status) );
3075 return !status;
3079 /******************************************************************
3080 * GetProcessIoCounters (KERNEL32.@)
3082 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3084 NTSTATUS status;
3086 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3087 ioc, sizeof(*ioc), NULL);
3088 if (status) SetLastError( RtlNtStatusToDosError(status) );
3089 return !status;
3092 /******************************************************************
3093 * GetProcessHandleCount (KERNEL32.@)
3095 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3097 NTSTATUS status;
3099 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3100 cnt, sizeof(*cnt), NULL);
3101 if (status) SetLastError( RtlNtStatusToDosError(status) );
3102 return !status;
3105 /***********************************************************************
3106 * ProcessIdToSessionId (KERNEL32.@)
3107 * This function is available on Terminal Server 4SP4 and Windows 2000
3109 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3111 /* According to MSDN, if the calling process is not in a terminal
3112 * services environment, then the sessionid returned is zero.
3114 *sessionid_ptr = 0;
3115 return TRUE;
3119 /***********************************************************************
3120 * RegisterServiceProcess (KERNEL.491)
3121 * RegisterServiceProcess (KERNEL32.@)
3123 * A service process calls this function to ensure that it continues to run
3124 * even after a user logged off.
3126 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3128 /* I don't think that Wine needs to do anything in this function */
3129 return 1; /* success */
3133 /**********************************************************************
3134 * IsWow64Process (KERNEL32.@)
3136 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3138 ULONG pbi;
3139 NTSTATUS status;
3141 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3143 if (status != STATUS_SUCCESS)
3145 SetLastError( RtlNtStatusToDosError( status ) );
3146 return FALSE;
3148 *Wow64Process = (pbi != 0);
3149 return TRUE;
3153 /***********************************************************************
3154 * GetCurrentProcess (KERNEL32.@)
3156 * Get a handle to the current process.
3158 * PARAMS
3159 * None.
3161 * RETURNS
3162 * A handle representing the current process.
3164 #undef GetCurrentProcess
3165 HANDLE WINAPI GetCurrentProcess(void)
3167 return (HANDLE)~(ULONG_PTR)0;
3170 /***********************************************************************
3171 * CmdBatNotification (KERNEL32.@)
3173 * Notifies the system that a batch file has started or finished.
3175 * PARAMS
3176 * bBatchRunning [I] TRUE if a batch file has started or
3177 * FALSE if a batch file has finished executing.
3179 * RETURNS
3180 * Unknown.
3182 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3184 FIXME("%d\n", bBatchRunning);
3185 return FALSE;
3189 /***********************************************************************
3190 * RegisterApplicationRestart (KERNEL32.@)
3192 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3194 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3196 return S_OK;