kernel32/nls: Define the neutral and reading layout locale values.
[wine.git] / dlls / kernel32 / process.c
blobd4c2063a9154da5b15eb2f4427c181205d6e3a66
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 <stdarg.h>
29 #include <stdio.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
42 #endif
43 #include <sys/types.h>
45 #include "ntstatus.h"
46 #define WIN32_NO_STATUS
47 #include "winternl.h"
48 #include "kernel_private.h"
49 #include "wine/library.h"
50 #include "wine/server.h"
51 #include "wine/unicode.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(process);
55 WINE_DECLARE_DEBUG_CHANNEL(file);
56 WINE_DECLARE_DEBUG_CHANNEL(relay);
58 #ifdef __APPLE__
59 extern char **__wine_get_main_environment(void);
60 #else
61 extern char **__wine_main_environ;
62 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
63 #endif
65 typedef struct
67 LPSTR lpEnvAddress;
68 LPSTR lpCmdLine;
69 LPSTR lpCmdShow;
70 DWORD dwReserved;
71 } LOADPARMS32;
73 static DWORD shutdown_flags = 0;
74 static DWORD shutdown_priority = 0x280;
75 static BOOL is_wow64;
76 static const int is_win64 = (sizeof(void *) > sizeof(int));
78 HMODULE kernel32_handle = 0;
80 const WCHAR *DIR_Windows = NULL;
81 const WCHAR *DIR_System = NULL;
82 const WCHAR *DIR_SysWow64 = NULL;
84 /* Process flags */
85 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
86 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
87 #define PDB32_DOS_PROC 0x0010 /* Dos process */
88 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
89 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
90 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
92 static const WCHAR exeW[] = {'.','e','x','e',0};
93 static const WCHAR comW[] = {'.','c','o','m',0};
94 static const WCHAR batW[] = {'.','b','a','t',0};
95 static const WCHAR cmdW[] = {'.','c','m','d',0};
96 static const WCHAR pifW[] = {'.','p','i','f',0};
97 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
99 static void exec_process( LPCWSTR name );
101 extern void SHELL_LoadRegistry(void);
104 /***********************************************************************
105 * contains_path
107 static inline int contains_path( LPCWSTR name )
109 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
113 /***********************************************************************
114 * is_special_env_var
116 * Check if an environment variable needs to be handled specially when
117 * passed through the Unix environment (i.e. prefixed with "WINE").
119 static inline int is_special_env_var( const char *var )
121 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
122 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
123 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
124 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
125 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
129 /***********************************************************************
130 * is_path_prefix
132 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
134 unsigned int len = strlenW( prefix );
136 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
137 while (filename[len] == '\\') len++;
138 return len;
142 /***************************************************************************
143 * get_builtin_path
145 * Get the path of a builtin module when the native file does not exist.
147 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
148 UINT size, struct binary_info *binary_info )
150 WCHAR *file_part;
151 UINT len;
152 void *redir_disabled = 0;
153 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
155 /* builtin names cannot be empty or contain spaces */
156 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
158 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
159 Wow64RevertWow64FsRedirection( redir_disabled );
161 if (contains_path( libname ))
163 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
164 filename, &file_part ) > size * sizeof(WCHAR))
165 return FALSE; /* too long */
167 if ((len = is_path_prefix( DIR_System, filename )))
169 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
171 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
173 flags = 0;
175 else return FALSE;
177 if (filename + len != file_part) return FALSE;
179 else
181 len = strlenW( DIR_System );
182 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
183 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
184 file_part = filename + len;
185 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
186 strcpyW( file_part, libname );
187 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
189 if (ext && !strchrW( file_part, '.' ))
191 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
192 return FALSE; /* too long */
193 strcatW( file_part, ext );
195 binary_info->type = BINARY_UNIX_LIB;
196 binary_info->flags = flags;
197 binary_info->res_start = NULL;
198 binary_info->res_end = NULL;
199 return TRUE;
203 /***********************************************************************
204 * open_exe_file
206 * Open a specific exe file, taking load order into account.
207 * Returns the file handle or 0 for a builtin exe.
209 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
211 HANDLE handle;
213 TRACE("looking for %s\n", debugstr_w(name) );
215 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
216 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
218 WCHAR buffer[MAX_PATH];
219 /* file doesn't exist, check for builtin */
220 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
221 handle = 0;
223 else MODULE_get_binary_info( handle, binary_info );
225 return handle;
229 /***********************************************************************
230 * find_exe_file
232 * Open an exe file, and return the full name and file handle.
233 * Returns FALSE if file could not be found.
234 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
235 * If file is a builtin exe, returns TRUE and sets handle to 0.
237 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
238 HANDLE *handle, struct binary_info *binary_info )
240 TRACE("looking for %s\n", debugstr_w(name) );
242 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
244 if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
246 *handle = 0;
247 return TRUE;
249 /* no builtin found, try native without extension in case it is a Unix app */
250 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
253 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
254 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
255 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
257 MODULE_get_binary_info( *handle, binary_info );
258 return TRUE;
260 return FALSE;
264 /***********************************************************************
265 * build_initial_environment
267 * Build the Win32 environment from the Unix environment
269 static BOOL build_initial_environment(void)
271 SIZE_T size = 1;
272 char **e;
273 WCHAR *p, *endptr;
274 void *ptr;
275 char **env = __wine_get_main_environment();
277 /* Compute the total size of the Unix environment */
278 for (e = env; *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 = env; *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 static const WCHAR pathW[] = {'P','A','T','H'};
325 static const WCHAR sep[] = {';',0};
326 UNICODE_STRING env_name, env_value;
327 NTSTATUS status;
328 DWORD size;
329 int index;
330 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
331 WCHAR tmpbuf[1024];
332 UNICODE_STRING tmp;
333 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
335 tmp.Buffer = tmpbuf;
336 tmp.MaximumLength = sizeof(tmpbuf);
338 for (index = 0; ; index++)
340 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
341 buffer, sizeof(buffer), &size );
342 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
343 break;
344 if (info->Type != type)
345 continue;
346 env_name.Buffer = info->Name;
347 env_name.Length = env_name.MaximumLength = info->NameLength;
348 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
349 env_value.Length = info->DataLength;
350 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
351 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
352 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
353 if (!env_value.Length) continue;
354 if (info->Type == REG_EXPAND_SZ)
356 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
357 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
358 RtlCopyUnicodeString( &env_value, &tmp );
360 /* PATH is magic */
361 if (env_name.Length == sizeof(pathW) &&
362 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
363 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
365 RtlAppendUnicodeToString( &tmp, sep );
366 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
367 RtlCopyUnicodeString( &env_value, &tmp );
369 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
374 /***********************************************************************
375 * set_registry_environment
377 * Set the environment variables specified in the registry.
379 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
380 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
381 * on the order in which the variables are processed. But on Windows it
382 * does not really matter since they only use %SystemDrive% and
383 * %SystemRoot% which are predefined. But Wine defines these in the
384 * registry, so we need two passes.
386 static BOOL set_registry_environment( BOOL volatile_only )
388 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
389 'S','y','s','t','e','m','\\',
390 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
391 'C','o','n','t','r','o','l','\\',
392 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
393 'E','n','v','i','r','o','n','m','e','n','t',0};
394 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
395 static const WCHAR volatile_envW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
397 OBJECT_ATTRIBUTES attr;
398 UNICODE_STRING nameW;
399 HANDLE hkey;
400 BOOL ret = FALSE;
402 attr.Length = sizeof(attr);
403 attr.RootDirectory = 0;
404 attr.ObjectName = &nameW;
405 attr.Attributes = 0;
406 attr.SecurityDescriptor = NULL;
407 attr.SecurityQualityOfService = NULL;
409 /* first the system environment variables */
410 RtlInitUnicodeString( &nameW, env_keyW );
411 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
413 set_registry_variables( hkey, REG_SZ );
414 set_registry_variables( hkey, REG_EXPAND_SZ );
415 NtClose( hkey );
416 ret = TRUE;
419 /* then the ones for the current user */
420 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
421 RtlInitUnicodeString( &nameW, envW );
422 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
424 set_registry_variables( hkey, REG_SZ );
425 set_registry_variables( hkey, REG_EXPAND_SZ );
426 NtClose( hkey );
429 RtlInitUnicodeString( &nameW, volatile_envW );
430 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
432 set_registry_variables( hkey, REG_SZ );
433 set_registry_variables( hkey, REG_EXPAND_SZ );
434 NtClose( hkey );
437 NtClose( attr.RootDirectory );
438 return ret;
442 /***********************************************************************
443 * get_reg_value
445 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
447 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
448 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
449 DWORD len, size = sizeof(buffer);
450 WCHAR *ret = NULL;
451 UNICODE_STRING nameW;
453 RtlInitUnicodeString( &nameW, name );
454 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
455 return NULL;
457 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
458 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
460 if (info->Type == REG_EXPAND_SZ)
462 UNICODE_STRING value, expanded;
464 value.MaximumLength = len * sizeof(WCHAR);
465 value.Buffer = (WCHAR *)info->Data;
466 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
467 value.Length = len * sizeof(WCHAR);
468 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
469 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
470 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
471 else RtlFreeUnicodeString( &expanded );
473 else if (info->Type == REG_SZ)
475 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
477 memcpy( ret, info->Data, len * sizeof(WCHAR) );
478 ret[len] = 0;
481 return ret;
485 /***********************************************************************
486 * set_additional_environment
488 * Set some additional environment variables not specified in the registry.
490 static void set_additional_environment(void)
492 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
493 'S','o','f','t','w','a','r','e','\\',
494 'M','i','c','r','o','s','o','f','t','\\',
495 'W','i','n','d','o','w','s',' ','N','T','\\',
496 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
497 'P','r','o','f','i','l','e','L','i','s','t',0};
498 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
499 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
500 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
501 OBJECT_ATTRIBUTES attr;
502 UNICODE_STRING nameW;
503 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
504 HANDLE hkey;
505 DWORD len;
507 /* set the ALLUSERSPROFILE variables */
509 attr.Length = sizeof(attr);
510 attr.RootDirectory = 0;
511 attr.ObjectName = &nameW;
512 attr.Attributes = 0;
513 attr.SecurityDescriptor = NULL;
514 attr.SecurityQualityOfService = NULL;
515 RtlInitUnicodeString( &nameW, profile_keyW );
516 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
518 profile_dir = get_reg_value( hkey, profiles_valueW );
519 all_users_dir = get_reg_value( hkey, all_users_valueW );
520 NtClose( hkey );
523 if (profile_dir && all_users_dir)
525 WCHAR *value, *p;
527 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
528 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
529 strcpyW( value, profile_dir );
530 p = value + strlenW(value);
531 if (p > value && p[-1] != '\\') *p++ = '\\';
532 strcpyW( p, all_users_dir );
533 SetEnvironmentVariableW( allusersW, value );
534 HeapFree( GetProcessHeap(), 0, value );
537 HeapFree( GetProcessHeap(), 0, all_users_dir );
538 HeapFree( GetProcessHeap(), 0, profile_dir );
541 /***********************************************************************
542 * set_library_wargv
544 * Set the Wine library Unicode argv global variables.
546 static void set_library_wargv( char **argv )
548 int argc;
549 char *q;
550 WCHAR *p;
551 WCHAR **wargv;
552 DWORD total = 0;
554 for (argc = 0; argv[argc]; argc++)
555 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
557 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
558 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
559 p = (WCHAR *)(wargv + argc + 1);
560 for (argc = 0; argv[argc]; argc++)
562 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
563 wargv[argc] = p;
564 p += reslen;
565 total -= reslen;
567 wargv[argc] = NULL;
569 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
571 for (argc = 0; wargv[argc]; argc++)
572 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
574 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
575 q = (char *)(argv + argc + 1);
576 for (argc = 0; wargv[argc]; argc++)
578 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
579 argv[argc] = q;
580 q += reslen;
581 total -= reslen;
583 argv[argc] = NULL;
585 __wine_main_argc = argc;
586 __wine_main_argv = argv;
587 __wine_main_wargv = wargv;
591 /***********************************************************************
592 * update_library_argv0
594 * Update the argv[0] global variable with the binary we have found.
596 static void update_library_argv0( const WCHAR *argv0 )
598 DWORD len = strlenW( argv0 );
600 if (len > strlenW( __wine_main_wargv[0] ))
602 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
604 strcpyW( __wine_main_wargv[0], argv0 );
606 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
607 if (len > strlen( __wine_main_argv[0] ) + 1)
609 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
611 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
615 /***********************************************************************
616 * build_command_line
618 * Build the command line of a process from the argv array.
620 * Note that it does NOT necessarily include the file name.
621 * Sometimes we don't even have any command line options at all.
623 * We must quote and escape characters so that the argv array can be rebuilt
624 * from the command line:
625 * - spaces and tabs must be quoted
626 * 'a b' -> '"a b"'
627 * - quotes must be escaped
628 * '"' -> '\"'
629 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
630 * resulting in an odd number of '\' followed by a '"'
631 * '\"' -> '\\\"'
632 * '\\"' -> '\\\\\"'
633 * - '\'s that are not followed by a '"' can be left as is
634 * 'a\b' == 'a\b'
635 * 'a\\b' == 'a\\b'
637 static BOOL build_command_line( WCHAR **argv )
639 int len;
640 WCHAR **arg;
641 LPWSTR p;
642 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
644 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
646 len = 0;
647 for (arg = argv; *arg; arg++)
649 int has_space,bcount;
650 WCHAR* a;
652 has_space=0;
653 bcount=0;
654 a=*arg;
655 if( !*a ) has_space=1;
656 while (*a!='\0') {
657 if (*a=='\\') {
658 bcount++;
659 } else {
660 if (*a==' ' || *a=='\t') {
661 has_space=1;
662 } else if (*a=='"') {
663 /* doubling of '\' preceding a '"',
664 * plus escaping of said '"'
666 len+=2*bcount+1;
668 bcount=0;
670 a++;
672 len+=(a-*arg)+1 /* for the separating space */;
673 if (has_space)
674 len+=2; /* for the quotes */
677 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
678 return FALSE;
680 p = rupp->CommandLine.Buffer;
681 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
682 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
683 for (arg = argv; *arg; arg++)
685 int has_space,has_quote;
686 WCHAR* a;
688 /* Check for quotes and spaces in this argument */
689 has_space=has_quote=0;
690 a=*arg;
691 if( !*a ) has_space=1;
692 while (*a!='\0') {
693 if (*a==' ' || *a=='\t') {
694 has_space=1;
695 if (has_quote)
696 break;
697 } else if (*a=='"') {
698 has_quote=1;
699 if (has_space)
700 break;
702 a++;
705 /* Now transfer it to the command line */
706 if (has_space)
707 *p++='"';
708 if (has_quote) {
709 int bcount;
710 WCHAR* a;
712 bcount=0;
713 a=*arg;
714 while (*a!='\0') {
715 if (*a=='\\') {
716 *p++=*a;
717 bcount++;
718 } else {
719 if (*a=='"') {
720 int i;
722 /* Double all the '\\' preceding this '"', plus one */
723 for (i=0;i<=bcount;i++)
724 *p++='\\';
725 *p++='"';
726 } else {
727 *p++=*a;
729 bcount=0;
731 a++;
733 } else {
734 WCHAR* x = *arg;
735 while ((*p=*x++)) p++;
737 if (has_space)
738 *p++='"';
739 *p++=' ';
741 if (p > rupp->CommandLine.Buffer)
742 p--; /* remove last space */
743 *p = '\0';
745 return TRUE;
749 /***********************************************************************
750 * init_current_directory
752 * Initialize the current directory from the Unix cwd or the parent info.
754 static void init_current_directory( CURDIR *cur_dir )
756 UNICODE_STRING dir_str;
757 const char *pwd;
758 char *cwd;
759 int size;
761 /* if we received a cur dir from the parent, try this first */
763 if (cur_dir->DosPath.Length)
765 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
768 /* now try to get it from the Unix cwd */
770 for (size = 256; ; size *= 2)
772 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
773 if (getcwd( cwd, size )) break;
774 HeapFree( GetProcessHeap(), 0, cwd );
775 if (errno == ERANGE) continue;
776 cwd = NULL;
777 break;
780 /* try to use PWD if it is valid, so that we don't resolve symlinks */
782 pwd = getenv( "PWD" );
783 if (cwd)
785 struct stat st1, st2;
787 if (!pwd || stat( pwd, &st1 ) == -1 ||
788 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
789 pwd = cwd;
792 if (pwd)
794 ANSI_STRING unix_name;
795 UNICODE_STRING nt_name;
796 RtlInitAnsiString( &unix_name, pwd );
797 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
799 UNICODE_STRING dos_path;
800 /* skip the \??\ prefix, nt_name is 0 terminated */
801 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
802 RtlSetCurrentDirectory_U( &dos_path );
803 RtlFreeUnicodeString( &nt_name );
807 if (!cur_dir->DosPath.Length) /* still not initialized */
809 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
810 "starting in the Windows directory.\n", cwd ? cwd : "" );
811 RtlInitUnicodeString( &dir_str, DIR_Windows );
812 RtlSetCurrentDirectory_U( &dir_str );
814 HeapFree( GetProcessHeap(), 0, cwd );
816 done:
817 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
818 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
822 /***********************************************************************
823 * init_windows_dirs
825 * Initialize the windows and system directories from the environment.
827 static void init_windows_dirs(void)
829 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
831 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
832 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
833 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
834 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
835 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
837 DWORD len;
838 WCHAR *buffer;
840 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
842 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
843 GetEnvironmentVariableW( windirW, buffer, len );
844 DIR_Windows = buffer;
846 else DIR_Windows = default_windirW;
848 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
850 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
851 GetEnvironmentVariableW( winsysdirW, buffer, len );
852 DIR_System = buffer;
854 else
856 len = strlenW( DIR_Windows );
857 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
858 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
859 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
860 DIR_System = buffer;
863 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
864 ERR( "directory %s could not be created, error %u\n",
865 debugstr_w(DIR_Windows), GetLastError() );
866 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
867 ERR( "directory %s could not be created, error %u\n",
868 debugstr_w(DIR_System), GetLastError() );
870 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
872 len = strlenW( DIR_Windows );
873 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
874 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
875 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
876 DIR_SysWow64 = buffer;
877 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
878 ERR( "directory %s could not be created, error %u\n",
879 debugstr_w(DIR_SysWow64), GetLastError() );
882 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
883 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
885 /* set the directories in ntdll too */
886 __wine_init_windows_dir( DIR_Windows, DIR_System );
890 /***********************************************************************
891 * start_wineboot
893 * Start the wineboot process if necessary. Return the handles to wait on.
895 static void start_wineboot( HANDLE handles[2] )
897 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
899 handles[1] = 0;
900 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
902 ERR( "failed to create wineboot event, expect trouble\n" );
903 return;
905 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
907 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
908 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
909 STARTUPINFOW si;
910 PROCESS_INFORMATION pi;
911 void *redir;
912 WCHAR app[MAX_PATH];
913 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
915 memset( &si, 0, sizeof(si) );
916 si.cb = sizeof(si);
917 si.dwFlags = STARTF_USESTDHANDLES;
918 si.hStdInput = 0;
919 si.hStdOutput = 0;
920 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
922 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
923 lstrcatW( app, wineboot );
925 Wow64DisableWow64FsRedirection( &redir );
926 strcpyW( cmdline, app );
927 strcatW( cmdline, args );
928 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
930 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
931 CloseHandle( pi.hThread );
932 handles[1] = pi.hProcess;
934 else
936 ERR( "failed to start wineboot, err %u\n", GetLastError() );
937 CloseHandle( handles[0] );
938 handles[0] = 0;
940 Wow64RevertWow64FsRedirection( redir );
945 #ifdef __i386__
946 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
947 __ASM_GLOBAL_FUNC( call_process_entry,
948 "pushl %ebp\n\t"
949 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
950 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
951 "movl %esp,%ebp\n\t"
952 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
953 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
954 "pushl 8(%ebp)\n\t"
955 "call *12(%ebp)\n\t"
956 "leave\n\t"
957 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
958 __ASM_CFI(".cfi_same_value %ebp\n\t")
959 "ret" )
960 #else
961 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
963 return entry( peb );
965 #endif
967 /***********************************************************************
968 * start_process
970 * Startup routine of a new process. Runs on the new process stack.
972 static DWORD WINAPI start_process( PEB *peb )
974 IMAGE_NT_HEADERS *nt;
975 LPTHREAD_START_ROUTINE entry;
977 nt = RtlImageNtHeader( peb->ImageBaseAddress );
978 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
979 nt->OptionalHeader.AddressOfEntryPoint);
981 if (!nt->OptionalHeader.AddressOfEntryPoint)
983 ERR( "%s doesn't have an entry point, it cannot be executed\n",
984 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
985 ExitThread( 1 );
988 if (TRACE_ON(relay))
989 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
990 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
992 SetLastError( 0 ); /* clear error code */
993 if (peb->BeingDebugged) DbgBreakPoint();
994 return call_process_entry( peb, entry );
998 /***********************************************************************
999 * set_process_name
1001 * Change the process name in the ps output.
1003 static void set_process_name( int argc, char *argv[] )
1005 #ifdef HAVE_SETPROCTITLE
1006 setproctitle("-%s", argv[1]);
1007 #endif
1009 #ifdef HAVE_PRCTL
1010 int i, offset;
1011 char *p, *prctl_name = argv[1];
1012 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1014 #ifndef PR_SET_NAME
1015 # define PR_SET_NAME 15
1016 #endif
1018 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1019 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1021 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1023 offset = argv[1] - argv[0];
1024 memmove( argv[1] - offset, argv[1], end - argv[1] );
1025 memset( end - offset, 0, offset );
1026 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1027 argv[i-1] = NULL;
1029 else
1030 #endif /* HAVE_PRCTL */
1032 /* remove argv[0] */
1033 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1038 /***********************************************************************
1039 * __wine_kernel_init
1041 * Wine initialisation: load and start the main exe file.
1043 void CDECL __wine_kernel_init(void)
1045 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1046 static const WCHAR dotW[] = {'.',0};
1048 WCHAR *p, main_exe_name[MAX_PATH+1];
1049 PEB *peb = NtCurrentTeb()->Peb;
1050 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1051 HANDLE boot_events[2];
1052 BOOL got_environment = TRUE;
1054 /* Initialize everything */
1056 setbuf(stdout,NULL);
1057 setbuf(stderr,NULL);
1058 kernel32_handle = GetModuleHandleW(kernel32W);
1059 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1061 LOCALE_Init();
1063 if (!params->Environment)
1065 /* Copy the parent environment */
1066 if (!build_initial_environment()) exit(1);
1068 /* convert old configuration to new format */
1069 convert_old_config();
1071 got_environment = set_registry_environment( FALSE );
1072 set_additional_environment();
1075 init_windows_dirs();
1076 init_current_directory( &params->CurrentDirectory );
1078 set_process_name( __wine_main_argc, __wine_main_argv );
1079 set_library_wargv( __wine_main_argv );
1080 boot_events[0] = boot_events[1] = 0;
1082 if (peb->ProcessParameters->ImagePathName.Buffer)
1084 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1086 else
1088 struct binary_info binary_info;
1090 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1091 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1093 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1094 ExitProcess( GetLastError() );
1096 update_library_argv0( main_exe_name );
1097 if (!build_command_line( __wine_main_wargv )) goto error;
1098 start_wineboot( boot_events );
1101 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1102 p = strrchrW( main_exe_name, '.' );
1103 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1105 TRACE( "starting process name=%s argv[0]=%s\n",
1106 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1108 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1109 MODULE_get_dll_load_path(main_exe_name) );
1111 if (boot_events[0])
1113 DWORD timeout = 2 * 60 * 1000, count = 1;
1115 if (boot_events[1]) count++;
1116 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1117 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1118 ERR( "boot event wait timed out\n" );
1119 CloseHandle( boot_events[0] );
1120 if (boot_events[1]) CloseHandle( boot_events[1] );
1121 /* reload environment now that wineboot has run */
1122 set_registry_environment( got_environment );
1123 set_additional_environment();
1126 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1128 DWORD_PTR args[1];
1129 WCHAR msgW[1024];
1130 char msg[1024];
1131 DWORD error = GetLastError();
1133 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1134 if (error == ERROR_BAD_EXE_FORMAT ||
1135 error == ERROR_INVALID_ADDRESS ||
1136 error == ERROR_NOT_ENOUGH_MEMORY)
1138 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1139 /* if we get back here, it failed */
1141 else if (error == ERROR_MOD_NOT_FOUND)
1143 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1144 else p = main_exe_name;
1145 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1147 /* args 1 and 2 are --app-name full_path */
1148 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1149 debugstr_w(__wine_main_wargv[3]) );
1150 ExitProcess( ERROR_BAD_EXE_FORMAT );
1152 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1153 ExitProcess( ERROR_FILE_NOT_FOUND );
1155 args[0] = (DWORD_PTR)main_exe_name;
1156 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1157 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1158 WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1159 MESSAGE( "wine: %s", msg );
1160 ExitProcess( error );
1163 LdrInitializeThunk( start_process, 0, 0, 0 );
1165 error:
1166 ExitProcess( GetLastError() );
1170 /***********************************************************************
1171 * build_argv
1173 * Build an argv array from a command-line.
1174 * 'reserved' is the number of args to reserve before the first one.
1176 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1178 int argc;
1179 char** argv;
1180 char *arg,*s,*d,*cmdline;
1181 int in_quotes,bcount,len;
1183 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1184 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1185 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1187 argc=reserved+1;
1188 bcount=0;
1189 in_quotes=0;
1190 s=cmdline;
1191 while (1) {
1192 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1193 /* space */
1194 argc++;
1195 /* skip the remaining spaces */
1196 while (*s==' ' || *s=='\t') {
1197 s++;
1199 if (*s=='\0')
1200 break;
1201 bcount=0;
1202 continue;
1203 } else if (*s=='\\') {
1204 /* '\', count them */
1205 bcount++;
1206 } else if ((*s=='"') && ((bcount & 1)==0)) {
1207 /* unescaped '"' */
1208 in_quotes=!in_quotes;
1209 bcount=0;
1210 } else {
1211 /* a regular character */
1212 bcount=0;
1214 s++;
1216 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1218 HeapFree( GetProcessHeap(), 0, cmdline );
1219 return NULL;
1222 arg = d = s = (char *)(argv + argc);
1223 memcpy( d, cmdline, len );
1224 bcount=0;
1225 in_quotes=0;
1226 argc=reserved;
1227 while (*s) {
1228 if ((*s==' ' || *s=='\t') && !in_quotes) {
1229 /* Close the argument and copy it */
1230 *d=0;
1231 argv[argc++]=arg;
1233 /* skip the remaining spaces */
1234 do {
1235 s++;
1236 } while (*s==' ' || *s=='\t');
1238 /* Start with a new argument */
1239 arg=d=s;
1240 bcount=0;
1241 } else if (*s=='\\') {
1242 /* '\\' */
1243 *d++=*s++;
1244 bcount++;
1245 } else if (*s=='"') {
1246 /* '"' */
1247 if ((bcount & 1)==0) {
1248 /* Preceded by an even number of '\', this is half that
1249 * number of '\', plus a '"' which we discard.
1251 d-=bcount/2;
1252 s++;
1253 in_quotes=!in_quotes;
1254 } else {
1255 /* Preceded by an odd number of '\', this is half that
1256 * number of '\' followed by a '"'
1258 d=d-bcount/2-1;
1259 *d++='"';
1260 s++;
1262 bcount=0;
1263 } else {
1264 /* a regular character */
1265 *d++=*s++;
1266 bcount=0;
1269 if (*arg) {
1270 *d='\0';
1271 argv[argc++]=arg;
1273 argv[argc]=NULL;
1275 HeapFree( GetProcessHeap(), 0, cmdline );
1276 return argv;
1280 /***********************************************************************
1281 * build_envp
1283 * Build the environment of a new child process.
1285 static char **build_envp( const WCHAR *envW )
1287 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1289 const WCHAR *end;
1290 char **envp;
1291 char *env, *p;
1292 int count = 1, length;
1293 unsigned int i;
1295 for (end = envW; *end; count++) end += strlenW(end) + 1;
1296 end++;
1297 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1298 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1299 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1301 for (p = env; *p; p += strlen(p) + 1)
1302 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1304 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1306 if (!(p = getenv(unix_vars[i]))) continue;
1307 length += strlen(unix_vars[i]) + strlen(p) + 2;
1308 count++;
1311 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1313 char **envptr = envp;
1314 char *dst = (char *)(envp + count);
1316 /* some variables must not be modified, so we get them directly from the unix env */
1317 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1319 if (!(p = getenv(unix_vars[i]))) continue;
1320 *envptr++ = strcpy( dst, unix_vars[i] );
1321 strcat( dst, "=" );
1322 strcat( dst, p );
1323 dst += strlen(dst) + 1;
1326 /* now put the Windows environment strings */
1327 for (p = env; *p; p += strlen(p) + 1)
1329 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1330 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1331 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1332 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1333 if (is_special_env_var( p )) /* prefix it with "WINE" */
1335 *envptr++ = strcpy( dst, "WINE" );
1336 strcat( dst, p );
1338 else
1340 *envptr++ = strcpy( dst, p );
1342 dst += strlen(dst) + 1;
1344 *envptr = 0;
1346 HeapFree( GetProcessHeap(), 0, env );
1347 return envp;
1351 /***********************************************************************
1352 * fork_and_exec
1354 * Fork and exec a new Unix binary, checking for errors.
1356 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1357 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1359 int fd[2], stdin_fd = -1, stdout_fd = -1;
1360 int pid, err;
1361 char **argv, **envp;
1363 if (!env) env = GetEnvironmentStringsW();
1365 #ifdef HAVE_PIPE2
1366 if (pipe2( fd, O_CLOEXEC ) == -1)
1367 #endif
1369 if (pipe(fd) == -1)
1371 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1372 return -1;
1374 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1375 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1378 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1380 HANDLE hstdin, hstdout;
1382 if (startup->dwFlags & STARTF_USESTDHANDLES)
1384 hstdin = startup->hStdInput;
1385 hstdout = startup->hStdOutput;
1387 else
1389 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1390 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1393 if (is_console_handle( hstdin ))
1394 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1395 if (is_console_handle( hstdout ))
1396 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1397 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1398 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1401 argv = build_argv( cmdline, 0 );
1402 envp = build_envp( env );
1404 if (!(pid = fork())) /* child */
1406 close( fd[0] );
1408 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1410 int pid;
1411 if (!(pid = fork()))
1413 int fd = open( "/dev/null", O_RDWR );
1414 setsid();
1415 /* close stdin and stdout */
1416 if (fd != -1)
1418 dup2( fd, 0 );
1419 dup2( fd, 1 );
1420 close( fd );
1423 else if (pid != -1) _exit(0); /* parent */
1425 else
1427 if (stdin_fd != -1)
1429 dup2( stdin_fd, 0 );
1430 close( stdin_fd );
1432 if (stdout_fd != -1)
1434 dup2( stdout_fd, 1 );
1435 close( stdout_fd );
1439 /* Reset signals that we previously set to SIG_IGN */
1440 signal( SIGPIPE, SIG_DFL );
1441 signal( SIGCHLD, SIG_DFL );
1443 if (newdir) chdir(newdir);
1445 if (argv && envp) execve( filename, argv, envp );
1446 err = errno;
1447 write( fd[1], &err, sizeof(err) );
1448 _exit(1);
1450 HeapFree( GetProcessHeap(), 0, argv );
1451 HeapFree( GetProcessHeap(), 0, envp );
1452 if (stdin_fd != -1) close( stdin_fd );
1453 if (stdout_fd != -1) close( stdout_fd );
1454 close( fd[1] );
1455 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1457 errno = err;
1458 pid = -1;
1460 if (pid == -1) FILE_SetDosError();
1461 close( fd[0] );
1462 return pid;
1466 static inline DWORD append_string( void **ptr, const WCHAR *str )
1468 DWORD len = strlenW( str );
1469 memcpy( *ptr, str, len * sizeof(WCHAR) );
1470 *ptr = (WCHAR *)*ptr + len;
1471 return len * sizeof(WCHAR);
1474 /***********************************************************************
1475 * create_startup_info
1477 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1478 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1479 const STARTUPINFOW *startup, DWORD *info_size )
1481 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1482 const WCHAR *title;
1483 startup_info_t *info;
1484 DWORD size;
1485 void *ptr;
1486 UNICODE_STRING newdir;
1487 WCHAR imagepath[MAX_PATH];
1488 HANDLE hstdin, hstdout, hstderr;
1490 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1491 lstrcpynW( imagepath, filename, MAX_PATH );
1492 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1493 lstrcpynW( imagepath, filename, MAX_PATH );
1495 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1497 newdir.Buffer = NULL;
1498 if (cur_dir)
1500 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1501 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1502 else
1503 cur_dir = NULL;
1505 if (!cur_dir)
1507 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1508 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1509 else
1510 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1512 title = startup->lpTitle ? startup->lpTitle : imagepath;
1514 size = sizeof(*info);
1515 size += strlenW( cur_dir ) * sizeof(WCHAR);
1516 size += cur_params->DllPath.Length;
1517 size += strlenW( imagepath ) * sizeof(WCHAR);
1518 size += strlenW( cmdline ) * sizeof(WCHAR);
1519 size += strlenW( title ) * sizeof(WCHAR);
1520 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1521 /* FIXME: shellinfo */
1522 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1523 size = (size + 1) & ~1;
1524 *info_size = size;
1526 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1528 info->console_flags = cur_params->ConsoleFlags;
1529 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1530 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1532 if (startup->dwFlags & STARTF_USESTDHANDLES)
1534 hstdin = startup->hStdInput;
1535 hstdout = startup->hStdOutput;
1536 hstderr = startup->hStdError;
1538 else
1540 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1541 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1542 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1544 info->hstdin = wine_server_obj_handle( hstdin );
1545 info->hstdout = wine_server_obj_handle( hstdout );
1546 info->hstderr = wine_server_obj_handle( hstderr );
1547 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1549 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1550 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1551 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1552 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1554 else
1556 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1557 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1558 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1561 info->x = startup->dwX;
1562 info->y = startup->dwY;
1563 info->xsize = startup->dwXSize;
1564 info->ysize = startup->dwYSize;
1565 info->xchars = startup->dwXCountChars;
1566 info->ychars = startup->dwYCountChars;
1567 info->attribute = startup->dwFillAttribute;
1568 info->flags = startup->dwFlags;
1569 info->show = startup->wShowWindow;
1571 ptr = info + 1;
1572 info->curdir_len = append_string( &ptr, cur_dir );
1573 info->dllpath_len = cur_params->DllPath.Length;
1574 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1575 ptr = (char *)ptr + cur_params->DllPath.Length;
1576 info->imagepath_len = append_string( &ptr, imagepath );
1577 info->cmdline_len = append_string( &ptr, cmdline );
1578 info->title_len = append_string( &ptr, title );
1579 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1580 if (startup->lpReserved2 && startup->cbReserved2)
1582 info->runtime_len = startup->cbReserved2;
1583 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1586 done:
1587 RtlFreeUnicodeString( &newdir );
1588 return info;
1591 /***********************************************************************
1592 * get_alternate_loader
1594 * Get the name of the alternate (32 or 64 bit) Wine loader.
1596 static const char *get_alternate_loader( char **ret_env )
1598 char *env;
1599 const char *loader = NULL;
1600 const char *loader_env = getenv( "WINELOADER" );
1602 *ret_env = NULL;
1604 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1606 if (loader_env)
1608 int len = strlen( loader_env );
1609 if (!is_win64)
1611 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1612 strcpy( env, "WINELOADER=" );
1613 strcat( env, loader_env );
1614 strcat( env, "64" );
1616 else
1618 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1619 strcpy( env, "WINELOADER=" );
1620 strcat( env, loader_env );
1621 len += sizeof("WINELOADER=") - 1;
1622 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1624 if (!loader)
1626 if ((loader = strrchr( env, '/' ))) loader++;
1627 else loader = env;
1629 *ret_env = env;
1631 if (!loader) loader = is_win64 ? "wine" : "wine64";
1632 return loader;
1635 /***********************************************************************
1636 * create_process
1638 * Create a new process. If hFile is a valid handle we have an exe
1639 * file, otherwise it is a Winelib app.
1641 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1642 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1643 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1644 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1645 const struct binary_info *binary_info, int exec_only )
1647 BOOL ret, success = FALSE;
1648 HANDLE process_info;
1649 WCHAR *env_end;
1650 char *winedebug = NULL;
1651 char *wineloader = NULL;
1652 const char *loader = NULL;
1653 char **argv;
1654 startup_info_t *startup_info;
1655 DWORD startup_info_size;
1656 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1657 pid_t pid;
1658 int err;
1660 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1662 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename) );
1663 SetLastError( ERROR_BAD_EXE_FORMAT );
1664 return FALSE;
1667 RtlAcquirePebLock();
1669 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1670 &startup_info_size )))
1672 RtlReleasePebLock();
1673 return FALSE;
1675 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1676 env_end = env;
1677 while (*env_end)
1679 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1680 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1682 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1683 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1684 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1686 env_end += strlenW(env_end) + 1;
1688 env_end++;
1690 /* create the socket for the new process */
1692 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1694 RtlReleasePebLock();
1695 HeapFree( GetProcessHeap(), 0, winedebug );
1696 HeapFree( GetProcessHeap(), 0, startup_info );
1697 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1698 return FALSE;
1700 wine_server_send_fd( socketfd[1] );
1701 close( socketfd[1] );
1703 /* create the process on the server side */
1705 SERVER_START_REQ( new_process )
1707 req->inherit_all = inherit;
1708 req->create_flags = flags;
1709 req->socket_fd = socketfd[1];
1710 req->exe_file = wine_server_obj_handle( hFile );
1711 req->process_access = PROCESS_ALL_ACCESS;
1712 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1713 req->thread_access = THREAD_ALL_ACCESS;
1714 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1715 req->info_size = startup_info_size;
1717 wine_server_add_data( req, startup_info, startup_info_size );
1718 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1719 if ((ret = !wine_server_call_err( req )))
1721 info->dwProcessId = (DWORD)reply->pid;
1722 info->dwThreadId = (DWORD)reply->tid;
1723 info->hProcess = wine_server_ptr_handle( reply->phandle );
1724 info->hThread = wine_server_ptr_handle( reply->thandle );
1726 process_info = wine_server_ptr_handle( reply->info );
1728 SERVER_END_REQ;
1730 RtlReleasePebLock();
1731 if (!ret)
1733 close( socketfd[0] );
1734 HeapFree( GetProcessHeap(), 0, startup_info );
1735 HeapFree( GetProcessHeap(), 0, winedebug );
1736 return FALSE;
1739 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1741 if (startup_info->hstdin)
1742 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1743 FILE_READ_DATA, &stdin_fd, NULL );
1744 if (startup_info->hstdout)
1745 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1746 FILE_WRITE_DATA, &stdout_fd, NULL );
1748 HeapFree( GetProcessHeap(), 0, startup_info );
1750 /* create the child process */
1751 argv = build_argv( cmd_line, 1 );
1753 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1754 loader = get_alternate_loader( &wineloader );
1756 if (exec_only || !(pid = fork())) /* child */
1758 char preloader_reserve[64], socket_env[64];
1760 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1762 if (!(pid = fork()))
1764 int fd = open( "/dev/null", O_RDWR );
1765 setsid();
1766 /* close stdin and stdout */
1767 if (fd != -1)
1769 dup2( fd, 0 );
1770 dup2( fd, 1 );
1771 close( fd );
1774 else if (pid != -1) _exit(0); /* parent */
1776 else
1778 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1779 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1782 if (stdin_fd != -1) close( stdin_fd );
1783 if (stdout_fd != -1) close( stdout_fd );
1785 /* Reset signals that we previously set to SIG_IGN */
1786 signal( SIGPIPE, SIG_DFL );
1787 signal( SIGCHLD, SIG_DFL );
1789 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1790 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1791 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1793 putenv( preloader_reserve );
1794 putenv( socket_env );
1795 if (winedebug) putenv( winedebug );
1796 if (wineloader) putenv( wineloader );
1797 if (unixdir) chdir(unixdir);
1799 if (argv) wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1800 _exit(1);
1803 /* this is the parent */
1805 if (stdin_fd != -1) close( stdin_fd );
1806 if (stdout_fd != -1) close( stdout_fd );
1807 close( socketfd[0] );
1808 HeapFree( GetProcessHeap(), 0, argv );
1809 HeapFree( GetProcessHeap(), 0, winedebug );
1810 HeapFree( GetProcessHeap(), 0, wineloader );
1811 if (pid == -1)
1813 FILE_SetDosError();
1814 goto error;
1817 /* wait for the new process info to be ready */
1819 WaitForSingleObject( process_info, INFINITE );
1820 SERVER_START_REQ( get_new_process_info )
1822 req->info = wine_server_obj_handle( process_info );
1823 wine_server_call( req );
1824 success = reply->success;
1825 err = reply->exit_code;
1827 SERVER_END_REQ;
1829 if (!success)
1831 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1832 goto error;
1834 CloseHandle( process_info );
1835 return success;
1837 error:
1838 CloseHandle( process_info );
1839 CloseHandle( info->hProcess );
1840 CloseHandle( info->hThread );
1841 info->hProcess = info->hThread = 0;
1842 info->dwProcessId = info->dwThreadId = 0;
1843 return FALSE;
1847 /***********************************************************************
1848 * create_vdm_process
1850 * Create a new VDM process for a 16-bit or DOS application.
1852 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1853 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1854 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1855 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1856 const struct binary_info *binary_info, int exec_only )
1858 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1860 BOOL ret;
1861 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1862 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1864 if (!new_cmd_line)
1866 SetLastError( ERROR_OUTOFMEMORY );
1867 return FALSE;
1869 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1870 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1871 flags, startup, info, unixdir, binary_info, exec_only );
1872 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1873 return ret;
1877 /***********************************************************************
1878 * create_cmd_process
1880 * Create a new cmd shell process for a .BAT file.
1882 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1883 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1884 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1885 LPPROCESS_INFORMATION info )
1888 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1889 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1890 WCHAR comspec[MAX_PATH];
1891 WCHAR *newcmdline;
1892 BOOL ret;
1894 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1895 return FALSE;
1896 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1897 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1898 return FALSE;
1900 strcpyW( newcmdline, comspec );
1901 strcatW( newcmdline, slashcW );
1902 strcatW( newcmdline, cmd_line );
1903 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1904 flags, env, cur_dir, startup, info );
1905 HeapFree( GetProcessHeap(), 0, newcmdline );
1906 return ret;
1910 /*************************************************************************
1911 * get_file_name
1913 * Helper for CreateProcess: retrieve the file name to load from the
1914 * app name and command line. Store the file name in buffer, and
1915 * return a possibly modified command line.
1916 * Also returns a handle to the opened file if it's a Windows binary.
1918 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1919 int buflen, HANDLE *handle, struct binary_info *binary_info )
1921 static const WCHAR quotesW[] = {'"','%','s','"',0};
1923 WCHAR *name, *pos, *first_space, *ret = NULL;
1924 const WCHAR *p;
1926 /* if we have an app name, everything is easy */
1928 if (appname)
1930 /* use the unmodified app name as file name */
1931 lstrcpynW( buffer, appname, buflen );
1932 *handle = open_exe_file( buffer, binary_info );
1933 if (!(ret = cmdline) || !cmdline[0])
1935 /* no command-line, create one */
1936 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1937 sprintfW( ret, quotesW, appname );
1939 return ret;
1942 /* first check for a quoted file name */
1944 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1946 int len = p - cmdline - 1;
1947 /* extract the quoted portion as file name */
1948 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1949 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1950 name[len] = 0;
1952 if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
1954 if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
1955 *handle = 0;
1957 ret = cmdline; /* no change necessary */
1958 goto done;
1961 /* now try the command-line word by word */
1963 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1964 return NULL;
1965 pos = name;
1966 p = cmdline;
1967 first_space = NULL;
1969 for (;;)
1971 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
1972 *pos = 0;
1973 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1975 ret = cmdline;
1976 break;
1978 if (!first_space) first_space = pos;
1979 if (!(*pos++ = *p++)) break;
1982 if (!ret)
1984 if (first_space) *first_space = 0; /* try only the first word as a builtin */
1985 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
1987 *handle = 0;
1988 ret = cmdline;
1990 else SetLastError( ERROR_FILE_NOT_FOUND );
1992 else if (first_space) /* build a new command-line with quotes */
1994 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1995 goto done;
1996 sprintfW( ret, quotesW, name );
1997 strcatW( ret, p );
2000 done:
2001 HeapFree( GetProcessHeap(), 0, name );
2002 return ret;
2006 /**********************************************************************
2007 * CreateProcessA (KERNEL32.@)
2009 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2010 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2011 DWORD flags, LPVOID env, LPCSTR cur_dir,
2012 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2014 BOOL ret = FALSE;
2015 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2016 UNICODE_STRING desktopW, titleW;
2017 STARTUPINFOW infoW;
2019 desktopW.Buffer = NULL;
2020 titleW.Buffer = NULL;
2021 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2022 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2023 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2025 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2026 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2028 memcpy( &infoW, startup_info, sizeof(infoW) );
2029 infoW.lpDesktop = desktopW.Buffer;
2030 infoW.lpTitle = titleW.Buffer;
2032 if (startup_info->lpReserved)
2033 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2034 debugstr_a(startup_info->lpReserved));
2036 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
2037 inherit, flags, env, cur_dirW, &infoW, info );
2038 done:
2039 HeapFree( GetProcessHeap(), 0, app_nameW );
2040 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2041 HeapFree( GetProcessHeap(), 0, cur_dirW );
2042 RtlFreeUnicodeString( &desktopW );
2043 RtlFreeUnicodeString( &titleW );
2044 return ret;
2048 /**********************************************************************
2049 * CreateProcessW (KERNEL32.@)
2051 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2052 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2053 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2054 LPPROCESS_INFORMATION info )
2056 BOOL retv = FALSE;
2057 HANDLE hFile = 0;
2058 char *unixdir = NULL;
2059 WCHAR name[MAX_PATH];
2060 WCHAR *tidy_cmdline, *p, *envW = env;
2061 struct binary_info binary_info;
2063 /* Process the AppName and/or CmdLine to get module name and path */
2065 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2067 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2068 &hFile, &binary_info )))
2069 return FALSE;
2070 if (hFile == INVALID_HANDLE_VALUE) goto done;
2072 /* Warn if unsupported features are used */
2074 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2075 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2076 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2077 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2078 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2080 if (cur_dir)
2082 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2084 SetLastError(ERROR_DIRECTORY);
2085 goto done;
2088 else
2090 WCHAR buf[MAX_PATH];
2091 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2094 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2096 char *p = env;
2097 DWORD lenW;
2099 while (*p) p += strlen(p) + 1;
2100 p++; /* final null */
2101 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2102 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2103 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2104 flags |= CREATE_UNICODE_ENVIRONMENT;
2107 info->hThread = info->hProcess = 0;
2108 info->dwProcessId = info->dwThreadId = 0;
2110 if (binary_info.flags & BINARY_FLAG_DLL)
2112 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2113 SetLastError( ERROR_BAD_EXE_FORMAT );
2115 else switch (binary_info.type)
2117 case BINARY_PE:
2118 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2119 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2120 binary_info.res_start, binary_info.res_end );
2121 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2122 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2123 break;
2124 case BINARY_OS216:
2125 case BINARY_WIN16:
2126 case BINARY_DOS:
2127 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2128 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2129 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2130 break;
2131 case BINARY_UNIX_LIB:
2132 TRACE( "starting %s as %d-bit Winelib app\n",
2133 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2134 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2135 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2136 break;
2137 case BINARY_UNKNOWN:
2138 /* check for .com or .bat extension */
2139 if ((p = strrchrW( name, '.' )))
2141 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2143 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2144 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2145 inherit, flags, startup_info, info, unixdir,
2146 &binary_info, FALSE );
2147 break;
2149 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2151 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2152 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2153 inherit, flags, startup_info, info );
2154 break;
2157 /* fall through */
2158 case BINARY_UNIX_EXE:
2160 /* unknown file, try as unix executable */
2161 char *unix_name;
2163 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2165 if ((unix_name = wine_get_unix_file_name( name )))
2167 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2168 HeapFree( GetProcessHeap(), 0, unix_name );
2171 break;
2173 if (hFile) CloseHandle( hFile );
2175 done:
2176 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2177 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2178 HeapFree( GetProcessHeap(), 0, unixdir );
2179 if (retv)
2180 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2181 return retv;
2185 /**********************************************************************
2186 * exec_process
2188 static void exec_process( LPCWSTR name )
2190 HANDLE hFile;
2191 WCHAR *p;
2192 STARTUPINFOW startup_info;
2193 PROCESS_INFORMATION info;
2194 struct binary_info binary_info;
2196 hFile = open_exe_file( name, &binary_info );
2197 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2199 memset( &startup_info, 0, sizeof(startup_info) );
2200 startup_info.cb = sizeof(startup_info);
2202 /* Determine executable type */
2204 if (binary_info.flags & BINARY_FLAG_DLL) return;
2205 switch (binary_info.type)
2207 case BINARY_PE:
2208 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2209 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2210 binary_info.res_start, binary_info.res_end );
2211 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2212 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2213 break;
2214 case BINARY_UNIX_LIB:
2215 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2216 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2217 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2218 break;
2219 case BINARY_UNKNOWN:
2220 /* check for .com or .pif extension */
2221 if (!(p = strrchrW( name, '.' ))) break;
2222 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2223 /* fall through */
2224 case BINARY_OS216:
2225 case BINARY_WIN16:
2226 case BINARY_DOS:
2227 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2228 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2229 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2230 break;
2231 default:
2232 break;
2234 CloseHandle( hFile );
2238 /***********************************************************************
2239 * wait_input_idle
2241 * Wrapper to call WaitForInputIdle USER function
2243 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2245 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2247 HMODULE mod = GetModuleHandleA( "user32.dll" );
2248 if (mod)
2250 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2251 if (ptr) return ptr( process, timeout );
2253 return 0;
2257 /***********************************************************************
2258 * WinExec (KERNEL32.@)
2260 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2262 PROCESS_INFORMATION info;
2263 STARTUPINFOA startup;
2264 char *cmdline;
2265 UINT ret;
2267 memset( &startup, 0, sizeof(startup) );
2268 startup.cb = sizeof(startup);
2269 startup.dwFlags = STARTF_USESHOWWINDOW;
2270 startup.wShowWindow = nCmdShow;
2272 /* cmdline needs to be writable for CreateProcess */
2273 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2274 strcpy( cmdline, lpCmdLine );
2276 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2277 0, NULL, NULL, &startup, &info ))
2279 /* Give 30 seconds to the app to come up */
2280 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2281 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2282 ret = 33;
2283 /* Close off the handles */
2284 CloseHandle( info.hThread );
2285 CloseHandle( info.hProcess );
2287 else if ((ret = GetLastError()) >= 32)
2289 FIXME("Strange error set by CreateProcess: %d\n", ret );
2290 ret = 11;
2292 HeapFree( GetProcessHeap(), 0, cmdline );
2293 return ret;
2297 /**********************************************************************
2298 * LoadModule (KERNEL32.@)
2300 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2302 LOADPARMS32 *params = paramBlock;
2303 PROCESS_INFORMATION info;
2304 STARTUPINFOA startup;
2305 HINSTANCE hInstance;
2306 LPSTR cmdline, p;
2307 char filename[MAX_PATH];
2308 BYTE len;
2310 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2312 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2313 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2314 return ULongToHandle(GetLastError());
2316 len = (BYTE)params->lpCmdLine[0];
2317 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2318 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2320 strcpy( cmdline, filename );
2321 p = cmdline + strlen(cmdline);
2322 *p++ = ' ';
2323 memcpy( p, params->lpCmdLine + 1, len );
2324 p[len] = 0;
2326 memset( &startup, 0, sizeof(startup) );
2327 startup.cb = sizeof(startup);
2328 if (params->lpCmdShow)
2330 startup.dwFlags = STARTF_USESHOWWINDOW;
2331 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2334 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2335 params->lpEnvAddress, NULL, &startup, &info ))
2337 /* Give 30 seconds to the app to come up */
2338 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2339 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2340 hInstance = (HINSTANCE)33;
2341 /* Close off the handles */
2342 CloseHandle( info.hThread );
2343 CloseHandle( info.hProcess );
2345 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2347 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2348 hInstance = (HINSTANCE)11;
2351 HeapFree( GetProcessHeap(), 0, cmdline );
2352 return hInstance;
2356 /******************************************************************************
2357 * TerminateProcess (KERNEL32.@)
2359 * Terminates a process.
2361 * PARAMS
2362 * handle [I] Process to terminate.
2363 * exit_code [I] Exit code.
2365 * RETURNS
2366 * Success: TRUE.
2367 * Failure: FALSE, check GetLastError().
2369 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2371 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2372 if (status) SetLastError( RtlNtStatusToDosError(status) );
2373 return !status;
2376 /***********************************************************************
2377 * ExitProcess (KERNEL32.@)
2379 * Exits the current process.
2381 * PARAMS
2382 * status [I] Status code to exit with.
2384 * RETURNS
2385 * Nothing.
2387 #ifdef __i386__
2388 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2389 "pushl %ebp\n\t"
2390 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2391 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2392 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2393 "pushl 8(%ebp)\n\t"
2394 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2395 "leave\n\t"
2396 "ret $4" )
2398 void WINAPI process_ExitProcess( DWORD status )
2400 LdrShutdownProcess();
2401 NtTerminateProcess(GetCurrentProcess(), status);
2402 exit(status);
2405 #else
2407 void WINAPI ExitProcess( DWORD status )
2409 LdrShutdownProcess();
2410 NtTerminateProcess(GetCurrentProcess(), status);
2411 exit(status);
2414 #endif
2416 /***********************************************************************
2417 * GetExitCodeProcess [KERNEL32.@]
2419 * Gets termination status of specified process.
2421 * PARAMS
2422 * hProcess [in] Handle to the process.
2423 * lpExitCode [out] Address to receive termination status.
2425 * RETURNS
2426 * Success: TRUE
2427 * Failure: FALSE
2429 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2431 NTSTATUS status;
2432 PROCESS_BASIC_INFORMATION pbi;
2434 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2435 sizeof(pbi), NULL);
2436 if (status == STATUS_SUCCESS)
2438 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2439 return TRUE;
2441 SetLastError( RtlNtStatusToDosError(status) );
2442 return FALSE;
2446 /***********************************************************************
2447 * SetErrorMode (KERNEL32.@)
2449 UINT WINAPI SetErrorMode( UINT mode )
2451 UINT old;
2453 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2454 &old, sizeof(old), NULL );
2455 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2456 &mode, sizeof(mode) );
2457 return old;
2460 /***********************************************************************
2461 * GetErrorMode (KERNEL32.@)
2463 UINT WINAPI GetErrorMode( void )
2465 UINT mode;
2467 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2468 &mode, sizeof(mode), NULL );
2469 return mode;
2472 /**********************************************************************
2473 * TlsAlloc [KERNEL32.@]
2475 * Allocates a thread local storage index.
2477 * RETURNS
2478 * Success: TLS index.
2479 * Failure: 0xFFFFFFFF
2481 DWORD WINAPI TlsAlloc( void )
2483 DWORD index;
2484 PEB * const peb = NtCurrentTeb()->Peb;
2486 RtlAcquirePebLock();
2487 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2488 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2489 else
2491 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2492 if (index != ~0U)
2494 if (!NtCurrentTeb()->TlsExpansionSlots &&
2495 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2496 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2498 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2499 index = ~0U;
2500 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2502 else
2504 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2505 index += TLS_MINIMUM_AVAILABLE;
2508 else SetLastError( ERROR_NO_MORE_ITEMS );
2510 RtlReleasePebLock();
2511 return index;
2515 /**********************************************************************
2516 * TlsFree [KERNEL32.@]
2518 * Releases a thread local storage index, making it available for reuse.
2520 * PARAMS
2521 * index [in] TLS index to free.
2523 * RETURNS
2524 * Success: TRUE
2525 * Failure: FALSE
2527 BOOL WINAPI TlsFree( DWORD index )
2529 BOOL ret;
2531 RtlAcquirePebLock();
2532 if (index >= TLS_MINIMUM_AVAILABLE)
2534 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2535 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2537 else
2539 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2540 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2542 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2543 else SetLastError( ERROR_INVALID_PARAMETER );
2544 RtlReleasePebLock();
2545 return ret;
2549 /**********************************************************************
2550 * TlsGetValue [KERNEL32.@]
2552 * Gets value in a thread's TLS slot.
2554 * PARAMS
2555 * index [in] TLS index to retrieve value for.
2557 * RETURNS
2558 * Success: Value stored in calling thread's TLS slot for index.
2559 * Failure: 0 and GetLastError() returns NO_ERROR.
2561 LPVOID WINAPI TlsGetValue( DWORD index )
2563 LPVOID ret;
2565 if (index < TLS_MINIMUM_AVAILABLE)
2567 ret = NtCurrentTeb()->TlsSlots[index];
2569 else
2571 index -= TLS_MINIMUM_AVAILABLE;
2572 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2574 SetLastError( ERROR_INVALID_PARAMETER );
2575 return NULL;
2577 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2578 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2580 SetLastError( ERROR_SUCCESS );
2581 return ret;
2585 /**********************************************************************
2586 * TlsSetValue [KERNEL32.@]
2588 * Stores a value in the thread's TLS slot.
2590 * PARAMS
2591 * index [in] TLS index to set value for.
2592 * value [in] Value to be stored.
2594 * RETURNS
2595 * Success: TRUE
2596 * Failure: FALSE
2598 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2600 if (index < TLS_MINIMUM_AVAILABLE)
2602 NtCurrentTeb()->TlsSlots[index] = value;
2604 else
2606 index -= TLS_MINIMUM_AVAILABLE;
2607 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2609 SetLastError( ERROR_INVALID_PARAMETER );
2610 return FALSE;
2612 if (!NtCurrentTeb()->TlsExpansionSlots &&
2613 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2614 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2616 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2617 return FALSE;
2619 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2621 return TRUE;
2625 /***********************************************************************
2626 * GetProcessFlags (KERNEL32.@)
2628 DWORD WINAPI GetProcessFlags( DWORD processid )
2630 IMAGE_NT_HEADERS *nt;
2631 DWORD flags = 0;
2633 if (processid && processid != GetCurrentProcessId()) return 0;
2635 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2637 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2638 flags |= PDB32_CONSOLE_PROC;
2640 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2641 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2642 return flags;
2646 /*********************************************************************
2647 * OpenProcess (KERNEL32.@)
2649 * Opens a handle to a process.
2651 * PARAMS
2652 * access [I] Desired access rights assigned to the returned handle.
2653 * inherit [I] Determines whether or not child processes will inherit the handle.
2654 * id [I] Process identifier of the process to get a handle to.
2656 * RETURNS
2657 * Success: Valid handle to the specified process.
2658 * Failure: NULL, check GetLastError().
2660 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2662 NTSTATUS status;
2663 HANDLE handle;
2664 OBJECT_ATTRIBUTES attr;
2665 CLIENT_ID cid;
2667 cid.UniqueProcess = ULongToHandle(id);
2668 cid.UniqueThread = 0; /* FIXME ? */
2670 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2671 attr.RootDirectory = NULL;
2672 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2673 attr.SecurityDescriptor = NULL;
2674 attr.SecurityQualityOfService = NULL;
2675 attr.ObjectName = NULL;
2677 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2679 status = NtOpenProcess(&handle, access, &attr, &cid);
2680 if (status != STATUS_SUCCESS)
2682 SetLastError( RtlNtStatusToDosError(status) );
2683 return NULL;
2685 return handle;
2689 /*********************************************************************
2690 * GetProcessId (KERNEL32.@)
2692 * Gets the a unique identifier of a process.
2694 * PARAMS
2695 * hProcess [I] Handle to the process.
2697 * RETURNS
2698 * Success: TRUE.
2699 * Failure: FALSE, check GetLastError().
2701 * NOTES
2703 * The identifier is unique only on the machine and only until the process
2704 * exits (including system shutdown).
2706 DWORD WINAPI GetProcessId( HANDLE hProcess )
2708 NTSTATUS status;
2709 PROCESS_BASIC_INFORMATION pbi;
2711 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2712 sizeof(pbi), NULL);
2713 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2714 SetLastError( RtlNtStatusToDosError(status) );
2715 return 0;
2719 /*********************************************************************
2720 * CloseHandle (KERNEL32.@)
2722 * Closes a handle.
2724 * PARAMS
2725 * handle [I] Handle to close.
2727 * RETURNS
2728 * Success: TRUE.
2729 * Failure: FALSE, check GetLastError().
2731 BOOL WINAPI CloseHandle( HANDLE handle )
2733 NTSTATUS status;
2735 /* stdio handles need special treatment */
2736 if (handle == (HANDLE)STD_INPUT_HANDLE)
2737 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2738 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2739 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2740 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2741 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2743 if (is_console_handle(handle))
2744 return CloseConsoleHandle(handle);
2746 status = NtClose( handle );
2747 if (status) SetLastError( RtlNtStatusToDosError(status) );
2748 return !status;
2752 /*********************************************************************
2753 * GetHandleInformation (KERNEL32.@)
2755 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2757 OBJECT_DATA_INFORMATION info;
2758 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2760 if (status) SetLastError( RtlNtStatusToDosError(status) );
2761 else if (flags)
2763 *flags = 0;
2764 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2765 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2767 return !status;
2771 /*********************************************************************
2772 * SetHandleInformation (KERNEL32.@)
2774 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2776 OBJECT_DATA_INFORMATION info;
2777 NTSTATUS status;
2779 /* if not setting both fields, retrieve current value first */
2780 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2781 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2783 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2785 SetLastError( RtlNtStatusToDosError(status) );
2786 return FALSE;
2789 if (mask & HANDLE_FLAG_INHERIT)
2790 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2791 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2792 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2794 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2795 if (status) SetLastError( RtlNtStatusToDosError(status) );
2796 return !status;
2800 /*********************************************************************
2801 * DuplicateHandle (KERNEL32.@)
2803 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2804 HANDLE dest_process, HANDLE *dest,
2805 DWORD access, BOOL inherit, DWORD options )
2807 NTSTATUS status;
2809 if (is_console_handle(source))
2811 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2812 if (source_process != dest_process ||
2813 source_process != GetCurrentProcess())
2815 SetLastError(ERROR_INVALID_PARAMETER);
2816 return FALSE;
2818 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2819 return (*dest != INVALID_HANDLE_VALUE);
2821 status = NtDuplicateObject( source_process, source, dest_process, dest,
2822 access, inherit ? OBJ_INHERIT : 0, options );
2823 if (status) SetLastError( RtlNtStatusToDosError(status) );
2824 return !status;
2828 /***********************************************************************
2829 * ConvertToGlobalHandle (KERNEL32.@)
2831 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2833 HANDLE ret = INVALID_HANDLE_VALUE;
2834 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2835 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2836 return ret;
2840 /***********************************************************************
2841 * SetHandleContext (KERNEL32.@)
2843 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2845 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2846 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2847 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2848 return FALSE;
2852 /***********************************************************************
2853 * GetHandleContext (KERNEL32.@)
2855 DWORD WINAPI GetHandleContext(HANDLE hnd)
2857 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2858 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2859 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2860 return 0;
2864 /***********************************************************************
2865 * CreateSocketHandle (KERNEL32.@)
2867 HANDLE WINAPI CreateSocketHandle(void)
2869 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2870 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2871 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2872 return INVALID_HANDLE_VALUE;
2876 /***********************************************************************
2877 * SetPriorityClass (KERNEL32.@)
2879 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2881 NTSTATUS status;
2882 PROCESS_PRIORITY_CLASS ppc;
2884 ppc.Foreground = FALSE;
2885 switch (priorityclass)
2887 case IDLE_PRIORITY_CLASS:
2888 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2889 case BELOW_NORMAL_PRIORITY_CLASS:
2890 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2891 case NORMAL_PRIORITY_CLASS:
2892 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2893 case ABOVE_NORMAL_PRIORITY_CLASS:
2894 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2895 case HIGH_PRIORITY_CLASS:
2896 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2897 case REALTIME_PRIORITY_CLASS:
2898 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2899 default:
2900 SetLastError(ERROR_INVALID_PARAMETER);
2901 return FALSE;
2904 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2905 &ppc, sizeof(ppc));
2907 if (status != STATUS_SUCCESS)
2909 SetLastError( RtlNtStatusToDosError(status) );
2910 return FALSE;
2912 return TRUE;
2916 /***********************************************************************
2917 * GetPriorityClass (KERNEL32.@)
2919 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2921 NTSTATUS status;
2922 PROCESS_BASIC_INFORMATION pbi;
2924 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2925 sizeof(pbi), NULL);
2926 if (status != STATUS_SUCCESS)
2928 SetLastError( RtlNtStatusToDosError(status) );
2929 return 0;
2931 switch (pbi.BasePriority)
2933 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2934 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2935 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2936 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2937 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2938 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2940 SetLastError( ERROR_INVALID_PARAMETER );
2941 return 0;
2945 /***********************************************************************
2946 * SetProcessAffinityMask (KERNEL32.@)
2948 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2950 NTSTATUS status;
2952 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2953 &affmask, sizeof(DWORD_PTR));
2954 if (status)
2956 SetLastError( RtlNtStatusToDosError(status) );
2957 return FALSE;
2959 return TRUE;
2963 /**********************************************************************
2964 * GetProcessAffinityMask (KERNEL32.@)
2966 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2967 PDWORD_PTR lpProcessAffinityMask,
2968 PDWORD_PTR lpSystemAffinityMask )
2970 PROCESS_BASIC_INFORMATION pbi;
2971 NTSTATUS status;
2973 status = NtQueryInformationProcess(hProcess,
2974 ProcessBasicInformation,
2975 &pbi, sizeof(pbi), NULL);
2976 if (status)
2978 SetLastError( RtlNtStatusToDosError(status) );
2979 return FALSE;
2981 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2982 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2983 return TRUE;
2987 /***********************************************************************
2988 * GetProcessVersion (KERNEL32.@)
2990 DWORD WINAPI GetProcessVersion( DWORD pid )
2992 HANDLE process;
2993 NTSTATUS status;
2994 PROCESS_BASIC_INFORMATION pbi;
2995 SIZE_T count;
2996 PEB peb;
2997 IMAGE_DOS_HEADER dos;
2998 IMAGE_NT_HEADERS nt;
2999 DWORD ver = 0;
3001 if (!pid || pid == GetCurrentProcessId())
3003 IMAGE_NT_HEADERS *nt;
3005 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3006 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
3007 nt->OptionalHeader.MinorSubsystemVersion);
3008 return 0;
3011 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3012 if (!process) return 0;
3014 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3015 if (status) goto err;
3017 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3018 if (status || count != sizeof(peb)) goto err;
3020 memset(&dos, 0, sizeof(dos));
3021 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3022 if (status || count != sizeof(dos)) goto err;
3023 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3025 memset(&nt, 0, sizeof(nt));
3026 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3027 if (status || count != sizeof(nt)) goto err;
3028 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3030 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3032 err:
3033 CloseHandle(process);
3035 if (status != STATUS_SUCCESS)
3036 SetLastError(RtlNtStatusToDosError(status));
3038 return ver;
3042 /***********************************************************************
3043 * SetProcessWorkingSetSize [KERNEL32.@]
3044 * Sets the min/max working set sizes for a specified process.
3046 * PARAMS
3047 * hProcess [I] Handle to the process of interest
3048 * minset [I] Specifies minimum working set size
3049 * maxset [I] Specifies maximum working set size
3051 * RETURNS
3052 * Success: TRUE
3053 * Failure: FALSE
3055 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3056 SIZE_T maxset)
3058 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3059 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3060 /* Trim the working set to zero */
3061 /* Swap the process out of physical RAM */
3063 return TRUE;
3066 /***********************************************************************
3067 * GetProcessWorkingSetSize (KERNEL32.@)
3069 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3070 PSIZE_T maxset)
3072 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3073 /* 32 MB working set size */
3074 if (minset) *minset = 32*1024*1024;
3075 if (maxset) *maxset = 32*1024*1024;
3076 return TRUE;
3080 /***********************************************************************
3081 * SetProcessShutdownParameters (KERNEL32.@)
3083 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3085 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3086 shutdown_flags = flags;
3087 shutdown_priority = level;
3088 return TRUE;
3092 /***********************************************************************
3093 * GetProcessShutdownParameters (KERNEL32.@)
3096 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3098 *lpdwLevel = shutdown_priority;
3099 *lpdwFlags = shutdown_flags;
3100 return TRUE;
3104 /***********************************************************************
3105 * GetProcessPriorityBoost (KERNEL32.@)
3107 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3109 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3111 /* Report that no boost is present.. */
3112 *pDisablePriorityBoost = FALSE;
3114 return TRUE;
3117 /***********************************************************************
3118 * SetProcessPriorityBoost (KERNEL32.@)
3120 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3122 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3123 /* Say we can do it. I doubt the program will notice that we don't. */
3124 return TRUE;
3128 /***********************************************************************
3129 * ReadProcessMemory (KERNEL32.@)
3131 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3132 SIZE_T *bytes_read )
3134 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3135 if (status) SetLastError( RtlNtStatusToDosError(status) );
3136 return !status;
3140 /***********************************************************************
3141 * WriteProcessMemory (KERNEL32.@)
3143 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3144 SIZE_T *bytes_written )
3146 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3147 if (status) SetLastError( RtlNtStatusToDosError(status) );
3148 return !status;
3152 /****************************************************************************
3153 * FlushInstructionCache (KERNEL32.@)
3155 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3157 NTSTATUS status;
3158 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3159 if (status) SetLastError( RtlNtStatusToDosError(status) );
3160 return !status;
3164 /******************************************************************
3165 * GetProcessIoCounters (KERNEL32.@)
3167 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3169 NTSTATUS status;
3171 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3172 ioc, sizeof(*ioc), NULL);
3173 if (status) SetLastError( RtlNtStatusToDosError(status) );
3174 return !status;
3177 /******************************************************************
3178 * GetProcessHandleCount (KERNEL32.@)
3180 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3182 NTSTATUS status;
3184 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3185 cnt, sizeof(*cnt), NULL);
3186 if (status) SetLastError( RtlNtStatusToDosError(status) );
3187 return !status;
3190 /******************************************************************
3191 * QueryFullProcessImageNameA (KERNEL32.@)
3193 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3195 BOOL retval;
3196 DWORD pdwSizeW = *pdwSize;
3197 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3199 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3201 if(retval)
3202 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3203 lpExeName, *pdwSize, NULL, NULL));
3204 if(retval)
3205 *pdwSize = strlen(lpExeName);
3207 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3208 return retval;
3211 /******************************************************************
3212 * QueryFullProcessImageNameW (KERNEL32.@)
3214 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3216 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3217 UNICODE_STRING *dynamic_buffer = NULL;
3218 UNICODE_STRING nt_path;
3219 UNICODE_STRING *result = NULL;
3220 NTSTATUS status;
3221 DWORD needed;
3223 RtlInitUnicodeStringEx(&nt_path, NULL);
3224 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3225 * as this is on Wine. */
3226 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3227 sizeof(buffer) - sizeof(WCHAR), &needed);
3228 if (status == STATUS_INFO_LENGTH_MISMATCH)
3230 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3231 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3232 result = dynamic_buffer;
3234 else
3235 result = (PUNICODE_STRING)buffer;
3237 if (status) goto cleanup;
3239 if (dwFlags & PROCESS_NAME_NATIVE)
3241 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3242 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3244 status = STATUS_OBJECT_PATH_NOT_FOUND;
3245 goto cleanup;
3247 result = &nt_path;
3250 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3252 status = STATUS_BUFFER_TOO_SMALL;
3253 goto cleanup;
3256 *pdwSize = result->Length/sizeof(WCHAR);
3257 memcpy( lpExeName, result->Buffer, result->Length );
3258 lpExeName[*pdwSize] = 0;
3260 cleanup:
3261 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3262 RtlFreeUnicodeString(&nt_path);
3263 if (status) SetLastError( RtlNtStatusToDosError(status) );
3264 return !status;
3267 /***********************************************************************
3268 * ProcessIdToSessionId (KERNEL32.@)
3269 * This function is available on Terminal Server 4SP4 and Windows 2000
3271 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3273 /* According to MSDN, if the calling process is not in a terminal
3274 * services environment, then the sessionid returned is zero.
3276 *sessionid_ptr = 0;
3277 return TRUE;
3281 /***********************************************************************
3282 * RegisterServiceProcess (KERNEL32.@)
3284 * A service process calls this function to ensure that it continues to run
3285 * even after a user logged off.
3287 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3289 /* I don't think that Wine needs to do anything in this function */
3290 return 1; /* success */
3294 /**********************************************************************
3295 * IsWow64Process (KERNEL32.@)
3297 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3299 ULONG pbi;
3300 NTSTATUS status;
3302 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3304 if (status != STATUS_SUCCESS)
3306 SetLastError( RtlNtStatusToDosError( status ) );
3307 return FALSE;
3309 *Wow64Process = (pbi != 0);
3310 return TRUE;
3314 /***********************************************************************
3315 * GetCurrentProcess (KERNEL32.@)
3317 * Get a handle to the current process.
3319 * PARAMS
3320 * None.
3322 * RETURNS
3323 * A handle representing the current process.
3325 #undef GetCurrentProcess
3326 HANDLE WINAPI GetCurrentProcess(void)
3328 return (HANDLE)~(ULONG_PTR)0;
3331 /***********************************************************************
3332 * GetLogicalProcessorInformation (KERNEL32.@)
3334 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3336 FIXME("(%p,%p): stub\n", buffer, pBufLen);
3337 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3338 return FALSE;
3341 /***********************************************************************
3342 * GetLogicalProcessorInformationEx (KERNEL32.@)
3344 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer, PDWORD pBufLen)
3346 FIXME("(%u,%p,%p): stub\n", relationship, buffer, pBufLen);
3347 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3348 return FALSE;
3351 /***********************************************************************
3352 * CmdBatNotification (KERNEL32.@)
3354 * Notifies the system that a batch file has started or finished.
3356 * PARAMS
3357 * bBatchRunning [I] TRUE if a batch file has started or
3358 * FALSE if a batch file has finished executing.
3360 * RETURNS
3361 * Unknown.
3363 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3365 FIXME("%d\n", bBatchRunning);
3366 return FALSE;
3370 /***********************************************************************
3371 * RegisterApplicationRestart (KERNEL32.@)
3373 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3375 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3377 return S_OK;
3380 /**********************************************************************
3381 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3383 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3385 FIXME("stub\n");
3386 return 0;
3389 /**********************************************************************
3390 * GetSystemDEPPolicy (KERNEL32.@)
3392 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3394 FIXME("stub\n");
3395 return OptIn;