devenum: Implement IMoniker::GetClassID().
[wine.git] / dlls / kernel32 / process.c
blob5b8a3d335e7d498aafddf17c1da09901f5784cfe
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>
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #ifdef __APPLE__
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <pthread.h>
53 #endif
55 #include "ntstatus.h"
56 #define WIN32_NO_STATUS
57 #include "winternl.h"
58 #include "kernel_private.h"
59 #include "psapi.h"
60 #include "wine/library.h"
61 #include "wine/server.h"
62 #include "wine/unicode.h"
63 #include "wine/debug.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(process);
66 WINE_DECLARE_DEBUG_CHANNEL(file);
67 WINE_DECLARE_DEBUG_CHANNEL(relay);
69 #ifdef __APPLE__
70 extern char **__wine_get_main_environment(void);
71 #else
72 extern char **__wine_main_environ;
73 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
74 #endif
76 typedef struct
78 LPSTR lpEnvAddress;
79 LPSTR lpCmdLine;
80 LPSTR lpCmdShow;
81 DWORD dwReserved;
82 } LOADPARMS32;
84 static DWORD shutdown_flags = 0;
85 static DWORD shutdown_priority = 0x280;
86 static BOOL is_wow64;
87 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
89 HMODULE kernel32_handle = 0;
90 SYSTEM_BASIC_INFORMATION system_info = { 0 };
92 const WCHAR *DIR_Windows = NULL;
93 const WCHAR *DIR_System = NULL;
94 const WCHAR *DIR_SysWow64 = NULL;
96 /* Process flags */
97 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
98 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
99 #define PDB32_DOS_PROC 0x0010 /* Dos process */
100 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
101 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
102 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
104 static const WCHAR exeW[] = {'.','e','x','e',0};
105 static const WCHAR comW[] = {'.','c','o','m',0};
106 static const WCHAR batW[] = {'.','b','a','t',0};
107 static const WCHAR cmdW[] = {'.','c','m','d',0};
108 static const WCHAR pifW[] = {'.','p','i','f',0};
109 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
111 static void exec_process( LPCWSTR name );
113 extern void SHELL_LoadRegistry(void);
116 /***********************************************************************
117 * contains_path
119 static inline BOOL contains_path( LPCWSTR name )
121 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
125 /***********************************************************************
126 * is_special_env_var
128 * Check if an environment variable needs to be handled specially when
129 * passed through the Unix environment (i.e. prefixed with "WINE").
131 static inline BOOL is_special_env_var( const char *var )
133 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
134 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
135 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
136 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
137 !strncmp( var, "TMP=", sizeof("TMP=")-1 ) ||
138 !strncmp( var, "QT_", sizeof("QT_")-1 ));
142 /***********************************************************************
143 * is_path_prefix
145 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
147 unsigned int len = strlenW( prefix );
149 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
150 while (filename[len] == '\\') len++;
151 return len;
155 /***************************************************************************
156 * get_builtin_path
158 * Get the path of a builtin module when the native file does not exist.
160 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
161 UINT size, struct binary_info *binary_info )
163 WCHAR *file_part;
164 UINT len;
165 void *redir_disabled = 0;
166 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
168 /* builtin names cannot be empty or contain spaces */
169 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
171 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
172 Wow64RevertWow64FsRedirection( redir_disabled );
174 if (contains_path( libname ))
176 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
177 filename, &file_part ) > size * sizeof(WCHAR))
178 return FALSE; /* too long */
180 if ((len = is_path_prefix( DIR_System, filename )))
182 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
184 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
186 flags = 0;
188 else return FALSE;
190 if (filename + len != file_part) return FALSE;
192 else
194 len = strlenW( DIR_System );
195 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
196 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
197 file_part = filename + len;
198 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
199 strcpyW( file_part, libname );
200 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
202 if (ext && !strchrW( file_part, '.' ))
204 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
205 return FALSE; /* too long */
206 strcatW( file_part, ext );
208 binary_info->type = BINARY_UNIX_LIB;
209 binary_info->flags = flags;
210 binary_info->res_start = NULL;
211 binary_info->res_end = NULL;
212 /* assume current arch */
213 #if defined(__i386__) || defined(__x86_64__)
214 binary_info->arch = (flags & BINARY_FLAG_64BIT) ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
215 #elif defined(__powerpc__)
216 binary_info->arch = IMAGE_FILE_MACHINE_POWERPC;
217 #elif defined(__arm__) && !defined(__ARMEB__)
218 binary_info->arch = IMAGE_FILE_MACHINE_ARMNT;
219 #elif defined(__aarch64__)
220 binary_info->arch = IMAGE_FILE_MACHINE_ARM64;
221 #else
222 binary_info->arch = IMAGE_FILE_MACHINE_UNKNOWN;
223 #endif
224 return TRUE;
228 /***********************************************************************
229 * open_exe_file
231 * Open a specific exe file, taking load order into account.
232 * Returns the file handle or 0 for a builtin exe.
234 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
236 HANDLE handle;
238 TRACE("looking for %s\n", debugstr_w(name) );
240 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
241 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
243 WCHAR buffer[MAX_PATH];
244 /* file doesn't exist, check for builtin */
245 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
246 handle = 0;
248 else MODULE_get_binary_info( handle, binary_info );
250 return handle;
254 /***********************************************************************
255 * find_exe_file
257 * Open an exe file, and return the full name and file handle.
258 * Returns FALSE if file could not be found.
260 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
261 HANDLE *handle, struct binary_info *binary_info )
263 TRACE("looking for %s\n", debugstr_w(name) );
265 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
266 /* no builtin found, try native without extension in case it is a Unix app */
267 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
269 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
270 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
271 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
273 MODULE_get_binary_info( *handle, binary_info );
274 return TRUE;
276 return FALSE;
280 /***********************************************************************
281 * build_initial_environment
283 * Build the Win32 environment from the Unix environment
285 static BOOL build_initial_environment(void)
287 SIZE_T size = 1;
288 char **e;
289 WCHAR *p, *endptr;
290 void *ptr;
291 char **env = __wine_get_main_environment();
293 /* Compute the total size of the Unix environment */
294 for (e = env; *e; e++)
296 if (is_special_env_var( *e )) continue;
297 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
299 size *= sizeof(WCHAR);
301 /* Now allocate the environment */
302 ptr = NULL;
303 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
304 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
305 return FALSE;
307 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
308 endptr = p + size / sizeof(WCHAR);
310 /* And fill it with the Unix environment */
311 for (e = env; *e; e++)
313 char *str = *e;
315 /* skip Unix special variables and use the Wine variants instead */
316 if (!strncmp( str, "WINE", 4 ))
318 if (is_special_env_var( str + 4 )) str += 4;
319 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
321 else if (is_special_env_var( str )) continue; /* skip it */
323 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
324 p += strlenW(p) + 1;
326 *p = 0;
327 return TRUE;
331 /***********************************************************************
332 * set_registry_variables
334 * Set environment variables by enumerating the values of a key;
335 * helper for set_registry_environment().
336 * Note that Windows happily truncates the value if it's too big.
338 static void set_registry_variables( HANDLE hkey, ULONG type )
340 static const WCHAR pathW[] = {'P','A','T','H'};
341 static const WCHAR sep[] = {';',0};
342 UNICODE_STRING env_name, env_value;
343 NTSTATUS status;
344 DWORD size;
345 int index;
346 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
347 WCHAR tmpbuf[1024];
348 UNICODE_STRING tmp;
349 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
351 tmp.Buffer = tmpbuf;
352 tmp.MaximumLength = sizeof(tmpbuf);
354 for (index = 0; ; index++)
356 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
357 buffer, sizeof(buffer), &size );
358 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
359 break;
360 if (info->Type != type)
361 continue;
362 env_name.Buffer = info->Name;
363 env_name.Length = env_name.MaximumLength = info->NameLength;
364 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
365 env_value.Length = info->DataLength;
366 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
367 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
368 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
369 if (!env_value.Length) continue;
370 if (info->Type == REG_EXPAND_SZ)
372 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
373 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
374 RtlCopyUnicodeString( &env_value, &tmp );
376 /* PATH is magic */
377 if (env_name.Length == sizeof(pathW) &&
378 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
379 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
381 RtlAppendUnicodeToString( &tmp, sep );
382 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
383 RtlCopyUnicodeString( &env_value, &tmp );
385 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
390 /***********************************************************************
391 * set_registry_environment
393 * Set the environment variables specified in the registry.
395 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
396 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
397 * on the order in which the variables are processed. But on Windows it
398 * does not really matter since they only use %SystemDrive% and
399 * %SystemRoot% which are predefined. But Wine defines these in the
400 * registry, so we need two passes.
402 static BOOL set_registry_environment( BOOL volatile_only )
404 static const WCHAR env_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
405 'M','a','c','h','i','n','e','\\',
406 'S','y','s','t','e','m','\\',
407 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
408 'C','o','n','t','r','o','l','\\',
409 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
410 'E','n','v','i','r','o','n','m','e','n','t',0};
411 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
412 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};
414 OBJECT_ATTRIBUTES attr;
415 UNICODE_STRING nameW;
416 HANDLE hkey;
417 BOOL ret = FALSE;
419 attr.Length = sizeof(attr);
420 attr.RootDirectory = 0;
421 attr.ObjectName = &nameW;
422 attr.Attributes = 0;
423 attr.SecurityDescriptor = NULL;
424 attr.SecurityQualityOfService = NULL;
426 /* first the system environment variables */
427 RtlInitUnicodeString( &nameW, env_keyW );
428 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
430 set_registry_variables( hkey, REG_SZ );
431 set_registry_variables( hkey, REG_EXPAND_SZ );
432 NtClose( hkey );
433 ret = TRUE;
436 /* then the ones for the current user */
437 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
438 RtlInitUnicodeString( &nameW, envW );
439 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
441 set_registry_variables( hkey, REG_SZ );
442 set_registry_variables( hkey, REG_EXPAND_SZ );
443 NtClose( hkey );
446 RtlInitUnicodeString( &nameW, volatile_envW );
447 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
449 set_registry_variables( hkey, REG_SZ );
450 set_registry_variables( hkey, REG_EXPAND_SZ );
451 NtClose( hkey );
454 NtClose( attr.RootDirectory );
455 return ret;
459 /***********************************************************************
460 * get_reg_value
462 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
464 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
465 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
466 DWORD len, size = sizeof(buffer);
467 WCHAR *ret = NULL;
468 UNICODE_STRING nameW;
470 RtlInitUnicodeString( &nameW, name );
471 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
472 return NULL;
474 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
475 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
477 if (info->Type == REG_EXPAND_SZ)
479 UNICODE_STRING value, expanded;
481 value.MaximumLength = len * sizeof(WCHAR);
482 value.Buffer = (WCHAR *)info->Data;
483 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
484 value.Length = len * sizeof(WCHAR);
485 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
486 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
487 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
488 else RtlFreeUnicodeString( &expanded );
490 else if (info->Type == REG_SZ)
492 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
494 memcpy( ret, info->Data, len * sizeof(WCHAR) );
495 ret[len] = 0;
498 return ret;
502 /***********************************************************************
503 * set_additional_environment
505 * Set some additional environment variables not specified in the registry.
507 static void set_additional_environment(void)
509 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
510 'M','a','c','h','i','n','e','\\',
511 'S','o','f','t','w','a','r','e','\\',
512 'M','i','c','r','o','s','o','f','t','\\',
513 'W','i','n','d','o','w','s',' ','N','T','\\',
514 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
515 'P','r','o','f','i','l','e','L','i','s','t',0};
516 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
517 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
518 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
519 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
520 OBJECT_ATTRIBUTES attr;
521 UNICODE_STRING nameW;
522 WCHAR *profile_dir = NULL, *all_users_dir = NULL;
523 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
524 HANDLE hkey;
525 DWORD len;
527 /* ComputerName */
528 len = sizeof(buf) / sizeof(WCHAR);
529 if (GetComputerNameW( buf, &len ))
530 SetEnvironmentVariableW( computernameW, buf );
532 /* set the ALLUSERSPROFILE variables */
534 attr.Length = sizeof(attr);
535 attr.RootDirectory = 0;
536 attr.ObjectName = &nameW;
537 attr.Attributes = 0;
538 attr.SecurityDescriptor = NULL;
539 attr.SecurityQualityOfService = NULL;
540 RtlInitUnicodeString( &nameW, profile_keyW );
541 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
543 profile_dir = get_reg_value( hkey, profiles_valueW );
544 all_users_dir = get_reg_value( hkey, all_users_valueW );
545 NtClose( hkey );
548 if (profile_dir && all_users_dir)
550 WCHAR *value, *p;
552 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
553 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
554 strcpyW( value, profile_dir );
555 p = value + strlenW(value);
556 if (p > value && p[-1] != '\\') *p++ = '\\';
557 strcpyW( p, all_users_dir );
558 SetEnvironmentVariableW( allusersW, value );
559 HeapFree( GetProcessHeap(), 0, value );
562 HeapFree( GetProcessHeap(), 0, all_users_dir );
563 HeapFree( GetProcessHeap(), 0, profile_dir );
566 /***********************************************************************
567 * set_wow64_environment
569 * Set the environment variables that change across 32/64/Wow64.
571 static void set_wow64_environment(void)
573 static const WCHAR archW[] = {'P','R','O','C','E','S','S','O','R','_','A','R','C','H','I','T','E','C','T','U','R','E',0};
574 static const WCHAR arch6432W[] = {'P','R','O','C','E','S','S','O','R','_','A','R','C','H','I','T','E','W','6','4','3','2',0};
575 static const WCHAR x86W[] = {'x','8','6',0};
576 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
577 'M','a','c','h','i','n','e','\\',
578 'S','o','f','t','w','a','r','e','\\',
579 'M','i','c','r','o','s','o','f','t','\\',
580 'W','i','n','d','o','w','s','\\',
581 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
582 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
583 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
584 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
585 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
586 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
587 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
588 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
589 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
591 OBJECT_ATTRIBUTES attr;
592 UNICODE_STRING nameW;
593 WCHAR arch[64];
594 WCHAR *value;
595 HANDLE hkey;
597 /* set the PROCESSOR_ARCHITECTURE variable */
599 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
601 if (is_win64)
603 SetEnvironmentVariableW( archW, arch );
604 SetEnvironmentVariableW( arch6432W, NULL );
607 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
609 if (is_wow64)
611 SetEnvironmentVariableW( arch6432W, arch );
612 SetEnvironmentVariableW( archW, x86W );
616 attr.Length = sizeof(attr);
617 attr.RootDirectory = 0;
618 attr.ObjectName = &nameW;
619 attr.Attributes = 0;
620 attr.SecurityDescriptor = NULL;
621 attr.SecurityQualityOfService = NULL;
622 RtlInitUnicodeString( &nameW, versionW );
623 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
625 /* set the ProgramFiles variables */
627 if ((value = get_reg_value( hkey, progdirW )))
629 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
630 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
631 HeapFree( GetProcessHeap(), 0, value );
633 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
635 SetEnvironmentVariableW( progfilesW, value );
636 HeapFree( GetProcessHeap(), 0, value );
639 /* set the CommonProgramFiles variables */
641 if ((value = get_reg_value( hkey, commondirW )))
643 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
644 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
645 HeapFree( GetProcessHeap(), 0, value );
647 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
649 SetEnvironmentVariableW( commonfilesW, value );
650 HeapFree( GetProcessHeap(), 0, value );
653 NtClose( hkey );
656 /***********************************************************************
657 * set_library_wargv
659 * Set the Wine library Unicode argv global variables.
661 static void set_library_wargv( char **argv )
663 int argc;
664 char *q;
665 WCHAR *p;
666 WCHAR **wargv;
667 DWORD total = 0;
669 for (argc = 0; argv[argc]; argc++)
670 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
672 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
673 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
674 p = (WCHAR *)(wargv + argc + 1);
675 for (argc = 0; argv[argc]; argc++)
677 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
678 wargv[argc] = p;
679 p += reslen;
680 total -= reslen;
682 wargv[argc] = NULL;
684 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
686 for (argc = 0; wargv[argc]; argc++)
687 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
689 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
690 q = (char *)(argv + argc + 1);
691 for (argc = 0; wargv[argc]; argc++)
693 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
694 argv[argc] = q;
695 q += reslen;
696 total -= reslen;
698 argv[argc] = NULL;
700 __wine_main_argc = argc;
701 __wine_main_argv = argv;
702 __wine_main_wargv = wargv;
706 /***********************************************************************
707 * update_library_argv0
709 * Update the argv[0] global variable with the binary we have found.
711 static void update_library_argv0( const WCHAR *argv0 )
713 DWORD len = strlenW( argv0 );
715 if (len > strlenW( __wine_main_wargv[0] ))
717 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
719 strcpyW( __wine_main_wargv[0], argv0 );
721 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
722 if (len > strlen( __wine_main_argv[0] ) + 1)
724 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
726 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
730 /***********************************************************************
731 * build_command_line
733 * Build the command line of a process from the argv array.
735 * Note that it does NOT necessarily include the file name.
736 * Sometimes we don't even have any command line options at all.
738 * We must quote and escape characters so that the argv array can be rebuilt
739 * from the command line:
740 * - spaces and tabs must be quoted
741 * 'a b' -> '"a b"'
742 * - quotes must be escaped
743 * '"' -> '\"'
744 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
745 * resulting in an odd number of '\' followed by a '"'
746 * '\"' -> '\\\"'
747 * '\\"' -> '\\\\\"'
748 * - '\'s are followed by the closing '"' must be doubled,
749 * resulting in an even number of '\' followed by a '"'
750 * ' \' -> '" \\"'
751 * ' \\' -> '" \\\\"'
752 * - '\'s that are not followed by a '"' can be left as is
753 * 'a\b' == 'a\b'
754 * 'a\\b' == 'a\\b'
756 static BOOL build_command_line( WCHAR **argv )
758 int len;
759 WCHAR **arg;
760 LPWSTR p;
761 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
763 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
765 len = 0;
766 for (arg = argv; *arg; arg++)
768 BOOL has_space;
769 int bcount;
770 WCHAR* a;
772 has_space=FALSE;
773 bcount=0;
774 a=*arg;
775 if( !*a ) has_space=TRUE;
776 while (*a!='\0') {
777 if (*a=='\\') {
778 bcount++;
779 } else {
780 if (*a==' ' || *a=='\t') {
781 has_space=TRUE;
782 } else if (*a=='"') {
783 /* doubling of '\' preceding a '"',
784 * plus escaping of said '"'
786 len+=2*bcount+1;
788 bcount=0;
790 a++;
792 len+=(a-*arg)+1 /* for the separating space */;
793 if (has_space)
794 len+=2+bcount; /* for the quotes and doubling of '\' preceding the closing quote */
797 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
798 return FALSE;
800 p = rupp->CommandLine.Buffer;
801 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
802 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
803 for (arg = argv; *arg; arg++)
805 BOOL has_space,has_quote;
806 WCHAR* a;
807 int bcount;
809 /* Check for quotes and spaces in this argument */
810 has_space=has_quote=FALSE;
811 a=*arg;
812 if( !*a ) has_space=TRUE;
813 while (*a!='\0') {
814 if (*a==' ' || *a=='\t') {
815 has_space=TRUE;
816 if (has_quote)
817 break;
818 } else if (*a=='"') {
819 has_quote=TRUE;
820 if (has_space)
821 break;
823 a++;
826 /* Now transfer it to the command line */
827 if (has_space)
828 *p++='"';
829 if (has_quote || has_space) {
830 bcount=0;
831 a=*arg;
832 while (*a!='\0') {
833 if (*a=='\\') {
834 *p++=*a;
835 bcount++;
836 } else {
837 if (*a=='"') {
838 int i;
840 /* Double all the '\\' preceding this '"', plus one */
841 for (i=0;i<=bcount;i++)
842 *p++='\\';
843 *p++='"';
844 } else {
845 *p++=*a;
847 bcount=0;
849 a++;
851 } else {
852 WCHAR* x = *arg;
853 while ((*p=*x++)) p++;
855 if (has_space) {
856 int i;
858 /* Double all the '\' preceding the closing quote */
859 for (i=0;i<bcount;i++)
860 *p++='\\';
861 *p++='"';
863 *p++=' ';
865 if (p > rupp->CommandLine.Buffer)
866 p--; /* remove last space */
867 *p = '\0';
869 return TRUE;
873 /***********************************************************************
874 * init_current_directory
876 * Initialize the current directory from the Unix cwd or the parent info.
878 static void init_current_directory( CURDIR *cur_dir )
880 UNICODE_STRING dir_str;
881 const char *pwd;
882 char *cwd;
883 int size;
885 /* if we received a cur dir from the parent, try this first */
887 if (cur_dir->DosPath.Length)
889 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
892 /* now try to get it from the Unix cwd */
894 for (size = 256; ; size *= 2)
896 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
897 if (getcwd( cwd, size )) break;
898 HeapFree( GetProcessHeap(), 0, cwd );
899 if (errno == ERANGE) continue;
900 cwd = NULL;
901 break;
904 /* try to use PWD if it is valid, so that we don't resolve symlinks */
906 pwd = getenv( "PWD" );
907 if (cwd)
909 struct stat st1, st2;
911 if (!pwd || stat( pwd, &st1 ) == -1 ||
912 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
913 pwd = cwd;
916 if (pwd)
918 ANSI_STRING unix_name;
919 UNICODE_STRING nt_name;
920 RtlInitAnsiString( &unix_name, pwd );
921 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
923 UNICODE_STRING dos_path;
924 /* skip the \??\ prefix, nt_name is 0 terminated */
925 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
926 RtlSetCurrentDirectory_U( &dos_path );
927 RtlFreeUnicodeString( &nt_name );
931 if (!cur_dir->DosPath.Length) /* still not initialized */
933 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
934 "starting in the Windows directory.\n", cwd ? cwd : "" );
935 RtlInitUnicodeString( &dir_str, DIR_Windows );
936 RtlSetCurrentDirectory_U( &dir_str );
938 HeapFree( GetProcessHeap(), 0, cwd );
940 done:
941 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
945 /***********************************************************************
946 * init_windows_dirs
948 * Initialize the windows and system directories from the environment.
950 static void init_windows_dirs(void)
952 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
954 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
955 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
956 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
957 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
958 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
960 DWORD len;
961 WCHAR *buffer;
963 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
965 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
966 GetEnvironmentVariableW( windirW, buffer, len );
967 DIR_Windows = buffer;
969 else DIR_Windows = default_windirW;
971 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
973 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
974 GetEnvironmentVariableW( winsysdirW, buffer, len );
975 DIR_System = buffer;
977 else
979 len = strlenW( DIR_Windows );
980 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
981 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
982 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
983 DIR_System = buffer;
986 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
987 ERR( "directory %s could not be created, error %u\n",
988 debugstr_w(DIR_Windows), GetLastError() );
989 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
990 ERR( "directory %s could not be created, error %u\n",
991 debugstr_w(DIR_System), GetLastError() );
993 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
995 len = strlenW( DIR_Windows );
996 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
997 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
998 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
999 DIR_SysWow64 = buffer;
1000 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1001 ERR( "directory %s could not be created, error %u\n",
1002 debugstr_w(DIR_SysWow64), GetLastError() );
1005 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
1006 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
1008 /* set the directories in ntdll too */
1009 __wine_init_windows_dir( DIR_Windows, DIR_System );
1013 /***********************************************************************
1014 * start_wineboot
1016 * Start the wineboot process if necessary. Return the handles to wait on.
1018 static void start_wineboot( HANDLE handles[2] )
1020 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1022 handles[1] = 0;
1023 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1025 ERR( "failed to create wineboot event, expect trouble\n" );
1026 return;
1028 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1030 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1031 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1032 STARTUPINFOW si;
1033 PROCESS_INFORMATION pi;
1034 void *redir;
1035 WCHAR app[MAX_PATH];
1036 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1038 memset( &si, 0, sizeof(si) );
1039 si.cb = sizeof(si);
1040 si.dwFlags = STARTF_USESTDHANDLES;
1041 si.hStdInput = 0;
1042 si.hStdOutput = 0;
1043 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1045 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1046 lstrcatW( app, wineboot );
1048 Wow64DisableWow64FsRedirection( &redir );
1049 strcpyW( cmdline, app );
1050 strcatW( cmdline, args );
1051 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1053 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1054 CloseHandle( pi.hThread );
1055 handles[1] = pi.hProcess;
1057 else
1059 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1060 CloseHandle( handles[0] );
1061 handles[0] = 0;
1063 Wow64RevertWow64FsRedirection( redir );
1068 #ifdef __i386__
1069 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1070 __ASM_GLOBAL_FUNC( call_process_entry,
1071 "pushl %ebp\n\t"
1072 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1073 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1074 "movl %esp,%ebp\n\t"
1075 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1076 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1077 "pushl 8(%ebp)\n\t"
1078 "call *12(%ebp)\n\t"
1079 "leave\n\t"
1080 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1081 __ASM_CFI(".cfi_same_value %ebp\n\t")
1082 "ret" )
1083 #else
1084 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1086 return entry( peb );
1088 #endif
1090 /***********************************************************************
1091 * start_process
1093 * Startup routine of a new process. Runs on the new process stack.
1095 static DWORD WINAPI start_process( LPTHREAD_START_ROUTINE entry )
1097 BOOL being_debugged;
1098 PEB *peb = NtCurrentTeb()->Peb;
1100 if (!entry)
1102 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1103 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1104 ExitThread( 1 );
1107 if (TRACE_ON(relay))
1108 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1109 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1111 if (!CheckRemoteDebuggerPresent( GetCurrentProcess(), &being_debugged ))
1112 being_debugged = FALSE;
1114 SetLastError( 0 ); /* clear error code */
1115 if (being_debugged) DbgBreakPoint();
1116 return call_process_entry( peb, entry );
1120 /***********************************************************************
1121 * set_process_name
1123 * Change the process name in the ps output.
1125 static void set_process_name( int argc, char *argv[] )
1127 BOOL shift_strings;
1128 char *p, *name;
1129 int i;
1131 #ifdef HAVE_SETPROCTITLE
1132 setproctitle("-%s", argv[1]);
1133 shift_strings = FALSE;
1134 #else
1135 p = argv[0];
1137 shift_strings = (argc >= 2);
1138 for (i = 1; i < argc; i++)
1140 p += strlen(p) + 1;
1141 if (p != argv[i])
1143 shift_strings = FALSE;
1144 break;
1147 #endif
1149 if (shift_strings)
1151 int offset = argv[1] - argv[0];
1152 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1153 memmove( argv[0], argv[1], end - argv[1] );
1154 memset( end - offset, 0, offset );
1155 for (i = 1; i < argc; i++)
1156 argv[i-1] = argv[i] - offset;
1157 argv[i-1] = NULL;
1159 else
1161 /* remove argv[0] */
1162 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1165 name = argv[0];
1166 if ((p = strrchr( name, '\\' ))) name = p + 1;
1167 if ((p = strrchr( name, '/' ))) name = p + 1;
1169 #if defined(HAVE_SETPROGNAME)
1170 setprogname( name );
1171 #endif
1173 #ifdef HAVE_PRCTL
1174 #ifndef PR_SET_NAME
1175 # define PR_SET_NAME 15
1176 #endif
1177 prctl( PR_SET_NAME, name );
1178 #endif /* HAVE_PRCTL */
1182 /***********************************************************************
1183 * __wine_kernel_init
1185 * Wine initialisation: load and start the main exe file.
1187 void CDECL __wine_kernel_init(void)
1189 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1190 static const WCHAR dotW[] = {'.',0};
1192 WCHAR *p, main_exe_name[MAX_PATH+1];
1193 PEB *peb = NtCurrentTeb()->Peb;
1194 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1195 HANDLE boot_events[2];
1196 BOOL got_environment = TRUE;
1198 /* Initialize everything */
1200 setbuf(stdout,NULL);
1201 setbuf(stderr,NULL);
1202 kernel32_handle = GetModuleHandleW(kernel32W);
1203 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1205 LOCALE_Init();
1207 if (!params->Environment)
1209 /* Copy the parent environment */
1210 if (!build_initial_environment()) exit(1);
1212 /* convert old configuration to new format */
1213 convert_old_config();
1215 got_environment = set_registry_environment( FALSE );
1216 set_additional_environment();
1219 init_windows_dirs();
1220 init_current_directory( &params->CurrentDirectory );
1222 set_process_name( __wine_main_argc, __wine_main_argv );
1223 set_library_wargv( __wine_main_argv );
1224 boot_events[0] = boot_events[1] = 0;
1226 if (peb->ProcessParameters->ImagePathName.Buffer)
1228 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1230 else
1232 struct binary_info binary_info;
1234 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1235 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1237 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1238 ExitProcess( GetLastError() );
1240 update_library_argv0( main_exe_name );
1241 if (!build_command_line( __wine_main_wargv )) goto error;
1242 start_wineboot( boot_events );
1245 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1246 p = strrchrW( main_exe_name, '.' );
1247 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1249 TRACE( "starting process name=%s argv[0]=%s\n",
1250 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1252 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1253 MODULE_get_dll_load_path(main_exe_name) );
1255 if (boot_events[0])
1257 DWORD timeout = 2 * 60 * 1000, count = 1;
1259 if (boot_events[1]) count++;
1260 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1261 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1262 ERR( "boot event wait timed out\n" );
1263 CloseHandle( boot_events[0] );
1264 if (boot_events[1]) CloseHandle( boot_events[1] );
1265 /* reload environment now that wineboot has run */
1266 set_registry_environment( got_environment );
1267 set_additional_environment();
1269 set_wow64_environment();
1271 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1273 DWORD_PTR args[1];
1274 WCHAR msgW[1024];
1275 char msg[1024];
1276 DWORD error = GetLastError();
1278 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1279 if (error == ERROR_BAD_EXE_FORMAT ||
1280 error == ERROR_INVALID_ADDRESS ||
1281 error == ERROR_NOT_ENOUGH_MEMORY)
1283 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1284 /* if we get back here, it failed */
1286 else if (error == ERROR_MOD_NOT_FOUND)
1288 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1289 else p = main_exe_name;
1290 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1292 /* args 1 and 2 are --app-name full_path */
1293 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1294 debugstr_w(__wine_main_wargv[3]) );
1295 ExitProcess( ERROR_BAD_EXE_FORMAT );
1297 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1298 ExitProcess( ERROR_FILE_NOT_FOUND );
1300 args[0] = (DWORD_PTR)main_exe_name;
1301 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1302 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1303 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1304 MESSAGE( "wine: %s", msg );
1305 ExitProcess( error );
1308 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1310 LdrInitializeThunk( start_process, 0, 0, 0 );
1312 error:
1313 ExitProcess( GetLastError() );
1317 /***********************************************************************
1318 * build_argv
1320 * Build an argv array from a command-line.
1321 * 'reserved' is the number of args to reserve before the first one.
1323 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1325 int argc;
1326 char** argv;
1327 char *arg,*s,*d,*cmdline;
1328 int in_quotes,bcount,len;
1330 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1331 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1332 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1334 argc=reserved+1;
1335 bcount=0;
1336 in_quotes=0;
1337 s=cmdline;
1338 while (1) {
1339 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1340 /* space */
1341 argc++;
1342 /* skip the remaining spaces */
1343 while (*s==' ' || *s=='\t') {
1344 s++;
1346 if (*s=='\0')
1347 break;
1348 bcount=0;
1349 continue;
1350 } else if (*s=='\\') {
1351 /* '\', count them */
1352 bcount++;
1353 } else if ((*s=='"') && ((bcount & 1)==0)) {
1354 /* unescaped '"' */
1355 in_quotes=!in_quotes;
1356 bcount=0;
1357 } else {
1358 /* a regular character */
1359 bcount=0;
1361 s++;
1363 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1365 HeapFree( GetProcessHeap(), 0, cmdline );
1366 return NULL;
1369 arg = d = s = (char *)(argv + argc);
1370 memcpy( d, cmdline, len );
1371 bcount=0;
1372 in_quotes=0;
1373 argc=reserved;
1374 while (*s) {
1375 if ((*s==' ' || *s=='\t') && !in_quotes) {
1376 /* Close the argument and copy it */
1377 *d=0;
1378 argv[argc++]=arg;
1380 /* skip the remaining spaces */
1381 do {
1382 s++;
1383 } while (*s==' ' || *s=='\t');
1385 /* Start with a new argument */
1386 arg=d=s;
1387 bcount=0;
1388 } else if (*s=='\\') {
1389 /* '\\' */
1390 *d++=*s++;
1391 bcount++;
1392 } else if (*s=='"') {
1393 /* '"' */
1394 if ((bcount & 1)==0) {
1395 /* Preceded by an even number of '\', this is half that
1396 * number of '\', plus a '"' which we discard.
1398 d-=bcount/2;
1399 s++;
1400 in_quotes=!in_quotes;
1401 } else {
1402 /* Preceded by an odd number of '\', this is half that
1403 * number of '\' followed by a '"'
1405 d=d-bcount/2-1;
1406 *d++='"';
1407 s++;
1409 bcount=0;
1410 } else {
1411 /* a regular character */
1412 *d++=*s++;
1413 bcount=0;
1416 if (*arg) {
1417 *d='\0';
1418 argv[argc++]=arg;
1420 argv[argc]=NULL;
1422 HeapFree( GetProcessHeap(), 0, cmdline );
1423 return argv;
1427 /***********************************************************************
1428 * build_envp
1430 * Build the environment of a new child process.
1432 static char **build_envp( const WCHAR *envW )
1434 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1436 const WCHAR *end;
1437 char **envp;
1438 char *env, *p;
1439 int count = 1, length;
1440 unsigned int i;
1442 for (end = envW; *end; count++) end += strlenW(end) + 1;
1443 end++;
1444 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1445 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1446 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1448 for (p = env; *p; p += strlen(p) + 1)
1449 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1451 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1453 if (!(p = getenv(unix_vars[i]))) continue;
1454 length += strlen(unix_vars[i]) + strlen(p) + 2;
1455 count++;
1458 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1460 char **envptr = envp;
1461 char *dst = (char *)(envp + count);
1463 /* some variables must not be modified, so we get them directly from the unix env */
1464 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1466 if (!(p = getenv(unix_vars[i]))) continue;
1467 *envptr++ = strcpy( dst, unix_vars[i] );
1468 strcat( dst, "=" );
1469 strcat( dst, p );
1470 dst += strlen(dst) + 1;
1473 /* now put the Windows environment strings */
1474 for (p = env; *p; p += strlen(p) + 1)
1476 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1477 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1478 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1479 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1480 if (is_special_env_var( p )) /* prefix it with "WINE" */
1482 *envptr++ = strcpy( dst, "WINE" );
1483 strcat( dst, p );
1485 else
1487 *envptr++ = strcpy( dst, p );
1489 dst += strlen(dst) + 1;
1491 *envptr = 0;
1493 HeapFree( GetProcessHeap(), 0, env );
1494 return envp;
1498 /***********************************************************************
1499 * fork_and_exec
1501 * Fork and exec a new Unix binary, checking for errors.
1503 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1504 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1506 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1507 int pid, err;
1508 char **argv, **envp;
1510 if (!env) env = GetEnvironmentStringsW();
1512 #ifdef HAVE_PIPE2
1513 if (pipe2( fd, O_CLOEXEC ) == -1)
1514 #endif
1516 if (pipe(fd) == -1)
1518 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1519 return -1;
1521 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1522 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1525 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1527 HANDLE hstdin, hstdout, hstderr;
1529 if (startup->dwFlags & STARTF_USESTDHANDLES)
1531 hstdin = startup->hStdInput;
1532 hstdout = startup->hStdOutput;
1533 hstderr = startup->hStdError;
1535 else
1537 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1538 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1539 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1542 if (is_console_handle( hstdin ))
1543 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1544 if (is_console_handle( hstdout ))
1545 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1546 if (is_console_handle( hstderr ))
1547 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1548 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1549 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1550 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1553 argv = build_argv( cmdline, 0 );
1554 envp = build_envp( env );
1556 if (!(pid = fork())) /* child */
1558 if (!(pid = fork())) /* grandchild */
1560 close( fd[0] );
1562 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1564 int nullfd = open( "/dev/null", O_RDWR );
1565 setsid();
1566 /* close stdin and stdout */
1567 if (nullfd != -1)
1569 dup2( nullfd, 0 );
1570 dup2( nullfd, 1 );
1571 close( nullfd );
1574 else
1576 if (stdin_fd != -1)
1578 dup2( stdin_fd, 0 );
1579 close( stdin_fd );
1581 if (stdout_fd != -1)
1583 dup2( stdout_fd, 1 );
1584 close( stdout_fd );
1586 if (stderr_fd != -1)
1588 dup2( stderr_fd, 2 );
1589 close( stderr_fd );
1593 /* Reset signals that we previously set to SIG_IGN */
1594 signal( SIGPIPE, SIG_DFL );
1596 if (newdir) chdir(newdir);
1598 if (argv && envp) execve( filename, argv, envp );
1601 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1603 err = errno;
1604 write( fd[1], &err, sizeof(err) );
1605 _exit(1);
1608 _exit(0); /* child if fork succeeded */
1610 HeapFree( GetProcessHeap(), 0, argv );
1611 HeapFree( GetProcessHeap(), 0, envp );
1612 if (stdin_fd != -1) close( stdin_fd );
1613 if (stdout_fd != -1) close( stdout_fd );
1614 if (stderr_fd != -1) close( stderr_fd );
1615 close( fd[1] );
1616 if (pid != -1)
1618 /* reap child */
1619 do {
1620 err = waitpid(pid, NULL, 0);
1621 } while (err < 0 && errno == EINTR);
1623 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1625 errno = err;
1626 pid = -1;
1629 if (pid == -1) FILE_SetDosError();
1630 close( fd[0] );
1631 return pid;
1635 static inline DWORD append_string( void **ptr, const WCHAR *str )
1637 DWORD len = strlenW( str );
1638 memcpy( *ptr, str, len * sizeof(WCHAR) );
1639 *ptr = (WCHAR *)*ptr + len;
1640 return len * sizeof(WCHAR);
1643 /***********************************************************************
1644 * create_startup_info
1646 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1647 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1648 const STARTUPINFOW *startup, DWORD *info_size )
1650 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1651 const WCHAR *title;
1652 startup_info_t *info;
1653 DWORD size;
1654 void *ptr;
1655 UNICODE_STRING newdir;
1656 WCHAR imagepath[MAX_PATH];
1657 HANDLE hstdin, hstdout, hstderr;
1659 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1660 lstrcpynW( imagepath, filename, MAX_PATH );
1661 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1662 lstrcpynW( imagepath, filename, MAX_PATH );
1664 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1666 newdir.Buffer = NULL;
1667 if (cur_dir)
1669 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1670 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1671 else
1672 cur_dir = NULL;
1674 if (!cur_dir)
1676 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1677 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1678 else
1679 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1681 title = startup->lpTitle ? startup->lpTitle : imagepath;
1683 size = sizeof(*info);
1684 size += strlenW( cur_dir ) * sizeof(WCHAR);
1685 size += cur_params->DllPath.Length;
1686 size += strlenW( imagepath ) * sizeof(WCHAR);
1687 size += strlenW( cmdline ) * sizeof(WCHAR);
1688 size += strlenW( title ) * sizeof(WCHAR);
1689 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1690 /* FIXME: shellinfo */
1691 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1692 size = (size + 1) & ~1;
1693 *info_size = size;
1695 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1697 info->console_flags = cur_params->ConsoleFlags;
1698 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1699 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1701 if (startup->dwFlags & STARTF_USESTDHANDLES)
1703 hstdin = startup->hStdInput;
1704 hstdout = startup->hStdOutput;
1705 hstderr = startup->hStdError;
1707 else if (flags & DETACHED_PROCESS)
1709 hstdin = INVALID_HANDLE_VALUE;
1710 hstdout = INVALID_HANDLE_VALUE;
1711 hstderr = INVALID_HANDLE_VALUE;
1713 else
1715 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1716 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1717 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1719 info->hstdin = wine_server_obj_handle( hstdin );
1720 info->hstdout = wine_server_obj_handle( hstdout );
1721 info->hstderr = wine_server_obj_handle( hstderr );
1722 if ((flags & CREATE_NEW_CONSOLE) != 0)
1724 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1725 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1726 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1727 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1729 else
1731 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1732 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1733 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1736 info->x = startup->dwX;
1737 info->y = startup->dwY;
1738 info->xsize = startup->dwXSize;
1739 info->ysize = startup->dwYSize;
1740 info->xchars = startup->dwXCountChars;
1741 info->ychars = startup->dwYCountChars;
1742 info->attribute = startup->dwFillAttribute;
1743 info->flags = startup->dwFlags;
1744 info->show = startup->wShowWindow;
1746 ptr = info + 1;
1747 info->curdir_len = append_string( &ptr, cur_dir );
1748 info->dllpath_len = cur_params->DllPath.Length;
1749 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1750 ptr = (char *)ptr + cur_params->DllPath.Length;
1751 info->imagepath_len = append_string( &ptr, imagepath );
1752 info->cmdline_len = append_string( &ptr, cmdline );
1753 info->title_len = append_string( &ptr, title );
1754 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1755 if (startup->lpReserved2 && startup->cbReserved2)
1757 info->runtime_len = startup->cbReserved2;
1758 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1761 done:
1762 RtlFreeUnicodeString( &newdir );
1763 return info;
1766 /***********************************************************************
1767 * get_alternate_loader
1769 * Get the name of the alternate (32 or 64 bit) Wine loader.
1771 static const char *get_alternate_loader( char **ret_env )
1773 char *env;
1774 const char *loader = NULL;
1775 const char *loader_env = getenv( "WINELOADER" );
1777 *ret_env = NULL;
1779 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1781 if (loader_env)
1783 int len = strlen( loader_env );
1784 if (!is_win64)
1786 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1787 strcpy( env, "WINELOADER=" );
1788 strcat( env, loader_env );
1789 strcat( env, "64" );
1791 else
1793 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1794 strcpy( env, "WINELOADER=" );
1795 strcat( env, loader_env );
1796 len += sizeof("WINELOADER=") - 1;
1797 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1799 if (!loader)
1801 if ((loader = strrchr( env, '/' ))) loader++;
1802 else loader = env;
1804 *ret_env = env;
1806 if (!loader) loader = is_win64 ? "wine" : "wine64";
1807 return loader;
1810 #ifdef __APPLE__
1811 /***********************************************************************
1812 * terminate_main_thread
1814 * On some versions of Mac OS X, the execve system call fails with
1815 * ENOTSUP if the process has multiple threads. Wine is always multi-
1816 * threaded on Mac OS X because it specifically reserves the main thread
1817 * for use by the system frameworks (see apple_main_thread() in
1818 * libs/wine/loader.c). So, when we need to exec without first forking,
1819 * we need to terminate the main thread first. We do this by installing
1820 * a custom run loop source onto the main run loop and signaling it.
1821 * The source's "perform" callback is pthread_exit and it will be
1822 * executed on the main thread, terminating it.
1824 * Returns TRUE if there's still hope the main thread has terminated or
1825 * will soon. Return FALSE if we've given up.
1827 static BOOL terminate_main_thread(void)
1829 static int delayms;
1831 if (!delayms)
1833 CFRunLoopSourceContext source_context = { 0 };
1834 CFRunLoopSourceRef source;
1836 source_context.perform = pthread_exit;
1837 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1838 return FALSE;
1840 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1841 CFRunLoopSourceSignal( source );
1842 CFRunLoopWakeUp( CFRunLoopGetMain() );
1843 CFRelease( source );
1845 delayms = 20;
1848 if (delayms > 1000)
1849 return FALSE;
1851 usleep(delayms * 1000);
1852 delayms *= 2;
1854 return TRUE;
1856 #endif
1858 /***********************************************************************
1859 * get_process_cpu
1861 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1863 switch (binary_info->arch)
1865 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1866 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1867 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1868 case IMAGE_FILE_MACHINE_ARM:
1869 case IMAGE_FILE_MACHINE_THUMB:
1870 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1871 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1873 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1874 return -1;
1877 /***********************************************************************
1878 * exec_loader
1880 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1881 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1882 const struct binary_info *binary_info, int exec_only )
1884 pid_t pid;
1885 char *wineloader = NULL;
1886 const char *loader = NULL;
1887 char **argv;
1889 argv = build_argv( cmd_line, 1 );
1891 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1892 loader = get_alternate_loader( &wineloader );
1894 if (exec_only || !(pid = fork())) /* child */
1896 if (exec_only || !(pid = fork())) /* grandchild */
1898 char preloader_reserve[64], socket_env[64];
1900 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1902 int fd = open( "/dev/null", O_RDWR );
1903 setsid();
1904 /* close stdin and stdout */
1905 if (fd != -1)
1907 dup2( fd, 0 );
1908 dup2( fd, 1 );
1909 close( fd );
1912 else
1914 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1915 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1918 if (stdin_fd != -1) close( stdin_fd );
1919 if (stdout_fd != -1) close( stdout_fd );
1921 /* Reset signals that we previously set to SIG_IGN */
1922 signal( SIGPIPE, SIG_DFL );
1924 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1925 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1926 (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1928 putenv( preloader_reserve );
1929 putenv( socket_env );
1930 if (winedebug) putenv( winedebug );
1931 if (wineloader) putenv( wineloader );
1932 if (unixdir) chdir(unixdir);
1934 if (argv)
1938 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1940 #ifdef __APPLE__
1941 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1942 #else
1943 while (0);
1944 #endif
1946 _exit(1);
1949 _exit(pid == -1);
1952 if (pid != -1)
1954 /* reap child */
1955 pid_t wret;
1956 do {
1957 wret = waitpid(pid, NULL, 0);
1958 } while (wret < 0 && errno == EINTR);
1961 HeapFree( GetProcessHeap(), 0, wineloader );
1962 HeapFree( GetProcessHeap(), 0, argv );
1963 return pid;
1966 /***********************************************************************
1967 * create_process
1969 * Create a new process. If hFile is a valid handle we have an exe
1970 * file, otherwise it is a Winelib app.
1972 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1973 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1974 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1975 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1976 const struct binary_info *binary_info, int exec_only )
1978 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1979 NTSTATUS status;
1980 BOOL success = FALSE;
1981 HANDLE process_info;
1982 WCHAR *env_end;
1983 char *winedebug = NULL;
1984 startup_info_t *startup_info;
1985 DWORD startup_info_size;
1986 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1987 pid_t pid;
1988 int err, cpu;
1990 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
1992 SetLastError( ERROR_BAD_EXE_FORMAT );
1993 return FALSE;
1996 /* create the socket for the new process */
1998 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2000 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2001 return FALSE;
2003 #ifdef SO_PASSCRED
2004 else
2006 int enable = 1;
2007 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2009 #endif
2011 if (exec_only) /* things are much simpler in this case */
2013 wine_server_send_fd( socketfd[1] );
2014 close( socketfd[1] );
2015 SERVER_START_REQ( new_process )
2017 req->create_flags = flags;
2018 req->socket_fd = socketfd[1];
2019 req->exe_file = wine_server_obj_handle( hFile );
2020 req->cpu = cpu;
2021 status = wine_server_call( req );
2023 SERVER_END_REQ;
2025 switch (status)
2027 case STATUS_INVALID_IMAGE_WIN_64:
2028 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2029 break;
2030 case STATUS_INVALID_IMAGE_FORMAT:
2031 ERR( "%s not supported on this installation (%s binary)\n",
2032 debugstr_w(filename), cpu_names[cpu] );
2033 break;
2034 case STATUS_SUCCESS:
2035 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2036 winedebug, binary_info, TRUE );
2038 close( socketfd[0] );
2039 SetLastError( RtlNtStatusToDosError( status ));
2040 return FALSE;
2043 RtlAcquirePebLock();
2045 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2046 &startup_info_size )))
2048 RtlReleasePebLock();
2049 close( socketfd[0] );
2050 close( socketfd[1] );
2051 return FALSE;
2053 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2054 env_end = env;
2055 while (*env_end)
2057 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2058 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2060 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2061 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2062 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2064 env_end += strlenW(env_end) + 1;
2066 env_end++;
2068 wine_server_send_fd( socketfd[1] );
2069 close( socketfd[1] );
2071 /* create the process on the server side */
2073 SERVER_START_REQ( new_process )
2075 req->inherit_all = inherit;
2076 req->create_flags = flags;
2077 req->socket_fd = socketfd[1];
2078 req->exe_file = wine_server_obj_handle( hFile );
2079 req->process_access = PROCESS_ALL_ACCESS;
2080 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2081 req->thread_access = THREAD_ALL_ACCESS;
2082 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2083 req->cpu = cpu;
2084 req->info_size = startup_info_size;
2086 wine_server_add_data( req, startup_info, startup_info_size );
2087 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2088 if (!(status = wine_server_call( req )))
2090 info->dwProcessId = (DWORD)reply->pid;
2091 info->dwThreadId = (DWORD)reply->tid;
2092 info->hProcess = wine_server_ptr_handle( reply->phandle );
2093 info->hThread = wine_server_ptr_handle( reply->thandle );
2095 process_info = wine_server_ptr_handle( reply->info );
2097 SERVER_END_REQ;
2099 RtlReleasePebLock();
2100 if (status)
2102 switch (status)
2104 case STATUS_INVALID_IMAGE_WIN_64:
2105 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2106 break;
2107 case STATUS_INVALID_IMAGE_FORMAT:
2108 ERR( "%s not supported on this installation (%s binary)\n",
2109 debugstr_w(filename), cpu_names[cpu] );
2110 break;
2112 close( socketfd[0] );
2113 HeapFree( GetProcessHeap(), 0, startup_info );
2114 HeapFree( GetProcessHeap(), 0, winedebug );
2115 SetLastError( RtlNtStatusToDosError( status ));
2116 return FALSE;
2119 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2121 if (startup_info->hstdin)
2122 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2123 FILE_READ_DATA, &stdin_fd, NULL );
2124 if (startup_info->hstdout)
2125 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2126 FILE_WRITE_DATA, &stdout_fd, NULL );
2128 HeapFree( GetProcessHeap(), 0, startup_info );
2130 /* create the child process */
2132 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2133 winedebug, binary_info, FALSE );
2135 if (stdin_fd != -1) close( stdin_fd );
2136 if (stdout_fd != -1) close( stdout_fd );
2137 close( socketfd[0] );
2138 HeapFree( GetProcessHeap(), 0, winedebug );
2139 if (pid == -1)
2141 FILE_SetDosError();
2142 goto error;
2145 /* wait for the new process info to be ready */
2147 WaitForSingleObject( process_info, INFINITE );
2148 SERVER_START_REQ( get_new_process_info )
2150 req->info = wine_server_obj_handle( process_info );
2151 wine_server_call( req );
2152 success = reply->success;
2153 err = reply->exit_code;
2155 SERVER_END_REQ;
2157 if (!success)
2159 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2160 goto error;
2162 CloseHandle( process_info );
2163 return success;
2165 error:
2166 CloseHandle( process_info );
2167 CloseHandle( info->hProcess );
2168 CloseHandle( info->hThread );
2169 info->hProcess = info->hThread = 0;
2170 info->dwProcessId = info->dwThreadId = 0;
2171 return FALSE;
2175 /***********************************************************************
2176 * create_vdm_process
2178 * Create a new VDM process for a 16-bit or DOS application.
2180 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2181 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2182 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2183 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2184 const struct binary_info *binary_info, int exec_only )
2186 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2188 BOOL ret;
2189 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
2190 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
2192 if (!new_cmd_line)
2194 SetLastError( ERROR_OUTOFMEMORY );
2195 return FALSE;
2197 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
2198 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2199 flags, startup, info, unixdir, binary_info, exec_only );
2200 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2201 return ret;
2205 /***********************************************************************
2206 * create_cmd_process
2208 * Create a new cmd shell process for a .BAT file.
2210 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2211 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2212 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2213 LPPROCESS_INFORMATION info )
2216 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2217 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2218 WCHAR comspec[MAX_PATH];
2219 WCHAR *newcmdline;
2220 BOOL ret;
2222 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2223 return FALSE;
2224 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2225 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2226 return FALSE;
2228 strcpyW( newcmdline, comspec );
2229 strcatW( newcmdline, slashcW );
2230 strcatW( newcmdline, cmd_line );
2231 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2232 flags, env, cur_dir, startup, info );
2233 HeapFree( GetProcessHeap(), 0, newcmdline );
2234 return ret;
2238 /*************************************************************************
2239 * get_file_name
2241 * Helper for CreateProcess: retrieve the file name to load from the
2242 * app name and command line. Store the file name in buffer, and
2243 * return a possibly modified command line.
2244 * Also returns a handle to the opened file if it's a Windows binary.
2246 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2247 int buflen, HANDLE *handle, struct binary_info *binary_info )
2249 static const WCHAR quotesW[] = {'"','%','s','"',0};
2251 WCHAR *name, *pos, *first_space, *ret = NULL;
2252 const WCHAR *p;
2254 /* if we have an app name, everything is easy */
2256 if (appname)
2258 /* use the unmodified app name as file name */
2259 lstrcpynW( buffer, appname, buflen );
2260 *handle = open_exe_file( buffer, binary_info );
2261 if (!(ret = cmdline) || !cmdline[0])
2263 /* no command-line, create one */
2264 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2265 sprintfW( ret, quotesW, appname );
2267 return ret;
2270 /* first check for a quoted file name */
2272 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2274 int len = p - cmdline - 1;
2275 /* extract the quoted portion as file name */
2276 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2277 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2278 name[len] = 0;
2280 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2281 ret = cmdline; /* no change necessary */
2282 goto done;
2285 /* now try the command-line word by word */
2287 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2288 return NULL;
2289 pos = name;
2290 p = cmdline;
2291 first_space = NULL;
2293 for (;;)
2295 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2296 *pos = 0;
2297 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2299 ret = cmdline;
2300 break;
2302 if (!first_space) first_space = pos;
2303 if (!(*pos++ = *p++)) break;
2306 if (!ret)
2308 SetLastError( ERROR_FILE_NOT_FOUND );
2310 else if (first_space) /* build a new command-line with quotes */
2312 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2313 goto done;
2314 sprintfW( ret, quotesW, name );
2315 strcatW( ret, p );
2318 done:
2319 HeapFree( GetProcessHeap(), 0, name );
2320 return ret;
2324 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2325 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2326 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2327 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2328 LPPROCESS_INFORMATION info )
2330 BOOL retv = FALSE;
2331 HANDLE hFile = 0;
2332 char *unixdir = NULL;
2333 WCHAR name[MAX_PATH];
2334 WCHAR *tidy_cmdline, *p, *envW = env;
2335 struct binary_info binary_info;
2337 /* Process the AppName and/or CmdLine to get module name and path */
2339 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2341 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2342 &hFile, &binary_info )))
2343 return FALSE;
2344 if (hFile == INVALID_HANDLE_VALUE) goto done;
2346 /* Warn if unsupported features are used */
2348 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2349 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2350 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2351 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2352 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2354 if (cur_dir)
2356 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2358 SetLastError(ERROR_DIRECTORY);
2359 goto done;
2362 else
2364 WCHAR buf[MAX_PATH];
2365 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2368 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2370 char *e = env;
2371 DWORD lenW;
2373 while (*e) e += strlen(e) + 1;
2374 e++; /* final null */
2375 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2376 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2377 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2378 flags |= CREATE_UNICODE_ENVIRONMENT;
2381 info->hThread = info->hProcess = 0;
2382 info->dwProcessId = info->dwThreadId = 0;
2384 if (binary_info.flags & BINARY_FLAG_DLL)
2386 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2387 SetLastError( ERROR_BAD_EXE_FORMAT );
2389 else switch (binary_info.type)
2391 case BINARY_PE:
2392 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x%s)\n",
2393 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2394 binary_info.res_start, binary_info.res_end, binary_info.arch,
2395 (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2396 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2397 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2398 break;
2399 case BINARY_OS216:
2400 case BINARY_WIN16:
2401 case BINARY_DOS:
2402 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2403 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2404 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2405 break;
2406 case BINARY_UNIX_LIB:
2407 TRACE( "starting %s as %d-bit Winelib app\n",
2408 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2409 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2410 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2411 break;
2412 case BINARY_UNKNOWN:
2413 /* check for .com or .bat extension */
2414 if ((p = strrchrW( name, '.' )))
2416 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2418 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2419 binary_info.type = BINARY_DOS;
2420 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2421 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2422 inherit, flags, startup_info, info, unixdir,
2423 &binary_info, FALSE );
2424 break;
2426 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2428 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2429 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2430 inherit, flags, startup_info, info );
2431 break;
2434 /* fall through */
2435 case BINARY_UNIX_EXE:
2437 /* unknown file, try as unix executable */
2438 char *unix_name;
2440 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2442 if ((unix_name = wine_get_unix_file_name( name )))
2444 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2445 HeapFree( GetProcessHeap(), 0, unix_name );
2448 break;
2450 if (hFile) CloseHandle( hFile );
2452 done:
2453 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2454 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2455 HeapFree( GetProcessHeap(), 0, unixdir );
2456 if (retv)
2457 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2458 return retv;
2462 /**********************************************************************
2463 * CreateProcessA (KERNEL32.@)
2465 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2466 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2467 DWORD flags, LPVOID env, LPCSTR cur_dir,
2468 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2470 BOOL ret = FALSE;
2471 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2472 UNICODE_STRING desktopW, titleW;
2473 STARTUPINFOW infoW;
2475 desktopW.Buffer = NULL;
2476 titleW.Buffer = NULL;
2477 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2478 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2479 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2481 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2482 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2484 memcpy( &infoW, startup_info, sizeof(infoW) );
2485 infoW.lpDesktop = desktopW.Buffer;
2486 infoW.lpTitle = titleW.Buffer;
2488 if (startup_info->lpReserved)
2489 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2490 debugstr_a(startup_info->lpReserved));
2492 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2493 inherit, flags, env, cur_dirW, &infoW, info );
2494 done:
2495 HeapFree( GetProcessHeap(), 0, app_nameW );
2496 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2497 HeapFree( GetProcessHeap(), 0, cur_dirW );
2498 RtlFreeUnicodeString( &desktopW );
2499 RtlFreeUnicodeString( &titleW );
2500 return ret;
2504 /**********************************************************************
2505 * CreateProcessW (KERNEL32.@)
2507 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2508 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2509 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2510 LPPROCESS_INFORMATION info )
2512 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2513 inherit, flags, env, cur_dir, startup_info, info);
2517 /**********************************************************************
2518 * exec_process
2520 static void exec_process( LPCWSTR name )
2522 HANDLE hFile;
2523 WCHAR *p;
2524 STARTUPINFOW startup_info;
2525 PROCESS_INFORMATION info;
2526 struct binary_info binary_info;
2528 hFile = open_exe_file( name, &binary_info );
2529 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2531 memset( &startup_info, 0, sizeof(startup_info) );
2532 startup_info.cb = sizeof(startup_info);
2534 /* Determine executable type */
2536 if (binary_info.flags & BINARY_FLAG_DLL)
2538 CloseHandle( hFile );
2539 return;
2542 switch (binary_info.type)
2544 case BINARY_PE:
2545 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2546 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2547 binary_info.res_start, binary_info.res_end, binary_info.arch );
2548 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2549 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2550 break;
2551 case BINARY_UNIX_LIB:
2552 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2553 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2554 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2555 break;
2556 case BINARY_UNKNOWN:
2557 /* check for .com or .pif extension */
2558 if (!(p = strrchrW( name, '.' ))) break;
2559 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2560 binary_info.type = BINARY_DOS;
2561 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2562 /* fall through */
2563 case BINARY_OS216:
2564 case BINARY_WIN16:
2565 case BINARY_DOS:
2566 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2567 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2568 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2569 break;
2570 default:
2571 break;
2573 CloseHandle( hFile );
2577 /***********************************************************************
2578 * wait_input_idle
2580 * Wrapper to call WaitForInputIdle USER function
2582 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2584 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2586 HMODULE mod = GetModuleHandleA( "user32.dll" );
2587 if (mod)
2589 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2590 if (ptr) return ptr( process, timeout );
2592 return 0;
2596 /***********************************************************************
2597 * WinExec (KERNEL32.@)
2599 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2601 PROCESS_INFORMATION info;
2602 STARTUPINFOA startup;
2603 char *cmdline;
2604 UINT ret;
2606 memset( &startup, 0, sizeof(startup) );
2607 startup.cb = sizeof(startup);
2608 startup.dwFlags = STARTF_USESHOWWINDOW;
2609 startup.wShowWindow = nCmdShow;
2611 /* cmdline needs to be writable for CreateProcess */
2612 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2613 strcpy( cmdline, lpCmdLine );
2615 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2616 0, NULL, NULL, &startup, &info ))
2618 /* Give 30 seconds to the app to come up */
2619 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2620 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2621 ret = 33;
2622 /* Close off the handles */
2623 CloseHandle( info.hThread );
2624 CloseHandle( info.hProcess );
2626 else if ((ret = GetLastError()) >= 32)
2628 FIXME("Strange error set by CreateProcess: %d\n", ret );
2629 ret = 11;
2631 HeapFree( GetProcessHeap(), 0, cmdline );
2632 return ret;
2636 /**********************************************************************
2637 * LoadModule (KERNEL32.@)
2639 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2641 LOADPARMS32 *params = paramBlock;
2642 PROCESS_INFORMATION info;
2643 STARTUPINFOA startup;
2644 DWORD ret;
2645 LPSTR cmdline, p;
2646 char filename[MAX_PATH];
2647 BYTE len;
2649 if (!name) return ERROR_FILE_NOT_FOUND;
2651 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2652 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2653 return GetLastError();
2655 len = (BYTE)params->lpCmdLine[0];
2656 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2657 return ERROR_NOT_ENOUGH_MEMORY;
2659 strcpy( cmdline, filename );
2660 p = cmdline + strlen(cmdline);
2661 *p++ = ' ';
2662 memcpy( p, params->lpCmdLine + 1, len );
2663 p[len] = 0;
2665 memset( &startup, 0, sizeof(startup) );
2666 startup.cb = sizeof(startup);
2667 if (params->lpCmdShow)
2669 startup.dwFlags = STARTF_USESHOWWINDOW;
2670 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2673 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2674 params->lpEnvAddress, NULL, &startup, &info ))
2676 /* Give 30 seconds to the app to come up */
2677 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2678 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2679 ret = 33;
2680 /* Close off the handles */
2681 CloseHandle( info.hThread );
2682 CloseHandle( info.hProcess );
2684 else if ((ret = GetLastError()) >= 32)
2686 FIXME("Strange error set by CreateProcess: %u\n", ret );
2687 ret = 11;
2690 HeapFree( GetProcessHeap(), 0, cmdline );
2691 return ret;
2695 /******************************************************************************
2696 * TerminateProcess (KERNEL32.@)
2698 * Terminates a process.
2700 * PARAMS
2701 * handle [I] Process to terminate.
2702 * exit_code [I] Exit code.
2704 * RETURNS
2705 * Success: TRUE.
2706 * Failure: FALSE, check GetLastError().
2708 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2710 NTSTATUS status;
2712 if (!handle)
2714 SetLastError( ERROR_INVALID_HANDLE );
2715 return FALSE;
2718 status = NtTerminateProcess( handle, exit_code );
2719 if (status) SetLastError( RtlNtStatusToDosError(status) );
2720 return !status;
2723 /***********************************************************************
2724 * ExitProcess (KERNEL32.@)
2726 * Exits the current process.
2728 * PARAMS
2729 * status [I] Status code to exit with.
2731 * RETURNS
2732 * Nothing.
2734 #ifdef __i386__
2735 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2736 "pushl %ebp\n\t"
2737 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2738 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2739 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2740 "pushl 8(%ebp)\n\t"
2741 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2742 "leave\n\t"
2743 "ret $4" )
2744 #else
2746 void WINAPI ExitProcess( DWORD status )
2748 RtlExitUserProcess( status );
2751 #endif
2753 /***********************************************************************
2754 * GetExitCodeProcess [KERNEL32.@]
2756 * Gets termination status of specified process.
2758 * PARAMS
2759 * hProcess [in] Handle to the process.
2760 * lpExitCode [out] Address to receive termination status.
2762 * RETURNS
2763 * Success: TRUE
2764 * Failure: FALSE
2766 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2768 NTSTATUS status;
2769 PROCESS_BASIC_INFORMATION pbi;
2771 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2772 sizeof(pbi), NULL);
2773 if (status == STATUS_SUCCESS)
2775 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2776 return TRUE;
2778 SetLastError( RtlNtStatusToDosError(status) );
2779 return FALSE;
2783 /***********************************************************************
2784 * SetErrorMode (KERNEL32.@)
2786 UINT WINAPI SetErrorMode( UINT mode )
2788 UINT old;
2790 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2791 &old, sizeof(old), NULL );
2792 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2793 &mode, sizeof(mode) );
2794 return old;
2797 /***********************************************************************
2798 * GetErrorMode (KERNEL32.@)
2800 UINT WINAPI GetErrorMode( void )
2802 UINT mode;
2804 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2805 &mode, sizeof(mode), NULL );
2806 return mode;
2809 /**********************************************************************
2810 * TlsAlloc [KERNEL32.@]
2812 * Allocates a thread local storage index.
2814 * RETURNS
2815 * Success: TLS index.
2816 * Failure: 0xFFFFFFFF
2818 DWORD WINAPI TlsAlloc( void )
2820 DWORD index;
2821 PEB * const peb = NtCurrentTeb()->Peb;
2823 RtlAcquirePebLock();
2824 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2825 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2826 else
2828 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2829 if (index != ~0U)
2831 if (!NtCurrentTeb()->TlsExpansionSlots &&
2832 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2833 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2835 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2836 index = ~0U;
2837 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2839 else
2841 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2842 index += TLS_MINIMUM_AVAILABLE;
2845 else SetLastError( ERROR_NO_MORE_ITEMS );
2847 RtlReleasePebLock();
2848 return index;
2852 /**********************************************************************
2853 * TlsFree [KERNEL32.@]
2855 * Releases a thread local storage index, making it available for reuse.
2857 * PARAMS
2858 * index [in] TLS index to free.
2860 * RETURNS
2861 * Success: TRUE
2862 * Failure: FALSE
2864 BOOL WINAPI TlsFree( DWORD index )
2866 BOOL ret;
2868 RtlAcquirePebLock();
2869 if (index >= TLS_MINIMUM_AVAILABLE)
2871 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2872 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2874 else
2876 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2877 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2879 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2880 else SetLastError( ERROR_INVALID_PARAMETER );
2881 RtlReleasePebLock();
2882 return ret;
2886 /**********************************************************************
2887 * TlsGetValue [KERNEL32.@]
2889 * Gets value in a thread's TLS slot.
2891 * PARAMS
2892 * index [in] TLS index to retrieve value for.
2894 * RETURNS
2895 * Success: Value stored in calling thread's TLS slot for index.
2896 * Failure: 0 and GetLastError() returns NO_ERROR.
2898 LPVOID WINAPI TlsGetValue( DWORD index )
2900 LPVOID ret;
2902 if (index < TLS_MINIMUM_AVAILABLE)
2904 ret = NtCurrentTeb()->TlsSlots[index];
2906 else
2908 index -= TLS_MINIMUM_AVAILABLE;
2909 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2911 SetLastError( ERROR_INVALID_PARAMETER );
2912 return NULL;
2914 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2915 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2917 SetLastError( ERROR_SUCCESS );
2918 return ret;
2922 /**********************************************************************
2923 * TlsSetValue [KERNEL32.@]
2925 * Stores a value in the thread's TLS slot.
2927 * PARAMS
2928 * index [in] TLS index to set value for.
2929 * value [in] Value to be stored.
2931 * RETURNS
2932 * Success: TRUE
2933 * Failure: FALSE
2935 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2937 if (index < TLS_MINIMUM_AVAILABLE)
2939 NtCurrentTeb()->TlsSlots[index] = value;
2941 else
2943 index -= TLS_MINIMUM_AVAILABLE;
2944 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2946 SetLastError( ERROR_INVALID_PARAMETER );
2947 return FALSE;
2949 if (!NtCurrentTeb()->TlsExpansionSlots &&
2950 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2951 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2953 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2954 return FALSE;
2956 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2958 return TRUE;
2962 /***********************************************************************
2963 * GetProcessFlags (KERNEL32.@)
2965 DWORD WINAPI GetProcessFlags( DWORD processid )
2967 IMAGE_NT_HEADERS *nt;
2968 DWORD flags = 0;
2970 if (processid && processid != GetCurrentProcessId()) return 0;
2972 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2974 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2975 flags |= PDB32_CONSOLE_PROC;
2977 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2978 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2979 return flags;
2983 /*********************************************************************
2984 * OpenProcess (KERNEL32.@)
2986 * Opens a handle to a process.
2988 * PARAMS
2989 * access [I] Desired access rights assigned to the returned handle.
2990 * inherit [I] Determines whether or not child processes will inherit the handle.
2991 * id [I] Process identifier of the process to get a handle to.
2993 * RETURNS
2994 * Success: Valid handle to the specified process.
2995 * Failure: NULL, check GetLastError().
2997 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2999 NTSTATUS status;
3000 HANDLE handle;
3001 OBJECT_ATTRIBUTES attr;
3002 CLIENT_ID cid;
3004 cid.UniqueProcess = ULongToHandle(id);
3005 cid.UniqueThread = 0; /* FIXME ? */
3007 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3008 attr.RootDirectory = NULL;
3009 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3010 attr.SecurityDescriptor = NULL;
3011 attr.SecurityQualityOfService = NULL;
3012 attr.ObjectName = NULL;
3014 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3016 status = NtOpenProcess(&handle, access, &attr, &cid);
3017 if (status != STATUS_SUCCESS)
3019 SetLastError( RtlNtStatusToDosError(status) );
3020 return NULL;
3022 return handle;
3026 /*********************************************************************
3027 * GetProcessId (KERNEL32.@)
3029 * Gets the a unique identifier of a process.
3031 * PARAMS
3032 * hProcess [I] Handle to the process.
3034 * RETURNS
3035 * Success: TRUE.
3036 * Failure: FALSE, check GetLastError().
3038 * NOTES
3040 * The identifier is unique only on the machine and only until the process
3041 * exits (including system shutdown).
3043 DWORD WINAPI GetProcessId( HANDLE hProcess )
3045 NTSTATUS status;
3046 PROCESS_BASIC_INFORMATION pbi;
3048 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3049 sizeof(pbi), NULL);
3050 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3051 SetLastError( RtlNtStatusToDosError(status) );
3052 return 0;
3056 /*********************************************************************
3057 * CloseHandle (KERNEL32.@)
3059 * Closes a handle.
3061 * PARAMS
3062 * handle [I] Handle to close.
3064 * RETURNS
3065 * Success: TRUE.
3066 * Failure: FALSE, check GetLastError().
3068 BOOL WINAPI CloseHandle( HANDLE handle )
3070 NTSTATUS status;
3072 /* stdio handles need special treatment */
3073 if (handle == (HANDLE)STD_INPUT_HANDLE)
3074 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3075 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3076 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3077 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3078 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3080 if (is_console_handle(handle))
3081 return CloseConsoleHandle(handle);
3083 status = NtClose( handle );
3084 if (status) SetLastError( RtlNtStatusToDosError(status) );
3085 return !status;
3089 /*********************************************************************
3090 * GetHandleInformation (KERNEL32.@)
3092 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3094 OBJECT_DATA_INFORMATION info;
3095 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3097 if (status) SetLastError( RtlNtStatusToDosError(status) );
3098 else if (flags)
3100 *flags = 0;
3101 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3102 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3104 return !status;
3108 /*********************************************************************
3109 * SetHandleInformation (KERNEL32.@)
3111 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3113 OBJECT_DATA_INFORMATION info;
3114 NTSTATUS status;
3116 /* if not setting both fields, retrieve current value first */
3117 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3118 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3120 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3122 SetLastError( RtlNtStatusToDosError(status) );
3123 return FALSE;
3126 if (mask & HANDLE_FLAG_INHERIT)
3127 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3128 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3129 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3131 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3132 if (status) SetLastError( RtlNtStatusToDosError(status) );
3133 return !status;
3137 /*********************************************************************
3138 * DuplicateHandle (KERNEL32.@)
3140 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3141 HANDLE dest_process, HANDLE *dest,
3142 DWORD access, BOOL inherit, DWORD options )
3144 NTSTATUS status;
3146 if (is_console_handle(source))
3148 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3149 if (source_process != dest_process ||
3150 source_process != GetCurrentProcess())
3152 SetLastError(ERROR_INVALID_PARAMETER);
3153 return FALSE;
3155 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3156 return (*dest != INVALID_HANDLE_VALUE);
3158 status = NtDuplicateObject( source_process, source, dest_process, dest,
3159 access, inherit ? OBJ_INHERIT : 0, options );
3160 if (status) SetLastError( RtlNtStatusToDosError(status) );
3161 return !status;
3165 /***********************************************************************
3166 * ConvertToGlobalHandle (KERNEL32.@)
3168 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3170 HANDLE ret = INVALID_HANDLE_VALUE;
3171 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3172 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3173 return ret;
3177 /***********************************************************************
3178 * SetHandleContext (KERNEL32.@)
3180 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3182 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3183 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3184 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3185 return FALSE;
3189 /***********************************************************************
3190 * GetHandleContext (KERNEL32.@)
3192 DWORD WINAPI GetHandleContext(HANDLE hnd)
3194 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3195 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3196 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3197 return 0;
3201 /***********************************************************************
3202 * CreateSocketHandle (KERNEL32.@)
3204 HANDLE WINAPI CreateSocketHandle(void)
3206 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3207 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3208 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3209 return INVALID_HANDLE_VALUE;
3213 /***********************************************************************
3214 * SetPriorityClass (KERNEL32.@)
3216 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3218 NTSTATUS status;
3219 PROCESS_PRIORITY_CLASS ppc;
3221 ppc.Foreground = FALSE;
3222 switch (priorityclass)
3224 case IDLE_PRIORITY_CLASS:
3225 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3226 case BELOW_NORMAL_PRIORITY_CLASS:
3227 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3228 case NORMAL_PRIORITY_CLASS:
3229 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3230 case ABOVE_NORMAL_PRIORITY_CLASS:
3231 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3232 case HIGH_PRIORITY_CLASS:
3233 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3234 case REALTIME_PRIORITY_CLASS:
3235 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3236 default:
3237 SetLastError(ERROR_INVALID_PARAMETER);
3238 return FALSE;
3241 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3242 &ppc, sizeof(ppc));
3244 if (status != STATUS_SUCCESS)
3246 SetLastError( RtlNtStatusToDosError(status) );
3247 return FALSE;
3249 return TRUE;
3253 /***********************************************************************
3254 * GetPriorityClass (KERNEL32.@)
3256 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3258 NTSTATUS status;
3259 PROCESS_BASIC_INFORMATION pbi;
3261 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3262 sizeof(pbi), NULL);
3263 if (status != STATUS_SUCCESS)
3265 SetLastError( RtlNtStatusToDosError(status) );
3266 return 0;
3268 switch (pbi.BasePriority)
3270 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3271 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3272 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3273 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3274 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3275 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3277 SetLastError( ERROR_INVALID_PARAMETER );
3278 return 0;
3282 /***********************************************************************
3283 * SetProcessAffinityMask (KERNEL32.@)
3285 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3287 NTSTATUS status;
3289 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3290 &affmask, sizeof(DWORD_PTR));
3291 if (status)
3293 SetLastError( RtlNtStatusToDosError(status) );
3294 return FALSE;
3296 return TRUE;
3300 /**********************************************************************
3301 * GetProcessAffinityMask (KERNEL32.@)
3303 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3305 NTSTATUS status = STATUS_SUCCESS;
3307 if (process_mask)
3309 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3310 process_mask, sizeof(*process_mask), NULL )))
3311 SetLastError( RtlNtStatusToDosError(status) );
3313 if (system_mask && status == STATUS_SUCCESS)
3315 SYSTEM_BASIC_INFORMATION info;
3317 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3318 SetLastError( RtlNtStatusToDosError(status) );
3319 else
3320 *system_mask = info.ActiveProcessorsAffinityMask;
3322 return !status;
3326 /***********************************************************************
3327 * GetProcessVersion (KERNEL32.@)
3329 DWORD WINAPI GetProcessVersion( DWORD pid )
3331 HANDLE process;
3332 NTSTATUS status;
3333 PROCESS_BASIC_INFORMATION pbi;
3334 SIZE_T count;
3335 PEB peb;
3336 IMAGE_DOS_HEADER dos;
3337 IMAGE_NT_HEADERS nt;
3338 DWORD ver = 0;
3340 if (!pid || pid == GetCurrentProcessId())
3342 IMAGE_NT_HEADERS *pnt;
3344 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3345 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3346 pnt->OptionalHeader.MinorSubsystemVersion);
3347 return 0;
3350 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3351 if (!process) return 0;
3353 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3354 if (status) goto err;
3356 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3357 if (status || count != sizeof(peb)) goto err;
3359 memset(&dos, 0, sizeof(dos));
3360 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3361 if (status || count != sizeof(dos)) goto err;
3362 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3364 memset(&nt, 0, sizeof(nt));
3365 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3366 if (status || count != sizeof(nt)) goto err;
3367 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3369 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3371 err:
3372 CloseHandle(process);
3374 if (status != STATUS_SUCCESS)
3375 SetLastError(RtlNtStatusToDosError(status));
3377 return ver;
3381 /***********************************************************************
3382 * SetProcessWorkingSetSize [KERNEL32.@]
3383 * Sets the min/max working set sizes for a specified process.
3385 * PARAMS
3386 * hProcess [I] Handle to the process of interest
3387 * minset [I] Specifies minimum working set size
3388 * maxset [I] Specifies maximum working set size
3390 * RETURNS
3391 * Success: TRUE
3392 * Failure: FALSE
3394 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3395 SIZE_T maxset)
3397 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3398 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3399 /* Trim the working set to zero */
3400 /* Swap the process out of physical RAM */
3402 return TRUE;
3405 /***********************************************************************
3406 * K32EmptyWorkingSet (KERNEL32.@)
3408 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3410 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3413 /***********************************************************************
3414 * GetProcessWorkingSetSize (KERNEL32.@)
3416 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3417 PSIZE_T maxset)
3419 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3420 /* 32 MB working set size */
3421 if (minset) *minset = 32*1024*1024;
3422 if (maxset) *maxset = 32*1024*1024;
3423 return TRUE;
3427 /***********************************************************************
3428 * SetProcessShutdownParameters (KERNEL32.@)
3430 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3432 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3433 shutdown_flags = flags;
3434 shutdown_priority = level;
3435 return TRUE;
3439 /***********************************************************************
3440 * GetProcessShutdownParameters (KERNEL32.@)
3443 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3445 *lpdwLevel = shutdown_priority;
3446 *lpdwFlags = shutdown_flags;
3447 return TRUE;
3451 /***********************************************************************
3452 * GetProcessPriorityBoost (KERNEL32.@)
3454 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3456 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3458 /* Report that no boost is present.. */
3459 *pDisablePriorityBoost = FALSE;
3461 return TRUE;
3464 /***********************************************************************
3465 * SetProcessPriorityBoost (KERNEL32.@)
3467 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3469 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3470 /* Say we can do it. I doubt the program will notice that we don't. */
3471 return TRUE;
3475 /***********************************************************************
3476 * ReadProcessMemory (KERNEL32.@)
3478 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3479 SIZE_T *bytes_read )
3481 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3482 if (status) SetLastError( RtlNtStatusToDosError(status) );
3483 return !status;
3487 /***********************************************************************
3488 * WriteProcessMemory (KERNEL32.@)
3490 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3491 SIZE_T *bytes_written )
3493 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3494 if (status) SetLastError( RtlNtStatusToDosError(status) );
3495 return !status;
3499 /****************************************************************************
3500 * FlushInstructionCache (KERNEL32.@)
3502 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3504 NTSTATUS status;
3505 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3506 if (status) SetLastError( RtlNtStatusToDosError(status) );
3507 return !status;
3511 /******************************************************************
3512 * GetProcessIoCounters (KERNEL32.@)
3514 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3516 NTSTATUS status;
3518 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3519 ioc, sizeof(*ioc), NULL);
3520 if (status) SetLastError( RtlNtStatusToDosError(status) );
3521 return !status;
3524 /******************************************************************
3525 * GetProcessHandleCount (KERNEL32.@)
3527 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3529 NTSTATUS status;
3531 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3532 cnt, sizeof(*cnt), NULL);
3533 if (status) SetLastError( RtlNtStatusToDosError(status) );
3534 return !status;
3537 /******************************************************************
3538 * QueryFullProcessImageNameA (KERNEL32.@)
3540 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3542 BOOL retval;
3543 DWORD pdwSizeW = *pdwSize;
3544 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3546 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3548 if(retval)
3549 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3550 lpExeName, *pdwSize, NULL, NULL));
3551 if(retval)
3552 *pdwSize = strlen(lpExeName);
3554 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3555 return retval;
3558 /******************************************************************
3559 * QueryFullProcessImageNameW (KERNEL32.@)
3561 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3563 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3564 UNICODE_STRING *dynamic_buffer = NULL;
3565 UNICODE_STRING *result = NULL;
3566 NTSTATUS status;
3567 DWORD needed;
3569 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3570 * is a DOS path and we depend on this. */
3571 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3572 sizeof(buffer) - sizeof(WCHAR), &needed);
3573 if (status == STATUS_INFO_LENGTH_MISMATCH)
3575 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3576 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3577 result = dynamic_buffer;
3579 else
3580 result = (PUNICODE_STRING)buffer;
3582 if (status) goto cleanup;
3584 if (dwFlags & PROCESS_NAME_NATIVE)
3586 WCHAR drive[3];
3587 WCHAR device[1024];
3588 DWORD ntlen, devlen;
3590 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3592 /* We cannot convert it to an NT device path so fail */
3593 status = STATUS_NO_SUCH_DEVICE;
3594 goto cleanup;
3597 /* Find this drive's NT device path */
3598 drive[0] = result->Buffer[0];
3599 drive[1] = ':';
3600 drive[2] = 0;
3601 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3603 status = STATUS_NO_SUCH_DEVICE;
3604 goto cleanup;
3607 devlen = lstrlenW(device);
3608 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3609 if (ntlen + 1 > *pdwSize)
3611 status = STATUS_BUFFER_TOO_SMALL;
3612 goto cleanup;
3614 *pdwSize = ntlen;
3616 memcpy(lpExeName, device, devlen * sizeof(*device));
3617 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3618 lpExeName[*pdwSize] = 0;
3619 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3621 else
3623 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3625 status = STATUS_BUFFER_TOO_SMALL;
3626 goto cleanup;
3629 *pdwSize = result->Length/sizeof(WCHAR);
3630 memcpy( lpExeName, result->Buffer, result->Length );
3631 lpExeName[*pdwSize] = 0;
3634 cleanup:
3635 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3636 if (status) SetLastError( RtlNtStatusToDosError(status) );
3637 return !status;
3640 /***********************************************************************
3641 * K32GetProcessImageFileNameA (KERNEL32.@)
3643 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3645 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3648 /***********************************************************************
3649 * K32GetProcessImageFileNameW (KERNEL32.@)
3651 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3653 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3656 /***********************************************************************
3657 * K32EnumProcesses (KERNEL32.@)
3659 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3661 SYSTEM_PROCESS_INFORMATION *spi;
3662 ULONG size = 0x4000;
3663 void *buf = NULL;
3664 NTSTATUS status;
3666 do {
3667 size *= 2;
3668 HeapFree(GetProcessHeap(), 0, buf);
3669 buf = HeapAlloc(GetProcessHeap(), 0, size);
3670 if (!buf)
3671 return FALSE;
3673 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3674 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3676 if (status != STATUS_SUCCESS)
3678 HeapFree(GetProcessHeap(), 0, buf);
3679 SetLastError(RtlNtStatusToDosError(status));
3680 return FALSE;
3683 spi = buf;
3685 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3687 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3688 *lpcbUsed += sizeof(DWORD);
3690 if (spi->NextEntryOffset == 0)
3691 break;
3693 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3696 HeapFree(GetProcessHeap(), 0, buf);
3697 return TRUE;
3700 /***********************************************************************
3701 * K32QueryWorkingSet (KERNEL32.@)
3703 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3705 NTSTATUS status;
3707 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3709 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3711 if (status)
3713 SetLastError( RtlNtStatusToDosError( status ) );
3714 return FALSE;
3716 return TRUE;
3719 /***********************************************************************
3720 * K32QueryWorkingSetEx (KERNEL32.@)
3722 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3724 NTSTATUS status;
3726 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3728 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3730 if (status)
3732 SetLastError( RtlNtStatusToDosError( status ) );
3733 return FALSE;
3735 return TRUE;
3738 /***********************************************************************
3739 * K32GetProcessMemoryInfo (KERNEL32.@)
3741 * Retrieve memory usage information for a given process
3744 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3745 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3747 NTSTATUS status;
3748 VM_COUNTERS vmc;
3750 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3752 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3753 return FALSE;
3756 status = NtQueryInformationProcess(process, ProcessVmCounters,
3757 &vmc, sizeof(vmc), NULL);
3759 if (status)
3761 SetLastError(RtlNtStatusToDosError(status));
3762 return FALSE;
3765 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3766 pmc->PageFaultCount = vmc.PageFaultCount;
3767 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3768 pmc->WorkingSetSize = vmc.WorkingSetSize;
3769 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3770 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3771 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3772 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3773 pmc->PagefileUsage = vmc.PagefileUsage;
3774 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3776 return TRUE;
3779 /***********************************************************************
3780 * ProcessIdToSessionId (KERNEL32.@)
3781 * This function is available on Terminal Server 4SP4 and Windows 2000
3783 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3785 if (procid != GetCurrentProcessId())
3786 FIXME("Unsupported for other processes.\n");
3788 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3789 return TRUE;
3793 /***********************************************************************
3794 * RegisterServiceProcess (KERNEL32.@)
3796 * A service process calls this function to ensure that it continues to run
3797 * even after a user logged off.
3799 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3801 /* I don't think that Wine needs to do anything in this function */
3802 return 1; /* success */
3806 /**********************************************************************
3807 * IsWow64Process (KERNEL32.@)
3809 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3811 ULONG_PTR pbi;
3812 NTSTATUS status;
3814 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3816 if (status != STATUS_SUCCESS)
3818 SetLastError( RtlNtStatusToDosError( status ) );
3819 return FALSE;
3821 *Wow64Process = (pbi != 0);
3822 return TRUE;
3826 /***********************************************************************
3827 * GetCurrentProcess (KERNEL32.@)
3829 * Get a handle to the current process.
3831 * PARAMS
3832 * None.
3834 * RETURNS
3835 * A handle representing the current process.
3837 #undef GetCurrentProcess
3838 HANDLE WINAPI GetCurrentProcess(void)
3840 return (HANDLE)~(ULONG_PTR)0;
3843 /***********************************************************************
3844 * GetLogicalProcessorInformation (KERNEL32.@)
3846 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3848 NTSTATUS status;
3850 TRACE("(%p,%p)\n", buffer, pBufLen);
3852 if(!pBufLen)
3854 SetLastError(ERROR_INVALID_PARAMETER);
3855 return FALSE;
3858 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3860 if (status == STATUS_INFO_LENGTH_MISMATCH)
3862 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3863 return FALSE;
3865 if (status != STATUS_SUCCESS)
3867 SetLastError( RtlNtStatusToDosError( status ) );
3868 return FALSE;
3870 return TRUE;
3873 /***********************************************************************
3874 * GetLogicalProcessorInformationEx (KERNEL32.@)
3876 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
3878 NTSTATUS status;
3880 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
3882 if (!len)
3884 SetLastError( ERROR_INVALID_PARAMETER );
3885 return FALSE;
3888 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
3889 buffer, *len, len );
3890 if (status == STATUS_INFO_LENGTH_MISMATCH)
3892 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3893 return FALSE;
3895 if (status != STATUS_SUCCESS)
3897 SetLastError( RtlNtStatusToDosError( status ) );
3898 return FALSE;
3900 return TRUE;
3903 /***********************************************************************
3904 * CmdBatNotification (KERNEL32.@)
3906 * Notifies the system that a batch file has started or finished.
3908 * PARAMS
3909 * bBatchRunning [I] TRUE if a batch file has started or
3910 * FALSE if a batch file has finished executing.
3912 * RETURNS
3913 * Unknown.
3915 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3917 FIXME("%d\n", bBatchRunning);
3918 return FALSE;
3922 /***********************************************************************
3923 * RegisterApplicationRestart (KERNEL32.@)
3925 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3927 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3929 return S_OK;
3932 /**********************************************************************
3933 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3935 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3937 static int once;
3938 if (!once++) FIXME("stub\n");
3939 /* Return current session id. */
3940 return NtCurrentTeb()->Peb->SessionId;
3943 /**********************************************************************
3944 * GetSystemDEPPolicy (KERNEL32.@)
3946 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3948 FIXME("stub\n");
3949 return OptIn;
3952 /**********************************************************************
3953 * SetProcessDEPPolicy (KERNEL32.@)
3955 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3957 FIXME("(%d): stub\n", newDEP);
3958 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3959 return FALSE;
3962 /**********************************************************************
3963 * ApplicationRecoveryFinished (KERNEL32.@)
3965 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3967 FIXME(": stub\n");
3968 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3971 /**********************************************************************
3972 * ApplicationRecoveryInProgress (KERNEL32.@)
3974 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3976 FIXME(":%p stub\n", canceled);
3977 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3978 return E_FAIL;
3981 /**********************************************************************
3982 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3984 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3986 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3987 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3988 return E_FAIL;
3991 /**********************************************************************
3992 * GetNumaHighestNodeNumber (KERNEL32.@)
3994 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
3996 *highestnode = 0;
3997 FIXME("(%p): semi-stub\n", highestnode);
3998 return TRUE;
4001 /**********************************************************************
4002 * GetNumaNodeProcessorMask (KERNEL32.@)
4004 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4006 FIXME("(%c %p): stub\n", node, mask);
4007 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4008 return FALSE;
4011 /**********************************************************************
4012 * GetNumaAvailableMemoryNode (KERNEL32.@)
4014 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4016 FIXME("(%c %p): stub\n", node, available_bytes);
4017 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4018 return FALSE;
4021 /***********************************************************************
4022 * GetNumaProcessorNode (KERNEL32.@)
4024 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4026 SYSTEM_INFO si;
4028 TRACE("(%d, %p)\n", processor, node);
4030 GetSystemInfo( &si );
4031 if (processor < si.dwNumberOfProcessors)
4033 *node = 0;
4034 return TRUE;
4037 *node = 0xFF;
4038 SetLastError(ERROR_INVALID_PARAMETER);
4039 return FALSE;
4042 /**********************************************************************
4043 * GetProcessDEPPolicy (KERNEL32.@)
4045 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4047 NTSTATUS status;
4048 ULONG dep_flags;
4050 TRACE("(%p %p %p)\n", process, flags, permanent);
4052 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4053 &dep_flags, sizeof(dep_flags), NULL );
4054 if (!status)
4057 if (flags)
4059 *flags = 0;
4060 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4061 *flags |= PROCESS_DEP_ENABLE;
4062 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4063 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4066 if (permanent)
4067 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4070 if (status) SetLastError( RtlNtStatusToDosError(status) );
4071 return !status;
4074 /**********************************************************************
4075 * FlushProcessWriteBuffers (KERNEL32.@)
4077 VOID WINAPI FlushProcessWriteBuffers(void)
4079 static int once = 0;
4081 if (!once++)
4082 FIXME(": stub\n");
4085 /***********************************************************************
4086 * UnregisterApplicationRestart (KERNEL32.@)
4088 HRESULT WINAPI UnregisterApplicationRestart(void)
4090 FIXME(": stub\n");
4091 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4092 return S_OK;
4095 /***********************************************************************
4096 * GetSystemFirmwareTable (KERNEL32.@)
4098 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4100 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4101 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4102 return 0;
4105 struct proc_thread_attr
4107 DWORD_PTR attr;
4108 SIZE_T size;
4109 void *value;
4112 struct _PROC_THREAD_ATTRIBUTE_LIST
4114 DWORD mask; /* bitmask of items in list */
4115 DWORD size; /* max number of items in list */
4116 DWORD count; /* number of items in list */
4117 DWORD pad;
4118 DWORD_PTR unk;
4119 struct proc_thread_attr attrs[1];
4122 /***********************************************************************
4123 * InitializeProcThreadAttributeList (KERNEL32.@)
4125 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4126 DWORD count, DWORD flags, SIZE_T *size)
4128 SIZE_T needed;
4129 BOOL ret = FALSE;
4131 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4133 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4134 if (list && *size >= needed)
4136 list->mask = 0;
4137 list->size = count;
4138 list->count = 0;
4139 list->unk = 0;
4140 ret = TRUE;
4142 else
4143 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4145 *size = needed;
4146 return ret;
4149 /***********************************************************************
4150 * UpdateProcThreadAttribute (KERNEL32.@)
4152 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4153 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4154 void *prev_ret, SIZE_T *size_ret)
4156 DWORD mask;
4157 struct proc_thread_attr *entry;
4159 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4161 if (list->count >= list->size)
4163 SetLastError(ERROR_GEN_FAILURE);
4164 return FALSE;
4167 switch (attr)
4169 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4170 if (size != sizeof(HANDLE))
4172 SetLastError(ERROR_BAD_LENGTH);
4173 return FALSE;
4175 break;
4177 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4178 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4180 SetLastError(ERROR_BAD_LENGTH);
4181 return FALSE;
4183 break;
4185 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4186 if (size != sizeof(PROCESSOR_NUMBER))
4188 SetLastError(ERROR_BAD_LENGTH);
4189 return FALSE;
4191 break;
4193 default:
4194 SetLastError(ERROR_NOT_SUPPORTED);
4195 return FALSE;
4198 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4200 if (list->mask & mask)
4202 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4203 return FALSE;
4206 list->mask |= mask;
4208 entry = list->attrs + list->count;
4209 entry->attr = attr;
4210 entry->size = size;
4211 entry->value = value;
4212 list->count++;
4214 return TRUE;
4217 /***********************************************************************
4218 * DeleteProcThreadAttributeList (KERNEL32.@)
4220 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4222 return;
4225 /**********************************************************************
4226 * BaseFlushAppcompatCache (KERNEL32.@)
4228 BOOL WINAPI BaseFlushAppcompatCache(void)
4230 FIXME(": stub\n");
4231 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4232 return FALSE;