kernel32: Make sure we always have a valid process title.
[wine/multimedia.git] / dlls / kernel32 / process.c
blobcc2a6ba6a0a685c2435b38e1c3ea16adc1905527
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 UINT process_error_mode;
75 static DWORD shutdown_flags = 0;
76 static DWORD shutdown_priority = 0x280;
77 static BOOL is_wow64;
78 static const int is_win64 = (sizeof(void *) > sizeof(int));
80 HMODULE kernel32_handle = 0;
82 const WCHAR *DIR_Windows = NULL;
83 const WCHAR *DIR_System = NULL;
84 const WCHAR *DIR_SysWow64 = NULL;
86 /* Process flags */
87 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
88 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
89 #define PDB32_DOS_PROC 0x0010 /* Dos process */
90 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
91 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
92 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
94 static const WCHAR exeW[] = {'.','e','x','e',0};
95 static const WCHAR comW[] = {'.','c','o','m',0};
96 static const WCHAR batW[] = {'.','b','a','t',0};
97 static const WCHAR cmdW[] = {'.','c','m','d',0};
98 static const WCHAR pifW[] = {'.','p','i','f',0};
99 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
101 static void exec_process( LPCWSTR name );
103 extern void SHELL_LoadRegistry(void);
106 /***********************************************************************
107 * contains_path
109 static inline int contains_path( LPCWSTR name )
111 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
115 /***********************************************************************
116 * is_special_env_var
118 * Check if an environment variable needs to be handled specially when
119 * passed through the Unix environment (i.e. prefixed with "WINE").
121 static inline int is_special_env_var( const char *var )
123 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
124 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
125 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
126 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
127 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
131 /***********************************************************************
132 * is_path_prefix
134 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
136 unsigned int len = strlenW( prefix );
138 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
139 while (filename[len] == '\\') len++;
140 return len;
144 /***************************************************************************
145 * get_builtin_path
147 * Get the path of a builtin module when the native file does not exist.
149 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
150 UINT size, struct binary_info *binary_info )
152 WCHAR *file_part;
153 UINT len;
154 void *redir_disabled = 0;
155 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
157 /* builtin names cannot be empty or contain spaces */
158 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
160 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
161 Wow64RevertWow64FsRedirection( redir_disabled );
163 if (contains_path( libname ))
165 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
166 filename, &file_part ) > size * sizeof(WCHAR))
167 return FALSE; /* too long */
169 if ((len = is_path_prefix( DIR_System, filename )))
171 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
173 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
175 flags = 0;
177 else return FALSE;
179 if (filename + len != file_part) return FALSE;
181 else
183 len = strlenW( DIR_System );
184 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
185 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
186 file_part = filename + len;
187 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
188 strcpyW( file_part, libname );
189 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
191 if (ext && !strchrW( file_part, '.' ))
193 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
194 return FALSE; /* too long */
195 strcatW( file_part, ext );
197 binary_info->type = BINARY_UNIX_LIB;
198 binary_info->flags = flags;
199 binary_info->res_start = NULL;
200 binary_info->res_end = NULL;
201 return TRUE;
205 /***********************************************************************
206 * open_exe_file
208 * Open a specific exe file, taking load order into account.
209 * Returns the file handle or 0 for a builtin exe.
211 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
213 HANDLE handle;
215 TRACE("looking for %s\n", debugstr_w(name) );
217 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
218 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
220 WCHAR buffer[MAX_PATH];
221 /* file doesn't exist, check for builtin */
222 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
223 handle = 0;
225 else MODULE_get_binary_info( handle, binary_info );
227 return handle;
231 /***********************************************************************
232 * find_exe_file
234 * Open an exe file, and return the full name and file handle.
235 * Returns FALSE if file could not be found.
236 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
237 * If file is a builtin exe, returns TRUE and sets handle to 0.
239 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
240 HANDLE *handle, struct binary_info *binary_info )
242 TRACE("looking for %s\n", debugstr_w(name) );
244 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
246 if (contains_path( name ) && get_builtin_path( name, exeW, buffer, buflen, binary_info ))
248 *handle = 0;
249 return TRUE;
251 /* no builtin found, try native without extension in case it is a Unix app */
252 if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
255 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
256 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
257 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
259 MODULE_get_binary_info( *handle, binary_info );
260 return TRUE;
262 return FALSE;
266 /***********************************************************************
267 * build_initial_environment
269 * Build the Win32 environment from the Unix environment
271 static BOOL build_initial_environment(void)
273 SIZE_T size = 1;
274 char **e;
275 WCHAR *p, *endptr;
276 void *ptr;
277 char **env = __wine_get_main_environment();
279 /* Compute the total size of the Unix environment */
280 for (e = env; *e; e++)
282 if (is_special_env_var( *e )) continue;
283 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
285 size *= sizeof(WCHAR);
287 /* Now allocate the environment */
288 ptr = NULL;
289 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
290 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
291 return FALSE;
293 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
294 endptr = p + size / sizeof(WCHAR);
296 /* And fill it with the Unix environment */
297 for (e = env; *e; e++)
299 char *str = *e;
301 /* skip Unix special variables and use the Wine variants instead */
302 if (!strncmp( str, "WINE", 4 ))
304 if (is_special_env_var( str + 4 )) str += 4;
305 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
307 else if (is_special_env_var( str )) continue; /* skip it */
309 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
310 p += strlenW(p) + 1;
312 *p = 0;
313 return TRUE;
317 /***********************************************************************
318 * set_registry_variables
320 * Set environment variables by enumerating the values of a key;
321 * helper for set_registry_environment().
322 * Note that Windows happily truncates the value if it's too big.
324 static void set_registry_variables( HANDLE hkey, ULONG type )
326 static const WCHAR pathW[] = {'P','A','T','H'};
327 static const WCHAR sep[] = {';',0};
328 UNICODE_STRING env_name, env_value;
329 NTSTATUS status;
330 DWORD size;
331 int index;
332 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
333 WCHAR tmpbuf[1024];
334 UNICODE_STRING tmp;
335 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
337 tmp.Buffer = tmpbuf;
338 tmp.MaximumLength = sizeof(tmpbuf);
340 for (index = 0; ; index++)
342 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
343 buffer, sizeof(buffer), &size );
344 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
345 break;
346 if (info->Type != type)
347 continue;
348 env_name.Buffer = info->Name;
349 env_name.Length = env_name.MaximumLength = info->NameLength;
350 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
351 env_value.Length = info->DataLength;
352 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
353 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
354 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
355 if (!env_value.Length) continue;
356 if (info->Type == REG_EXPAND_SZ)
358 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
359 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
360 RtlCopyUnicodeString( &env_value, &tmp );
362 /* PATH is magic */
363 if (env_name.Length == sizeof(pathW) &&
364 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
365 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
367 RtlAppendUnicodeToString( &tmp, sep );
368 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
369 RtlCopyUnicodeString( &env_value, &tmp );
371 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
376 /***********************************************************************
377 * set_registry_environment
379 * Set the environment variables specified in the registry.
381 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
382 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
383 * on the order in which the variables are processed. But on Windows it
384 * does not really matter since they only use %SystemDrive% and
385 * %SystemRoot% which are predefined. But Wine defines these in the
386 * registry, so we need two passes.
388 static BOOL set_registry_environment( BOOL volatile_only )
390 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
391 'S','y','s','t','e','m','\\',
392 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
393 'C','o','n','t','r','o','l','\\',
394 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
395 'E','n','v','i','r','o','n','m','e','n','t',0};
396 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
397 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};
399 OBJECT_ATTRIBUTES attr;
400 UNICODE_STRING nameW;
401 HANDLE hkey;
402 BOOL ret = FALSE;
404 attr.Length = sizeof(attr);
405 attr.RootDirectory = 0;
406 attr.ObjectName = &nameW;
407 attr.Attributes = 0;
408 attr.SecurityDescriptor = NULL;
409 attr.SecurityQualityOfService = NULL;
411 /* first the system environment variables */
412 RtlInitUnicodeString( &nameW, env_keyW );
413 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
415 set_registry_variables( hkey, REG_SZ );
416 set_registry_variables( hkey, REG_EXPAND_SZ );
417 NtClose( hkey );
418 ret = TRUE;
421 /* then the ones for the current user */
422 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
423 RtlInitUnicodeString( &nameW, envW );
424 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
426 set_registry_variables( hkey, REG_SZ );
427 set_registry_variables( hkey, REG_EXPAND_SZ );
428 NtClose( hkey );
431 RtlInitUnicodeString( &nameW, volatile_envW );
432 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
434 set_registry_variables( hkey, REG_SZ );
435 set_registry_variables( hkey, REG_EXPAND_SZ );
436 NtClose( hkey );
439 NtClose( attr.RootDirectory );
440 return ret;
444 /***********************************************************************
445 * get_reg_value
447 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
449 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
450 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
451 DWORD len, size = sizeof(buffer);
452 WCHAR *ret = NULL;
453 UNICODE_STRING nameW;
455 RtlInitUnicodeString( &nameW, name );
456 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
457 return NULL;
459 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
460 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
462 if (info->Type == REG_EXPAND_SZ)
464 UNICODE_STRING value, expanded;
466 value.MaximumLength = len * sizeof(WCHAR);
467 value.Buffer = (WCHAR *)info->Data;
468 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
469 value.Length = len * sizeof(WCHAR);
470 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
471 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
472 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
473 else RtlFreeUnicodeString( &expanded );
475 else if (info->Type == REG_SZ)
477 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
479 memcpy( ret, info->Data, len * sizeof(WCHAR) );
480 ret[len] = 0;
483 return ret;
487 /***********************************************************************
488 * set_additional_environment
490 * Set some additional environment variables not specified in the registry.
492 static void set_additional_environment(void)
494 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
495 'S','o','f','t','w','a','r','e','\\',
496 'M','i','c','r','o','s','o','f','t','\\',
497 'W','i','n','d','o','w','s',' ','N','T','\\',
498 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
499 'P','r','o','f','i','l','e','L','i','s','t',0};
500 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
501 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
502 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
503 OBJECT_ATTRIBUTES attr;
504 UNICODE_STRING nameW;
505 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
506 HANDLE hkey;
507 DWORD len;
509 /* set the ALLUSERSPROFILE variables */
511 attr.Length = sizeof(attr);
512 attr.RootDirectory = 0;
513 attr.ObjectName = &nameW;
514 attr.Attributes = 0;
515 attr.SecurityDescriptor = NULL;
516 attr.SecurityQualityOfService = NULL;
517 RtlInitUnicodeString( &nameW, profile_keyW );
518 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
520 profile_dir = get_reg_value( hkey, profiles_valueW );
521 all_users_dir = get_reg_value( hkey, all_users_valueW );
522 NtClose( hkey );
525 if (profile_dir && all_users_dir)
527 WCHAR *value, *p;
529 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
530 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
531 strcpyW( value, profile_dir );
532 p = value + strlenW(value);
533 if (p > value && p[-1] != '\\') *p++ = '\\';
534 strcpyW( p, all_users_dir );
535 SetEnvironmentVariableW( allusersW, value );
536 HeapFree( GetProcessHeap(), 0, value );
539 HeapFree( GetProcessHeap(), 0, all_users_dir );
540 HeapFree( GetProcessHeap(), 0, profile_dir );
543 /***********************************************************************
544 * set_library_wargv
546 * Set the Wine library Unicode argv global variables.
548 static void set_library_wargv( char **argv )
550 int argc;
551 char *q;
552 WCHAR *p;
553 WCHAR **wargv;
554 DWORD total = 0;
556 for (argc = 0; argv[argc]; argc++)
557 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
559 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
560 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
561 p = (WCHAR *)(wargv + argc + 1);
562 for (argc = 0; argv[argc]; argc++)
564 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
565 wargv[argc] = p;
566 p += reslen;
567 total -= reslen;
569 wargv[argc] = NULL;
571 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
573 for (argc = 0; wargv[argc]; argc++)
574 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
576 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
577 q = (char *)(argv + argc + 1);
578 for (argc = 0; wargv[argc]; argc++)
580 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
581 argv[argc] = q;
582 q += reslen;
583 total -= reslen;
585 argv[argc] = NULL;
587 __wine_main_argc = argc;
588 __wine_main_argv = argv;
589 __wine_main_wargv = wargv;
593 /***********************************************************************
594 * update_library_argv0
596 * Update the argv[0] global variable with the binary we have found.
598 static void update_library_argv0( const WCHAR *argv0 )
600 DWORD len = strlenW( argv0 );
602 if (len > strlenW( __wine_main_wargv[0] ))
604 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
606 strcpyW( __wine_main_wargv[0], argv0 );
608 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
609 if (len > strlen( __wine_main_argv[0] ) + 1)
611 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
613 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
617 /***********************************************************************
618 * build_command_line
620 * Build the command line of a process from the argv array.
622 * Note that it does NOT necessarily include the file name.
623 * Sometimes we don't even have any command line options at all.
625 * We must quote and escape characters so that the argv array can be rebuilt
626 * from the command line:
627 * - spaces and tabs must be quoted
628 * 'a b' -> '"a b"'
629 * - quotes must be escaped
630 * '"' -> '\"'
631 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
632 * resulting in an odd number of '\' followed by a '"'
633 * '\"' -> '\\\"'
634 * '\\"' -> '\\\\\"'
635 * - '\'s that are not followed by a '"' can be left as is
636 * 'a\b' == 'a\b'
637 * 'a\\b' == 'a\\b'
639 static BOOL build_command_line( WCHAR **argv )
641 int len;
642 WCHAR **arg;
643 LPWSTR p;
644 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
646 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
648 len = 0;
649 for (arg = argv; *arg; arg++)
651 int has_space,bcount;
652 WCHAR* a;
654 has_space=0;
655 bcount=0;
656 a=*arg;
657 if( !*a ) has_space=1;
658 while (*a!='\0') {
659 if (*a=='\\') {
660 bcount++;
661 } else {
662 if (*a==' ' || *a=='\t') {
663 has_space=1;
664 } else if (*a=='"') {
665 /* doubling of '\' preceding a '"',
666 * plus escaping of said '"'
668 len+=2*bcount+1;
670 bcount=0;
672 a++;
674 len+=(a-*arg)+1 /* for the separating space */;
675 if (has_space)
676 len+=2; /* for the quotes */
679 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
680 return FALSE;
682 p = rupp->CommandLine.Buffer;
683 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
684 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
685 for (arg = argv; *arg; arg++)
687 int has_space,has_quote;
688 WCHAR* a;
690 /* Check for quotes and spaces in this argument */
691 has_space=has_quote=0;
692 a=*arg;
693 if( !*a ) has_space=1;
694 while (*a!='\0') {
695 if (*a==' ' || *a=='\t') {
696 has_space=1;
697 if (has_quote)
698 break;
699 } else if (*a=='"') {
700 has_quote=1;
701 if (has_space)
702 break;
704 a++;
707 /* Now transfer it to the command line */
708 if (has_space)
709 *p++='"';
710 if (has_quote) {
711 int bcount;
712 WCHAR* a;
714 bcount=0;
715 a=*arg;
716 while (*a!='\0') {
717 if (*a=='\\') {
718 *p++=*a;
719 bcount++;
720 } else {
721 if (*a=='"') {
722 int i;
724 /* Double all the '\\' preceding this '"', plus one */
725 for (i=0;i<=bcount;i++)
726 *p++='\\';
727 *p++='"';
728 } else {
729 *p++=*a;
731 bcount=0;
733 a++;
735 } else {
736 WCHAR* x = *arg;
737 while ((*p=*x++)) p++;
739 if (has_space)
740 *p++='"';
741 *p++=' ';
743 if (p > rupp->CommandLine.Buffer)
744 p--; /* remove last space */
745 *p = '\0';
747 return TRUE;
751 /***********************************************************************
752 * init_current_directory
754 * Initialize the current directory from the Unix cwd or the parent info.
756 static void init_current_directory( CURDIR *cur_dir )
758 UNICODE_STRING dir_str;
759 const char *pwd;
760 char *cwd;
761 int size;
763 /* if we received a cur dir from the parent, try this first */
765 if (cur_dir->DosPath.Length)
767 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
770 /* now try to get it from the Unix cwd */
772 for (size = 256; ; size *= 2)
774 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
775 if (getcwd( cwd, size )) break;
776 HeapFree( GetProcessHeap(), 0, cwd );
777 if (errno == ERANGE) continue;
778 cwd = NULL;
779 break;
782 /* try to use PWD if it is valid, so that we don't resolve symlinks */
784 pwd = getenv( "PWD" );
785 if (cwd)
787 struct stat st1, st2;
789 if (!pwd || stat( pwd, &st1 ) == -1 ||
790 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
791 pwd = cwd;
794 if (pwd)
796 ANSI_STRING unix_name;
797 UNICODE_STRING nt_name;
798 RtlInitAnsiString( &unix_name, pwd );
799 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
801 UNICODE_STRING dos_path;
802 /* skip the \??\ prefix, nt_name is 0 terminated */
803 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
804 RtlSetCurrentDirectory_U( &dos_path );
805 RtlFreeUnicodeString( &nt_name );
809 if (!cur_dir->DosPath.Length) /* still not initialized */
811 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
812 "starting in the Windows directory.\n", cwd ? cwd : "" );
813 RtlInitUnicodeString( &dir_str, DIR_Windows );
814 RtlSetCurrentDirectory_U( &dir_str );
816 HeapFree( GetProcessHeap(), 0, cwd );
818 done:
819 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
820 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
824 /***********************************************************************
825 * init_windows_dirs
827 * Initialize the windows and system directories from the environment.
829 static void init_windows_dirs(void)
831 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
833 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
834 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
835 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
836 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
837 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
839 DWORD len;
840 WCHAR *buffer;
842 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
844 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
845 GetEnvironmentVariableW( windirW, buffer, len );
846 DIR_Windows = buffer;
848 else DIR_Windows = default_windirW;
850 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
852 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
853 GetEnvironmentVariableW( winsysdirW, buffer, len );
854 DIR_System = buffer;
856 else
858 len = strlenW( DIR_Windows );
859 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
860 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
861 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
862 DIR_System = buffer;
865 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
866 ERR( "directory %s could not be created, error %u\n",
867 debugstr_w(DIR_Windows), GetLastError() );
868 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
869 ERR( "directory %s could not be created, error %u\n",
870 debugstr_w(DIR_System), GetLastError() );
872 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
874 len = strlenW( DIR_Windows );
875 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
876 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
877 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
878 DIR_SysWow64 = buffer;
879 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
880 ERR( "directory %s could not be created, error %u\n",
881 debugstr_w(DIR_SysWow64), GetLastError() );
884 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
885 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
887 /* set the directories in ntdll too */
888 __wine_init_windows_dir( DIR_Windows, DIR_System );
892 /***********************************************************************
893 * start_wineboot
895 * Start the wineboot process if necessary. Return the handles to wait on.
897 static void start_wineboot( HANDLE handles[2] )
899 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
901 handles[1] = 0;
902 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
904 ERR( "failed to create wineboot event, expect trouble\n" );
905 return;
907 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
909 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
910 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
911 STARTUPINFOW si;
912 PROCESS_INFORMATION pi;
913 void *redir;
914 WCHAR app[MAX_PATH];
915 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
917 memset( &si, 0, sizeof(si) );
918 si.cb = sizeof(si);
919 si.dwFlags = STARTF_USESTDHANDLES;
920 si.hStdInput = 0;
921 si.hStdOutput = 0;
922 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
924 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
925 lstrcatW( app, wineboot );
927 Wow64DisableWow64FsRedirection( &redir );
928 strcpyW( cmdline, app );
929 strcatW( cmdline, args );
930 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
932 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
933 CloseHandle( pi.hThread );
934 handles[1] = pi.hProcess;
936 else
938 ERR( "failed to start wineboot, err %u\n", GetLastError() );
939 CloseHandle( handles[0] );
940 handles[0] = 0;
942 Wow64RevertWow64FsRedirection( redir );
947 #ifdef __i386__
948 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
949 __ASM_GLOBAL_FUNC( call_process_entry,
950 "pushl %ebp\n\t"
951 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
952 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
953 "movl %esp,%ebp\n\t"
954 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
955 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
956 "pushl 8(%ebp)\n\t"
957 "call *12(%ebp)\n\t"
958 "leave\n\t"
959 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
960 __ASM_CFI(".cfi_same_value %ebp\n\t")
961 "ret" )
962 #else
963 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
965 return entry( peb );
967 #endif
969 /***********************************************************************
970 * start_process
972 * Startup routine of a new process. Runs on the new process stack.
974 static DWORD WINAPI start_process( PEB *peb )
976 IMAGE_NT_HEADERS *nt;
977 LPTHREAD_START_ROUTINE entry;
979 nt = RtlImageNtHeader( peb->ImageBaseAddress );
980 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
981 nt->OptionalHeader.AddressOfEntryPoint);
983 if (!nt->OptionalHeader.AddressOfEntryPoint)
985 ERR( "%s doesn't have an entry point, it cannot be executed\n",
986 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
987 ExitThread( 1 );
990 if (TRACE_ON(relay))
991 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
992 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
994 SetLastError( 0 ); /* clear error code */
995 if (peb->BeingDebugged) DbgBreakPoint();
996 return call_process_entry( peb, entry );
1000 /***********************************************************************
1001 * set_process_name
1003 * Change the process name in the ps output.
1005 static void set_process_name( int argc, char *argv[] )
1007 #ifdef HAVE_SETPROCTITLE
1008 setproctitle("-%s", argv[1]);
1009 #endif
1011 #ifdef HAVE_PRCTL
1012 int i, offset;
1013 char *p, *prctl_name = argv[1];
1014 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1016 #ifndef PR_SET_NAME
1017 # define PR_SET_NAME 15
1018 #endif
1020 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1021 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1023 if (prctl( PR_SET_NAME, prctl_name ) != -1)
1025 offset = argv[1] - argv[0];
1026 memmove( argv[1] - offset, argv[1], end - argv[1] );
1027 memset( end - offset, 0, offset );
1028 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1029 argv[i-1] = NULL;
1031 else
1032 #endif /* HAVE_PRCTL */
1034 /* remove argv[0] */
1035 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1040 /***********************************************************************
1041 * __wine_kernel_init
1043 * Wine initialisation: load and start the main exe file.
1045 void CDECL __wine_kernel_init(void)
1047 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1048 static const WCHAR dotW[] = {'.',0};
1050 WCHAR *p, main_exe_name[MAX_PATH+1];
1051 PEB *peb = NtCurrentTeb()->Peb;
1052 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1053 HANDLE boot_events[2];
1054 BOOL got_environment = TRUE;
1056 /* Initialize everything */
1058 setbuf(stdout,NULL);
1059 setbuf(stderr,NULL);
1060 kernel32_handle = GetModuleHandleW(kernel32W);
1061 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1063 LOCALE_Init();
1065 if (!params->Environment)
1067 /* Copy the parent environment */
1068 if (!build_initial_environment()) exit(1);
1070 /* convert old configuration to new format */
1071 convert_old_config();
1073 got_environment = set_registry_environment( FALSE );
1074 set_additional_environment();
1077 init_windows_dirs();
1078 init_current_directory( &params->CurrentDirectory );
1080 set_process_name( __wine_main_argc, __wine_main_argv );
1081 set_library_wargv( __wine_main_argv );
1082 boot_events[0] = boot_events[1] = 0;
1084 if (peb->ProcessParameters->ImagePathName.Buffer)
1086 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1088 else
1090 struct binary_info binary_info;
1092 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1093 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1095 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1096 ExitProcess( GetLastError() );
1098 update_library_argv0( main_exe_name );
1099 if (!build_command_line( __wine_main_wargv )) goto error;
1100 start_wineboot( boot_events );
1103 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1104 p = strrchrW( main_exe_name, '.' );
1105 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1107 TRACE( "starting process name=%s argv[0]=%s\n",
1108 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1110 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1111 MODULE_get_dll_load_path(main_exe_name) );
1113 if (boot_events[0])
1115 DWORD timeout = 2 * 60 * 1000, count = 1;
1117 if (boot_events[1]) count++;
1118 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1119 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1120 ERR( "boot event wait timed out\n" );
1121 CloseHandle( boot_events[0] );
1122 if (boot_events[1]) CloseHandle( boot_events[1] );
1123 /* reload environment now that wineboot has run */
1124 set_registry_environment( got_environment );
1125 set_additional_environment();
1128 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1130 DWORD_PTR args[1];
1131 WCHAR msgW[1024];
1132 char msg[1024];
1133 DWORD error = GetLastError();
1135 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1136 if (error == ERROR_BAD_EXE_FORMAT ||
1137 error == ERROR_INVALID_ADDRESS ||
1138 error == ERROR_NOT_ENOUGH_MEMORY)
1140 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1141 /* if we get back here, it failed */
1143 else if (error == ERROR_MOD_NOT_FOUND)
1145 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1146 else p = main_exe_name;
1147 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1149 /* args 1 and 2 are --app-name full_path */
1150 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1151 debugstr_w(__wine_main_wargv[3]) );
1152 ExitProcess( ERROR_BAD_EXE_FORMAT );
1154 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1155 ExitProcess( ERROR_FILE_NOT_FOUND );
1157 args[0] = (DWORD_PTR)main_exe_name;
1158 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1159 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1160 WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1161 MESSAGE( "wine: %s", msg );
1162 ExitProcess( error );
1165 LdrInitializeThunk( start_process, 0, 0, 0 );
1167 error:
1168 ExitProcess( GetLastError() );
1172 /***********************************************************************
1173 * build_argv
1175 * Build an argv array from a command-line.
1176 * 'reserved' is the number of args to reserve before the first one.
1178 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1180 int argc;
1181 char** argv;
1182 char *arg,*s,*d,*cmdline;
1183 int in_quotes,bcount,len;
1185 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1186 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1187 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1189 argc=reserved+1;
1190 bcount=0;
1191 in_quotes=0;
1192 s=cmdline;
1193 while (1) {
1194 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1195 /* space */
1196 argc++;
1197 /* skip the remaining spaces */
1198 while (*s==' ' || *s=='\t') {
1199 s++;
1201 if (*s=='\0')
1202 break;
1203 bcount=0;
1204 continue;
1205 } else if (*s=='\\') {
1206 /* '\', count them */
1207 bcount++;
1208 } else if ((*s=='"') && ((bcount & 1)==0)) {
1209 /* unescaped '"' */
1210 in_quotes=!in_quotes;
1211 bcount=0;
1212 } else {
1213 /* a regular character */
1214 bcount=0;
1216 s++;
1218 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1220 HeapFree( GetProcessHeap(), 0, cmdline );
1221 return NULL;
1224 arg = d = s = (char *)(argv + argc);
1225 memcpy( d, cmdline, len );
1226 bcount=0;
1227 in_quotes=0;
1228 argc=reserved;
1229 while (*s) {
1230 if ((*s==' ' || *s=='\t') && !in_quotes) {
1231 /* Close the argument and copy it */
1232 *d=0;
1233 argv[argc++]=arg;
1235 /* skip the remaining spaces */
1236 do {
1237 s++;
1238 } while (*s==' ' || *s=='\t');
1240 /* Start with a new argument */
1241 arg=d=s;
1242 bcount=0;
1243 } else if (*s=='\\') {
1244 /* '\\' */
1245 *d++=*s++;
1246 bcount++;
1247 } else if (*s=='"') {
1248 /* '"' */
1249 if ((bcount & 1)==0) {
1250 /* Preceded by an even number of '\', this is half that
1251 * number of '\', plus a '"' which we discard.
1253 d-=bcount/2;
1254 s++;
1255 in_quotes=!in_quotes;
1256 } else {
1257 /* Preceded by an odd number of '\', this is half that
1258 * number of '\' followed by a '"'
1260 d=d-bcount/2-1;
1261 *d++='"';
1262 s++;
1264 bcount=0;
1265 } else {
1266 /* a regular character */
1267 *d++=*s++;
1268 bcount=0;
1271 if (*arg) {
1272 *d='\0';
1273 argv[argc++]=arg;
1275 argv[argc]=NULL;
1277 HeapFree( GetProcessHeap(), 0, cmdline );
1278 return argv;
1282 /***********************************************************************
1283 * build_envp
1285 * Build the environment of a new child process.
1287 static char **build_envp( const WCHAR *envW )
1289 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1291 const WCHAR *end;
1292 char **envp;
1293 char *env, *p;
1294 int count = 1, length;
1295 unsigned int i;
1297 for (end = envW; *end; count++) end += strlenW(end) + 1;
1298 end++;
1299 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1300 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1301 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1303 for (p = env; *p; p += strlen(p) + 1)
1304 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1306 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1308 if (!(p = getenv(unix_vars[i]))) continue;
1309 length += strlen(unix_vars[i]) + strlen(p) + 2;
1310 count++;
1313 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1315 char **envptr = envp;
1316 char *dst = (char *)(envp + count);
1318 /* some variables must not be modified, so we get them directly from the unix env */
1319 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1321 if (!(p = getenv(unix_vars[i]))) continue;
1322 *envptr++ = strcpy( dst, unix_vars[i] );
1323 strcat( dst, "=" );
1324 strcat( dst, p );
1325 dst += strlen(dst) + 1;
1328 /* now put the Windows environment strings */
1329 for (p = env; *p; p += strlen(p) + 1)
1331 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1332 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1333 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1334 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1335 if (is_special_env_var( p )) /* prefix it with "WINE" */
1337 *envptr++ = strcpy( dst, "WINE" );
1338 strcat( dst, p );
1340 else
1342 *envptr++ = strcpy( dst, p );
1344 dst += strlen(dst) + 1;
1346 *envptr = 0;
1348 HeapFree( GetProcessHeap(), 0, env );
1349 return envp;
1353 /***********************************************************************
1354 * fork_and_exec
1356 * Fork and exec a new Unix binary, checking for errors.
1358 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1359 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1361 int fd[2], stdin_fd = -1, stdout_fd = -1;
1362 int pid, err;
1363 char **argv, **envp;
1365 if (!env) env = GetEnvironmentStringsW();
1367 #ifdef HAVE_PIPE2
1368 if (pipe2( fd, O_CLOEXEC ) == -1)
1369 #endif
1371 if (pipe(fd) == -1)
1373 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1374 return -1;
1376 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1377 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1380 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1382 HANDLE hstdin, hstdout;
1384 if (startup->dwFlags & STARTF_USESTDHANDLES)
1386 hstdin = startup->hStdInput;
1387 hstdout = startup->hStdOutput;
1389 else
1391 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1392 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1395 if (is_console_handle( hstdin ))
1396 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1397 if (is_console_handle( hstdout ))
1398 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1399 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1400 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1403 argv = build_argv( cmdline, 0 );
1404 envp = build_envp( env );
1406 if (!(pid = fork())) /* child */
1408 close( fd[0] );
1410 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1412 int pid;
1413 if (!(pid = fork()))
1415 int fd = open( "/dev/null", O_RDWR );
1416 setsid();
1417 /* close stdin and stdout */
1418 if (fd != -1)
1420 dup2( fd, 0 );
1421 dup2( fd, 1 );
1422 close( fd );
1425 else if (pid != -1) _exit(0); /* parent */
1427 else
1429 if (stdin_fd != -1)
1431 dup2( stdin_fd, 0 );
1432 close( stdin_fd );
1434 if (stdout_fd != -1)
1436 dup2( stdout_fd, 1 );
1437 close( stdout_fd );
1441 /* Reset signals that we previously set to SIG_IGN */
1442 signal( SIGPIPE, SIG_DFL );
1443 signal( SIGCHLD, SIG_DFL );
1445 if (newdir) chdir(newdir);
1447 if (argv && envp) execve( filename, argv, envp );
1448 err = errno;
1449 write( fd[1], &err, sizeof(err) );
1450 _exit(1);
1452 HeapFree( GetProcessHeap(), 0, argv );
1453 HeapFree( GetProcessHeap(), 0, envp );
1454 if (stdin_fd != -1) close( stdin_fd );
1455 if (stdout_fd != -1) close( stdout_fd );
1456 close( fd[1] );
1457 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1459 errno = err;
1460 pid = -1;
1462 if (pid == -1) FILE_SetDosError();
1463 close( fd[0] );
1464 return pid;
1468 static inline DWORD append_string( void **ptr, const WCHAR *str )
1470 DWORD len = strlenW( str );
1471 memcpy( *ptr, str, len * sizeof(WCHAR) );
1472 *ptr = (WCHAR *)*ptr + len;
1473 return len * sizeof(WCHAR);
1476 /***********************************************************************
1477 * create_startup_info
1479 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1480 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1481 const STARTUPINFOW *startup, DWORD *info_size )
1483 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1484 const WCHAR *title;
1485 startup_info_t *info;
1486 DWORD size;
1487 void *ptr;
1488 UNICODE_STRING newdir;
1489 WCHAR imagepath[MAX_PATH];
1490 HANDLE hstdin, hstdout, hstderr;
1492 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1493 lstrcpynW( imagepath, filename, MAX_PATH );
1494 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1495 lstrcpynW( imagepath, filename, MAX_PATH );
1497 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1499 newdir.Buffer = NULL;
1500 if (cur_dir)
1502 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1503 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1504 else
1505 cur_dir = NULL;
1507 if (!cur_dir)
1509 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1510 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1511 else
1512 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1514 title = startup->lpTitle ? startup->lpTitle : imagepath;
1516 size = sizeof(*info);
1517 size += strlenW( cur_dir ) * sizeof(WCHAR);
1518 size += cur_params->DllPath.Length;
1519 size += strlenW( imagepath ) * sizeof(WCHAR);
1520 size += strlenW( cmdline ) * sizeof(WCHAR);
1521 size += strlenW( title ) * sizeof(WCHAR);
1522 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1523 /* FIXME: shellinfo */
1524 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1525 size = (size + 1) & ~1;
1526 *info_size = size;
1528 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1530 info->console_flags = cur_params->ConsoleFlags;
1531 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1532 if (flags & CREATE_NEW_CONSOLE) info->console = (obj_handle_t)1; /* FIXME: cf. kernel_main.c */
1534 if (startup->dwFlags & STARTF_USESTDHANDLES)
1536 hstdin = startup->hStdInput;
1537 hstdout = startup->hStdOutput;
1538 hstderr = startup->hStdError;
1540 else
1542 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1543 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1544 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1546 info->hstdin = wine_server_obj_handle( hstdin );
1547 info->hstdout = wine_server_obj_handle( hstdout );
1548 info->hstderr = wine_server_obj_handle( hstderr );
1549 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1551 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1552 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1553 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1554 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1556 else
1558 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1559 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1560 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1563 info->x = startup->dwX;
1564 info->y = startup->dwY;
1565 info->xsize = startup->dwXSize;
1566 info->ysize = startup->dwYSize;
1567 info->xchars = startup->dwXCountChars;
1568 info->ychars = startup->dwYCountChars;
1569 info->attribute = startup->dwFillAttribute;
1570 info->flags = startup->dwFlags;
1571 info->show = startup->wShowWindow;
1573 ptr = info + 1;
1574 info->curdir_len = append_string( &ptr, cur_dir );
1575 info->dllpath_len = cur_params->DllPath.Length;
1576 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1577 ptr = (char *)ptr + cur_params->DllPath.Length;
1578 info->imagepath_len = append_string( &ptr, imagepath );
1579 info->cmdline_len = append_string( &ptr, cmdline );
1580 info->title_len = append_string( &ptr, title );
1581 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1582 if (startup->lpReserved2 && startup->cbReserved2)
1584 info->runtime_len = startup->cbReserved2;
1585 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1588 done:
1589 RtlFreeUnicodeString( &newdir );
1590 return info;
1593 /***********************************************************************
1594 * get_alternate_loader
1596 * Get the name of the alternate (32 or 64 bit) Wine loader.
1598 static const char *get_alternate_loader( char **ret_env )
1600 char *env;
1601 const char *loader = NULL;
1602 const char *loader_env = getenv( "WINELOADER" );
1604 *ret_env = NULL;
1606 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1608 if (loader_env)
1610 int len = strlen( loader_env );
1611 if (!is_win64)
1613 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1614 strcpy( env, "WINELOADER=" );
1615 strcat( env, loader_env );
1616 strcat( env, "64" );
1618 else
1620 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1621 strcpy( env, "WINELOADER=" );
1622 strcat( env, loader_env );
1623 len += sizeof("WINELOADER=") - 1;
1624 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1626 if (!loader)
1628 if ((loader = strrchr( env, '/' ))) loader++;
1629 else loader = env;
1631 *ret_env = env;
1633 if (!loader) loader = is_win64 ? "wine" : "wine64";
1634 return loader;
1637 /***********************************************************************
1638 * create_process
1640 * Create a new process. If hFile is a valid handle we have an exe
1641 * file, otherwise it is a Winelib app.
1643 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1644 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1645 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1646 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1647 const struct binary_info *binary_info, int exec_only )
1649 BOOL ret, success = FALSE;
1650 HANDLE process_info;
1651 WCHAR *env_end;
1652 char *winedebug = NULL;
1653 char *wineloader = NULL;
1654 const char *loader = NULL;
1655 char **argv;
1656 startup_info_t *startup_info;
1657 DWORD startup_info_size;
1658 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1659 pid_t pid;
1660 int err;
1662 if (!is_win64 && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1664 ERR( "starting 64-bit process %s not supported on this environment\n", debugstr_w(filename) );
1665 SetLastError( ERROR_BAD_EXE_FORMAT );
1666 return FALSE;
1669 RtlAcquirePebLock();
1671 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1672 &startup_info_size )))
1674 RtlReleasePebLock();
1675 return FALSE;
1677 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1678 env_end = env;
1679 while (*env_end)
1681 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1682 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1684 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1685 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1686 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1688 env_end += strlenW(env_end) + 1;
1690 env_end++;
1692 /* create the socket for the new process */
1694 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1696 RtlReleasePebLock();
1697 HeapFree( GetProcessHeap(), 0, winedebug );
1698 HeapFree( GetProcessHeap(), 0, startup_info );
1699 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1700 return FALSE;
1702 wine_server_send_fd( socketfd[1] );
1703 close( socketfd[1] );
1705 /* create the process on the server side */
1707 SERVER_START_REQ( new_process )
1709 req->inherit_all = inherit;
1710 req->create_flags = flags;
1711 req->socket_fd = socketfd[1];
1712 req->exe_file = wine_server_obj_handle( hFile );
1713 req->process_access = PROCESS_ALL_ACCESS;
1714 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1715 req->thread_access = THREAD_ALL_ACCESS;
1716 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1717 req->info_size = startup_info_size;
1719 wine_server_add_data( req, startup_info, startup_info_size );
1720 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1721 if ((ret = !wine_server_call_err( req )))
1723 info->dwProcessId = (DWORD)reply->pid;
1724 info->dwThreadId = (DWORD)reply->tid;
1725 info->hProcess = wine_server_ptr_handle( reply->phandle );
1726 info->hThread = wine_server_ptr_handle( reply->thandle );
1728 process_info = wine_server_ptr_handle( reply->info );
1730 SERVER_END_REQ;
1732 RtlReleasePebLock();
1733 if (!ret)
1735 close( socketfd[0] );
1736 HeapFree( GetProcessHeap(), 0, startup_info );
1737 HeapFree( GetProcessHeap(), 0, winedebug );
1738 return FALSE;
1741 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1743 if (startup_info->hstdin)
1744 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1745 FILE_READ_DATA, &stdin_fd, NULL );
1746 if (startup_info->hstdout)
1747 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1748 FILE_WRITE_DATA, &stdout_fd, NULL );
1750 HeapFree( GetProcessHeap(), 0, startup_info );
1752 /* create the child process */
1753 argv = build_argv( cmd_line, 1 );
1755 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1756 loader = get_alternate_loader( &wineloader );
1758 if (exec_only || !(pid = fork())) /* child */
1760 char preloader_reserve[64], socket_env[64];
1762 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1764 if (!(pid = fork()))
1766 int fd = open( "/dev/null", O_RDWR );
1767 setsid();
1768 /* close stdin and stdout */
1769 if (fd != -1)
1771 dup2( fd, 0 );
1772 dup2( fd, 1 );
1773 close( fd );
1776 else if (pid != -1) _exit(0); /* parent */
1778 else
1780 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1781 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1784 if (stdin_fd != -1) close( stdin_fd );
1785 if (stdout_fd != -1) close( stdout_fd );
1787 /* Reset signals that we previously set to SIG_IGN */
1788 signal( SIGPIPE, SIG_DFL );
1789 signal( SIGCHLD, SIG_DFL );
1791 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1792 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1793 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1795 putenv( preloader_reserve );
1796 putenv( socket_env );
1797 if (winedebug) putenv( winedebug );
1798 if (wineloader) putenv( wineloader );
1799 if (unixdir) chdir(unixdir);
1801 if (argv) wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1802 _exit(1);
1805 /* this is the parent */
1807 if (stdin_fd != -1) close( stdin_fd );
1808 if (stdout_fd != -1) close( stdout_fd );
1809 close( socketfd[0] );
1810 HeapFree( GetProcessHeap(), 0, argv );
1811 HeapFree( GetProcessHeap(), 0, winedebug );
1812 HeapFree( GetProcessHeap(), 0, wineloader );
1813 if (pid == -1)
1815 FILE_SetDosError();
1816 goto error;
1819 /* wait for the new process info to be ready */
1821 WaitForSingleObject( process_info, INFINITE );
1822 SERVER_START_REQ( get_new_process_info )
1824 req->info = wine_server_obj_handle( process_info );
1825 wine_server_call( req );
1826 success = reply->success;
1827 err = reply->exit_code;
1829 SERVER_END_REQ;
1831 if (!success)
1833 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1834 goto error;
1836 CloseHandle( process_info );
1837 return success;
1839 error:
1840 CloseHandle( process_info );
1841 CloseHandle( info->hProcess );
1842 CloseHandle( info->hThread );
1843 info->hProcess = info->hThread = 0;
1844 info->dwProcessId = info->dwThreadId = 0;
1845 return FALSE;
1849 /***********************************************************************
1850 * create_vdm_process
1852 * Create a new VDM process for a 16-bit or DOS application.
1854 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1855 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1856 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1857 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1858 const struct binary_info *binary_info, int exec_only )
1860 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1862 BOOL ret;
1863 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1864 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1866 if (!new_cmd_line)
1868 SetLastError( ERROR_OUTOFMEMORY );
1869 return FALSE;
1871 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1872 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1873 flags, startup, info, unixdir, binary_info, exec_only );
1874 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1875 return ret;
1879 /***********************************************************************
1880 * create_cmd_process
1882 * Create a new cmd shell process for a .BAT file.
1884 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1885 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1886 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1887 LPPROCESS_INFORMATION info )
1890 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1891 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1892 WCHAR comspec[MAX_PATH];
1893 WCHAR *newcmdline;
1894 BOOL ret;
1896 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1897 return FALSE;
1898 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1899 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1900 return FALSE;
1902 strcpyW( newcmdline, comspec );
1903 strcatW( newcmdline, slashcW );
1904 strcatW( newcmdline, cmd_line );
1905 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1906 flags, env, cur_dir, startup, info );
1907 HeapFree( GetProcessHeap(), 0, newcmdline );
1908 return ret;
1912 /*************************************************************************
1913 * get_file_name
1915 * Helper for CreateProcess: retrieve the file name to load from the
1916 * app name and command line. Store the file name in buffer, and
1917 * return a possibly modified command line.
1918 * Also returns a handle to the opened file if it's a Windows binary.
1920 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1921 int buflen, HANDLE *handle, struct binary_info *binary_info )
1923 static const WCHAR quotesW[] = {'"','%','s','"',0};
1925 WCHAR *name, *pos, *first_space, *ret = NULL;
1926 const WCHAR *p;
1928 /* if we have an app name, everything is easy */
1930 if (appname)
1932 /* use the unmodified app name as file name */
1933 lstrcpynW( buffer, appname, buflen );
1934 *handle = open_exe_file( buffer, binary_info );
1935 if (!(ret = cmdline) || !cmdline[0])
1937 /* no command-line, create one */
1938 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1939 sprintfW( ret, quotesW, appname );
1941 return ret;
1944 /* first check for a quoted file name */
1946 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1948 int len = p - cmdline - 1;
1949 /* extract the quoted portion as file name */
1950 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1951 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1952 name[len] = 0;
1954 if (!find_exe_file( name, buffer, buflen, handle, binary_info ))
1956 if (!get_builtin_path( name, exeW, buffer, buflen, binary_info )) goto done;
1957 *handle = 0;
1959 ret = cmdline; /* no change necessary */
1960 goto done;
1963 /* now try the command-line word by word */
1965 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1966 return NULL;
1967 pos = name;
1968 p = cmdline;
1969 first_space = NULL;
1971 for (;;)
1973 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
1974 *pos = 0;
1975 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1977 ret = cmdline;
1978 break;
1980 if (!first_space) first_space = pos;
1981 if (!(*pos++ = *p++)) break;
1984 if (!ret)
1986 if (first_space) *first_space = 0; /* try only the first word as a builtin */
1987 if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
1989 *handle = 0;
1990 ret = cmdline;
1992 else SetLastError( ERROR_FILE_NOT_FOUND );
1994 else if (first_space) /* build a new command-line with quotes */
1996 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1997 goto done;
1998 sprintfW( ret, quotesW, name );
1999 strcatW( ret, p );
2002 done:
2003 HeapFree( GetProcessHeap(), 0, name );
2004 return ret;
2008 /**********************************************************************
2009 * CreateProcessA (KERNEL32.@)
2011 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2012 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2013 DWORD flags, LPVOID env, LPCSTR cur_dir,
2014 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2016 BOOL ret = FALSE;
2017 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2018 UNICODE_STRING desktopW, titleW;
2019 STARTUPINFOW infoW;
2021 desktopW.Buffer = NULL;
2022 titleW.Buffer = NULL;
2023 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2024 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2025 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2027 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2028 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2030 memcpy( &infoW, startup_info, sizeof(infoW) );
2031 infoW.lpDesktop = desktopW.Buffer;
2032 infoW.lpTitle = titleW.Buffer;
2034 if (startup_info->lpReserved)
2035 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2036 debugstr_a(startup_info->lpReserved));
2038 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
2039 inherit, flags, env, cur_dirW, &infoW, info );
2040 done:
2041 HeapFree( GetProcessHeap(), 0, app_nameW );
2042 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2043 HeapFree( GetProcessHeap(), 0, cur_dirW );
2044 RtlFreeUnicodeString( &desktopW );
2045 RtlFreeUnicodeString( &titleW );
2046 return ret;
2050 /**********************************************************************
2051 * CreateProcessW (KERNEL32.@)
2053 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2054 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2055 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2056 LPPROCESS_INFORMATION info )
2058 BOOL retv = FALSE;
2059 HANDLE hFile = 0;
2060 char *unixdir = NULL;
2061 WCHAR name[MAX_PATH];
2062 WCHAR *tidy_cmdline, *p, *envW = env;
2063 struct binary_info binary_info;
2065 /* Process the AppName and/or CmdLine to get module name and path */
2067 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2069 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2070 &hFile, &binary_info )))
2071 return FALSE;
2072 if (hFile == INVALID_HANDLE_VALUE) goto done;
2074 /* Warn if unsupported features are used */
2076 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2077 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2078 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2079 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2080 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2082 if (cur_dir)
2084 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2086 SetLastError(ERROR_DIRECTORY);
2087 goto done;
2090 else
2092 WCHAR buf[MAX_PATH];
2093 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2096 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2098 char *p = env;
2099 DWORD lenW;
2101 while (*p) p += strlen(p) + 1;
2102 p++; /* final null */
2103 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2104 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2105 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2106 flags |= CREATE_UNICODE_ENVIRONMENT;
2109 info->hThread = info->hProcess = 0;
2110 info->dwProcessId = info->dwThreadId = 0;
2112 if (binary_info.flags & BINARY_FLAG_DLL)
2114 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2115 SetLastError( ERROR_BAD_EXE_FORMAT );
2117 else switch (binary_info.type)
2119 case BINARY_PE:
2120 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2121 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2122 binary_info.res_start, binary_info.res_end );
2123 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2124 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2125 break;
2126 case BINARY_OS216:
2127 case BINARY_WIN16:
2128 case BINARY_DOS:
2129 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2130 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2131 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2132 break;
2133 case BINARY_UNIX_LIB:
2134 TRACE( "starting %s as %d-bit Winelib app\n",
2135 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2136 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2137 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2138 break;
2139 case BINARY_UNKNOWN:
2140 /* check for .com or .bat extension */
2141 if ((p = strrchrW( name, '.' )))
2143 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2145 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2146 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2147 inherit, flags, startup_info, info, unixdir,
2148 &binary_info, FALSE );
2149 break;
2151 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2153 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2154 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2155 inherit, flags, startup_info, info );
2156 break;
2159 /* fall through */
2160 case BINARY_UNIX_EXE:
2162 /* unknown file, try as unix executable */
2163 char *unix_name;
2165 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2167 if ((unix_name = wine_get_unix_file_name( name )))
2169 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2170 HeapFree( GetProcessHeap(), 0, unix_name );
2173 break;
2175 if (hFile) CloseHandle( hFile );
2177 done:
2178 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2179 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2180 HeapFree( GetProcessHeap(), 0, unixdir );
2181 if (retv)
2182 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2183 return retv;
2187 /**********************************************************************
2188 * exec_process
2190 static void exec_process( LPCWSTR name )
2192 HANDLE hFile;
2193 WCHAR *p;
2194 STARTUPINFOW startup_info;
2195 PROCESS_INFORMATION info;
2196 struct binary_info binary_info;
2198 hFile = open_exe_file( name, &binary_info );
2199 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2201 memset( &startup_info, 0, sizeof(startup_info) );
2202 startup_info.cb = sizeof(startup_info);
2204 /* Determine executable type */
2206 if (binary_info.flags & BINARY_FLAG_DLL) return;
2207 switch (binary_info.type)
2209 case BINARY_PE:
2210 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2211 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2212 binary_info.res_start, binary_info.res_end );
2213 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2214 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2215 break;
2216 case BINARY_UNIX_LIB:
2217 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2218 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2219 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2220 break;
2221 case BINARY_UNKNOWN:
2222 /* check for .com or .pif extension */
2223 if (!(p = strrchrW( name, '.' ))) break;
2224 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2225 /* fall through */
2226 case BINARY_OS216:
2227 case BINARY_WIN16:
2228 case BINARY_DOS:
2229 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2230 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2231 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2232 break;
2233 default:
2234 break;
2236 CloseHandle( hFile );
2240 /***********************************************************************
2241 * wait_input_idle
2243 * Wrapper to call WaitForInputIdle USER function
2245 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2247 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2249 HMODULE mod = GetModuleHandleA( "user32.dll" );
2250 if (mod)
2252 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2253 if (ptr) return ptr( process, timeout );
2255 return 0;
2259 /***********************************************************************
2260 * WinExec (KERNEL32.@)
2262 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2264 PROCESS_INFORMATION info;
2265 STARTUPINFOA startup;
2266 char *cmdline;
2267 UINT ret;
2269 memset( &startup, 0, sizeof(startup) );
2270 startup.cb = sizeof(startup);
2271 startup.dwFlags = STARTF_USESHOWWINDOW;
2272 startup.wShowWindow = nCmdShow;
2274 /* cmdline needs to be writable for CreateProcess */
2275 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2276 strcpy( cmdline, lpCmdLine );
2278 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2279 0, NULL, NULL, &startup, &info ))
2281 /* Give 30 seconds to the app to come up */
2282 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2283 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2284 ret = 33;
2285 /* Close off the handles */
2286 CloseHandle( info.hThread );
2287 CloseHandle( info.hProcess );
2289 else if ((ret = GetLastError()) >= 32)
2291 FIXME("Strange error set by CreateProcess: %d\n", ret );
2292 ret = 11;
2294 HeapFree( GetProcessHeap(), 0, cmdline );
2295 return ret;
2299 /**********************************************************************
2300 * LoadModule (KERNEL32.@)
2302 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2304 LOADPARMS32 *params = paramBlock;
2305 PROCESS_INFORMATION info;
2306 STARTUPINFOA startup;
2307 HINSTANCE hInstance;
2308 LPSTR cmdline, p;
2309 char filename[MAX_PATH];
2310 BYTE len;
2312 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2314 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2315 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2316 return ULongToHandle(GetLastError());
2318 len = (BYTE)params->lpCmdLine[0];
2319 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2320 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2322 strcpy( cmdline, filename );
2323 p = cmdline + strlen(cmdline);
2324 *p++ = ' ';
2325 memcpy( p, params->lpCmdLine + 1, len );
2326 p[len] = 0;
2328 memset( &startup, 0, sizeof(startup) );
2329 startup.cb = sizeof(startup);
2330 if (params->lpCmdShow)
2332 startup.dwFlags = STARTF_USESHOWWINDOW;
2333 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2336 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2337 params->lpEnvAddress, NULL, &startup, &info ))
2339 /* Give 30 seconds to the app to come up */
2340 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2341 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2342 hInstance = (HINSTANCE)33;
2343 /* Close off the handles */
2344 CloseHandle( info.hThread );
2345 CloseHandle( info.hProcess );
2347 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2349 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2350 hInstance = (HINSTANCE)11;
2353 HeapFree( GetProcessHeap(), 0, cmdline );
2354 return hInstance;
2358 /******************************************************************************
2359 * TerminateProcess (KERNEL32.@)
2361 * Terminates a process.
2363 * PARAMS
2364 * handle [I] Process to terminate.
2365 * exit_code [I] Exit code.
2367 * RETURNS
2368 * Success: TRUE.
2369 * Failure: FALSE, check GetLastError().
2371 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2373 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2374 if (status) SetLastError( RtlNtStatusToDosError(status) );
2375 return !status;
2378 /***********************************************************************
2379 * ExitProcess (KERNEL32.@)
2381 * Exits the current process.
2383 * PARAMS
2384 * status [I] Status code to exit with.
2386 * RETURNS
2387 * Nothing.
2389 #ifdef __i386__
2390 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2391 "pushl %ebp\n\t"
2392 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2393 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2394 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2395 "pushl 8(%ebp)\n\t"
2396 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2397 "leave\n\t"
2398 "ret $4" )
2400 void WINAPI process_ExitProcess( DWORD status )
2402 LdrShutdownProcess();
2403 NtTerminateProcess(GetCurrentProcess(), status);
2404 exit(status);
2407 #else
2409 void WINAPI ExitProcess( DWORD status )
2411 LdrShutdownProcess();
2412 NtTerminateProcess(GetCurrentProcess(), status);
2413 exit(status);
2416 #endif
2418 /***********************************************************************
2419 * GetExitCodeProcess [KERNEL32.@]
2421 * Gets termination status of specified process.
2423 * PARAMS
2424 * hProcess [in] Handle to the process.
2425 * lpExitCode [out] Address to receive termination status.
2427 * RETURNS
2428 * Success: TRUE
2429 * Failure: FALSE
2431 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2433 NTSTATUS status;
2434 PROCESS_BASIC_INFORMATION pbi;
2436 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2437 sizeof(pbi), NULL);
2438 if (status == STATUS_SUCCESS)
2440 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2441 return TRUE;
2443 SetLastError( RtlNtStatusToDosError(status) );
2444 return FALSE;
2448 /***********************************************************************
2449 * SetErrorMode (KERNEL32.@)
2451 UINT WINAPI SetErrorMode( UINT mode )
2453 UINT old = process_error_mode;
2454 process_error_mode = mode;
2455 return old;
2458 /***********************************************************************
2459 * GetErrorMode (KERNEL32.@)
2461 UINT WINAPI GetErrorMode( void )
2463 return process_error_mode;
2466 /**********************************************************************
2467 * TlsAlloc [KERNEL32.@]
2469 * Allocates a thread local storage index.
2471 * RETURNS
2472 * Success: TLS index.
2473 * Failure: 0xFFFFFFFF
2475 DWORD WINAPI TlsAlloc( void )
2477 DWORD index;
2478 PEB * const peb = NtCurrentTeb()->Peb;
2480 RtlAcquirePebLock();
2481 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2482 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2483 else
2485 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2486 if (index != ~0U)
2488 if (!NtCurrentTeb()->TlsExpansionSlots &&
2489 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2490 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2492 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2493 index = ~0U;
2494 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2496 else
2498 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2499 index += TLS_MINIMUM_AVAILABLE;
2502 else SetLastError( ERROR_NO_MORE_ITEMS );
2504 RtlReleasePebLock();
2505 return index;
2509 /**********************************************************************
2510 * TlsFree [KERNEL32.@]
2512 * Releases a thread local storage index, making it available for reuse.
2514 * PARAMS
2515 * index [in] TLS index to free.
2517 * RETURNS
2518 * Success: TRUE
2519 * Failure: FALSE
2521 BOOL WINAPI TlsFree( DWORD index )
2523 BOOL ret;
2525 RtlAcquirePebLock();
2526 if (index >= TLS_MINIMUM_AVAILABLE)
2528 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2529 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2531 else
2533 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2534 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2536 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2537 else SetLastError( ERROR_INVALID_PARAMETER );
2538 RtlReleasePebLock();
2539 return ret;
2543 /**********************************************************************
2544 * TlsGetValue [KERNEL32.@]
2546 * Gets value in a thread's TLS slot.
2548 * PARAMS
2549 * index [in] TLS index to retrieve value for.
2551 * RETURNS
2552 * Success: Value stored in calling thread's TLS slot for index.
2553 * Failure: 0 and GetLastError() returns NO_ERROR.
2555 LPVOID WINAPI TlsGetValue( DWORD index )
2557 LPVOID ret;
2559 if (index < TLS_MINIMUM_AVAILABLE)
2561 ret = NtCurrentTeb()->TlsSlots[index];
2563 else
2565 index -= TLS_MINIMUM_AVAILABLE;
2566 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2568 SetLastError( ERROR_INVALID_PARAMETER );
2569 return NULL;
2571 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2572 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2574 SetLastError( ERROR_SUCCESS );
2575 return ret;
2579 /**********************************************************************
2580 * TlsSetValue [KERNEL32.@]
2582 * Stores a value in the thread's TLS slot.
2584 * PARAMS
2585 * index [in] TLS index to set value for.
2586 * value [in] Value to be stored.
2588 * RETURNS
2589 * Success: TRUE
2590 * Failure: FALSE
2592 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2594 if (index < TLS_MINIMUM_AVAILABLE)
2596 NtCurrentTeb()->TlsSlots[index] = value;
2598 else
2600 index -= TLS_MINIMUM_AVAILABLE;
2601 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2603 SetLastError( ERROR_INVALID_PARAMETER );
2604 return FALSE;
2606 if (!NtCurrentTeb()->TlsExpansionSlots &&
2607 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2608 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2610 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2611 return FALSE;
2613 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2615 return TRUE;
2619 /***********************************************************************
2620 * GetProcessFlags (KERNEL32.@)
2622 DWORD WINAPI GetProcessFlags( DWORD processid )
2624 IMAGE_NT_HEADERS *nt;
2625 DWORD flags = 0;
2627 if (processid && processid != GetCurrentProcessId()) return 0;
2629 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2631 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2632 flags |= PDB32_CONSOLE_PROC;
2634 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2635 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2636 return flags;
2640 /***********************************************************************
2641 * GetProcessDword (KERNEL32.18)
2643 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2645 FIXME( "(%d, %d): not supported\n", dwProcessID, offset );
2646 return 0;
2650 /*********************************************************************
2651 * OpenProcess (KERNEL32.@)
2653 * Opens a handle to a process.
2655 * PARAMS
2656 * access [I] Desired access rights assigned to the returned handle.
2657 * inherit [I] Determines whether or not child processes will inherit the handle.
2658 * id [I] Process identifier of the process to get a handle to.
2660 * RETURNS
2661 * Success: Valid handle to the specified process.
2662 * Failure: NULL, check GetLastError().
2664 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2666 NTSTATUS status;
2667 HANDLE handle;
2668 OBJECT_ATTRIBUTES attr;
2669 CLIENT_ID cid;
2671 cid.UniqueProcess = ULongToHandle(id);
2672 cid.UniqueThread = 0; /* FIXME ? */
2674 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2675 attr.RootDirectory = NULL;
2676 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2677 attr.SecurityDescriptor = NULL;
2678 attr.SecurityQualityOfService = NULL;
2679 attr.ObjectName = NULL;
2681 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2683 status = NtOpenProcess(&handle, access, &attr, &cid);
2684 if (status != STATUS_SUCCESS)
2686 SetLastError( RtlNtStatusToDosError(status) );
2687 return NULL;
2689 return handle;
2693 /*********************************************************************
2694 * GetProcessId (KERNEL32.@)
2696 * Gets the a unique identifier of a process.
2698 * PARAMS
2699 * hProcess [I] Handle to the process.
2701 * RETURNS
2702 * Success: TRUE.
2703 * Failure: FALSE, check GetLastError().
2705 * NOTES
2707 * The identifier is unique only on the machine and only until the process
2708 * exits (including system shutdown).
2710 DWORD WINAPI GetProcessId( HANDLE hProcess )
2712 NTSTATUS status;
2713 PROCESS_BASIC_INFORMATION pbi;
2715 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2716 sizeof(pbi), NULL);
2717 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2718 SetLastError( RtlNtStatusToDosError(status) );
2719 return 0;
2723 /*********************************************************************
2724 * CloseHandle (KERNEL32.@)
2726 * Closes a handle.
2728 * PARAMS
2729 * handle [I] Handle to close.
2731 * RETURNS
2732 * Success: TRUE.
2733 * Failure: FALSE, check GetLastError().
2735 BOOL WINAPI CloseHandle( HANDLE handle )
2737 NTSTATUS status;
2739 /* stdio handles need special treatment */
2740 if (handle == (HANDLE)STD_INPUT_HANDLE)
2741 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
2742 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
2743 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
2744 else if (handle == (HANDLE)STD_ERROR_HANDLE)
2745 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
2747 if (is_console_handle(handle))
2748 return CloseConsoleHandle(handle);
2750 status = NtClose( handle );
2751 if (status) SetLastError( RtlNtStatusToDosError(status) );
2752 return !status;
2756 /*********************************************************************
2757 * GetHandleInformation (KERNEL32.@)
2759 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2761 OBJECT_DATA_INFORMATION info;
2762 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2764 if (status) SetLastError( RtlNtStatusToDosError(status) );
2765 else if (flags)
2767 *flags = 0;
2768 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2769 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2771 return !status;
2775 /*********************************************************************
2776 * SetHandleInformation (KERNEL32.@)
2778 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2780 OBJECT_DATA_INFORMATION info;
2781 NTSTATUS status;
2783 /* if not setting both fields, retrieve current value first */
2784 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2785 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2787 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2789 SetLastError( RtlNtStatusToDosError(status) );
2790 return FALSE;
2793 if (mask & HANDLE_FLAG_INHERIT)
2794 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2795 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2796 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2798 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2799 if (status) SetLastError( RtlNtStatusToDosError(status) );
2800 return !status;
2804 /*********************************************************************
2805 * DuplicateHandle (KERNEL32.@)
2807 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2808 HANDLE dest_process, HANDLE *dest,
2809 DWORD access, BOOL inherit, DWORD options )
2811 NTSTATUS status;
2813 if (is_console_handle(source))
2815 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2816 if (source_process != dest_process ||
2817 source_process != GetCurrentProcess())
2819 SetLastError(ERROR_INVALID_PARAMETER);
2820 return FALSE;
2822 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2823 return (*dest != INVALID_HANDLE_VALUE);
2825 status = NtDuplicateObject( source_process, source, dest_process, dest,
2826 access, inherit ? OBJ_INHERIT : 0, options );
2827 if (status) SetLastError( RtlNtStatusToDosError(status) );
2828 return !status;
2832 /***********************************************************************
2833 * ConvertToGlobalHandle (KERNEL32.@)
2835 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2837 HANDLE ret = INVALID_HANDLE_VALUE;
2838 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2839 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2840 return ret;
2844 /***********************************************************************
2845 * SetHandleContext (KERNEL32.@)
2847 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2849 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2850 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2851 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2852 return FALSE;
2856 /***********************************************************************
2857 * GetHandleContext (KERNEL32.@)
2859 DWORD WINAPI GetHandleContext(HANDLE hnd)
2861 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2862 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2863 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2864 return 0;
2868 /***********************************************************************
2869 * CreateSocketHandle (KERNEL32.@)
2871 HANDLE WINAPI CreateSocketHandle(void)
2873 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2874 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2875 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2876 return INVALID_HANDLE_VALUE;
2880 /***********************************************************************
2881 * SetPriorityClass (KERNEL32.@)
2883 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2885 NTSTATUS status;
2886 PROCESS_PRIORITY_CLASS ppc;
2888 ppc.Foreground = FALSE;
2889 switch (priorityclass)
2891 case IDLE_PRIORITY_CLASS:
2892 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2893 case BELOW_NORMAL_PRIORITY_CLASS:
2894 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2895 case NORMAL_PRIORITY_CLASS:
2896 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2897 case ABOVE_NORMAL_PRIORITY_CLASS:
2898 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2899 case HIGH_PRIORITY_CLASS:
2900 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2901 case REALTIME_PRIORITY_CLASS:
2902 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2903 default:
2904 SetLastError(ERROR_INVALID_PARAMETER);
2905 return FALSE;
2908 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2909 &ppc, sizeof(ppc));
2911 if (status != STATUS_SUCCESS)
2913 SetLastError( RtlNtStatusToDosError(status) );
2914 return FALSE;
2916 return TRUE;
2920 /***********************************************************************
2921 * GetPriorityClass (KERNEL32.@)
2923 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2925 NTSTATUS status;
2926 PROCESS_BASIC_INFORMATION pbi;
2928 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2929 sizeof(pbi), NULL);
2930 if (status != STATUS_SUCCESS)
2932 SetLastError( RtlNtStatusToDosError(status) );
2933 return 0;
2935 switch (pbi.BasePriority)
2937 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2938 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2939 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2940 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2941 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2942 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2944 SetLastError( ERROR_INVALID_PARAMETER );
2945 return 0;
2949 /***********************************************************************
2950 * SetProcessAffinityMask (KERNEL32.@)
2952 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2954 NTSTATUS status;
2956 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2957 &affmask, sizeof(DWORD_PTR));
2958 if (status)
2960 SetLastError( RtlNtStatusToDosError(status) );
2961 return FALSE;
2963 return TRUE;
2967 /**********************************************************************
2968 * GetProcessAffinityMask (KERNEL32.@)
2970 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2971 PDWORD_PTR lpProcessAffinityMask,
2972 PDWORD_PTR lpSystemAffinityMask )
2974 PROCESS_BASIC_INFORMATION pbi;
2975 NTSTATUS status;
2977 status = NtQueryInformationProcess(hProcess,
2978 ProcessBasicInformation,
2979 &pbi, sizeof(pbi), NULL);
2980 if (status)
2982 SetLastError( RtlNtStatusToDosError(status) );
2983 return FALSE;
2985 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2986 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2987 return TRUE;
2991 /***********************************************************************
2992 * GetProcessVersion (KERNEL32.@)
2994 DWORD WINAPI GetProcessVersion( DWORD pid )
2996 HANDLE process;
2997 NTSTATUS status;
2998 PROCESS_BASIC_INFORMATION pbi;
2999 SIZE_T count;
3000 PEB peb;
3001 IMAGE_DOS_HEADER dos;
3002 IMAGE_NT_HEADERS nt;
3003 DWORD ver = 0;
3005 if (!pid || pid == GetCurrentProcessId())
3007 IMAGE_NT_HEADERS *nt;
3009 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3010 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
3011 nt->OptionalHeader.MinorSubsystemVersion);
3012 return 0;
3015 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3016 if (!process) return 0;
3018 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3019 if (status) goto err;
3021 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3022 if (status || count != sizeof(peb)) goto err;
3024 memset(&dos, 0, sizeof(dos));
3025 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3026 if (status || count != sizeof(dos)) goto err;
3027 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3029 memset(&nt, 0, sizeof(nt));
3030 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3031 if (status || count != sizeof(nt)) goto err;
3032 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3034 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3036 err:
3037 CloseHandle(process);
3039 if (status != STATUS_SUCCESS)
3040 SetLastError(RtlNtStatusToDosError(status));
3042 return ver;
3046 /***********************************************************************
3047 * SetProcessWorkingSetSize [KERNEL32.@]
3048 * Sets the min/max working set sizes for a specified process.
3050 * PARAMS
3051 * hProcess [I] Handle to the process of interest
3052 * minset [I] Specifies minimum working set size
3053 * maxset [I] Specifies maximum working set size
3055 * RETURNS
3056 * Success: TRUE
3057 * Failure: FALSE
3059 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3060 SIZE_T maxset)
3062 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3063 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3064 /* Trim the working set to zero */
3065 /* Swap the process out of physical RAM */
3067 return TRUE;
3070 /***********************************************************************
3071 * GetProcessWorkingSetSize (KERNEL32.@)
3073 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3074 PSIZE_T maxset)
3076 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3077 /* 32 MB working set size */
3078 if (minset) *minset = 32*1024*1024;
3079 if (maxset) *maxset = 32*1024*1024;
3080 return TRUE;
3084 /***********************************************************************
3085 * SetProcessShutdownParameters (KERNEL32.@)
3087 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3089 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3090 shutdown_flags = flags;
3091 shutdown_priority = level;
3092 return TRUE;
3096 /***********************************************************************
3097 * GetProcessShutdownParameters (KERNEL32.@)
3100 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3102 *lpdwLevel = shutdown_priority;
3103 *lpdwFlags = shutdown_flags;
3104 return TRUE;
3108 /***********************************************************************
3109 * GetProcessPriorityBoost (KERNEL32.@)
3111 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3113 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3115 /* Report that no boost is present.. */
3116 *pDisablePriorityBoost = FALSE;
3118 return TRUE;
3121 /***********************************************************************
3122 * SetProcessPriorityBoost (KERNEL32.@)
3124 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3126 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3127 /* Say we can do it. I doubt the program will notice that we don't. */
3128 return TRUE;
3132 /***********************************************************************
3133 * ReadProcessMemory (KERNEL32.@)
3135 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3136 SIZE_T *bytes_read )
3138 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3139 if (status) SetLastError( RtlNtStatusToDosError(status) );
3140 return !status;
3144 /***********************************************************************
3145 * WriteProcessMemory (KERNEL32.@)
3147 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3148 SIZE_T *bytes_written )
3150 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3151 if (status) SetLastError( RtlNtStatusToDosError(status) );
3152 return !status;
3156 /****************************************************************************
3157 * FlushInstructionCache (KERNEL32.@)
3159 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3161 NTSTATUS status;
3162 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3163 if (status) SetLastError( RtlNtStatusToDosError(status) );
3164 return !status;
3168 /******************************************************************
3169 * GetProcessIoCounters (KERNEL32.@)
3171 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3173 NTSTATUS status;
3175 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3176 ioc, sizeof(*ioc), NULL);
3177 if (status) SetLastError( RtlNtStatusToDosError(status) );
3178 return !status;
3181 /******************************************************************
3182 * GetProcessHandleCount (KERNEL32.@)
3184 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3186 NTSTATUS status;
3188 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3189 cnt, sizeof(*cnt), NULL);
3190 if (status) SetLastError( RtlNtStatusToDosError(status) );
3191 return !status;
3194 /******************************************************************
3195 * QueryFullProcessImageNameA (KERNEL32.@)
3197 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3199 BOOL retval;
3200 DWORD pdwSizeW = *pdwSize;
3201 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3203 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3205 if(retval)
3206 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3207 lpExeName, *pdwSize, NULL, NULL));
3208 if(retval)
3209 *pdwSize = strlen(lpExeName);
3211 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3212 return retval;
3215 /******************************************************************
3216 * QueryFullProcessImageNameW (KERNEL32.@)
3218 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3220 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3221 UNICODE_STRING *dynamic_buffer = NULL;
3222 UNICODE_STRING nt_path;
3223 UNICODE_STRING *result = NULL;
3224 NTSTATUS status;
3225 DWORD needed;
3227 RtlInitUnicodeStringEx(&nt_path, NULL);
3228 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3229 * as this is on Wine. */
3230 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3231 sizeof(buffer) - sizeof(WCHAR), &needed);
3232 if (status == STATUS_INFO_LENGTH_MISMATCH)
3234 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3235 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3236 result = dynamic_buffer;
3238 else
3239 result = (PUNICODE_STRING)buffer;
3241 if (status) goto cleanup;
3243 if (dwFlags & PROCESS_NAME_NATIVE)
3245 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3246 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3248 status = STATUS_OBJECT_PATH_NOT_FOUND;
3249 goto cleanup;
3251 result = &nt_path;
3254 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3256 status = STATUS_BUFFER_TOO_SMALL;
3257 goto cleanup;
3260 *pdwSize = result->Length/sizeof(WCHAR);
3261 memcpy( lpExeName, result->Buffer, result->Length );
3262 lpExeName[*pdwSize] = 0;
3264 cleanup:
3265 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3266 RtlFreeUnicodeString(&nt_path);
3267 if (status) SetLastError( RtlNtStatusToDosError(status) );
3268 return !status;
3271 /***********************************************************************
3272 * ProcessIdToSessionId (KERNEL32.@)
3273 * This function is available on Terminal Server 4SP4 and Windows 2000
3275 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3277 /* According to MSDN, if the calling process is not in a terminal
3278 * services environment, then the sessionid returned is zero.
3280 *sessionid_ptr = 0;
3281 return TRUE;
3285 /***********************************************************************
3286 * RegisterServiceProcess (KERNEL32.@)
3288 * A service process calls this function to ensure that it continues to run
3289 * even after a user logged off.
3291 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3293 /* I don't think that Wine needs to do anything in this function */
3294 return 1; /* success */
3298 /**********************************************************************
3299 * IsWow64Process (KERNEL32.@)
3301 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3303 ULONG pbi;
3304 NTSTATUS status;
3306 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3308 if (status != STATUS_SUCCESS)
3310 SetLastError( RtlNtStatusToDosError( status ) );
3311 return FALSE;
3313 *Wow64Process = (pbi != 0);
3314 return TRUE;
3318 /***********************************************************************
3319 * GetCurrentProcess (KERNEL32.@)
3321 * Get a handle to the current process.
3323 * PARAMS
3324 * None.
3326 * RETURNS
3327 * A handle representing the current process.
3329 #undef GetCurrentProcess
3330 HANDLE WINAPI GetCurrentProcess(void)
3332 return (HANDLE)~(ULONG_PTR)0;
3335 /***********************************************************************
3336 * CmdBatNotification (KERNEL32.@)
3338 * Notifies the system that a batch file has started or finished.
3340 * PARAMS
3341 * bBatchRunning [I] TRUE if a batch file has started or
3342 * FALSE if a batch file has finished executing.
3344 * RETURNS
3345 * Unknown.
3347 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3349 FIXME("%d\n", bBatchRunning);
3350 return FALSE;
3354 /***********************************************************************
3355 * RegisterApplicationRestart (KERNEL32.@)
3357 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3359 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3361 return S_OK;
3364 /**********************************************************************
3365 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3367 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3369 FIXME("stub\n");
3370 return 0;