combase: Add stub for RoGetApartmentIdentifier.
[wine.git] / dlls / kernel32 / process.c
blob47f1cfba965220480532d44ae1da453480920162
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/exception.h"
61 #include "wine/library.h"
62 #include "wine/server.h"
63 #include "wine/unicode.h"
64 #include "wine/debug.h"
66 WINE_DEFAULT_DEBUG_CHANNEL(process);
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[] = {'C',':','\\','w','i','n','d','o','w','s',0};
93 const WCHAR DIR_System[] = {'C',':','\\','w','i','n','d','o','w','s',
94 '\\','s','y','s','t','e','m','3','2',0};
95 const WCHAR *DIR_SysWow64 = NULL;
97 /* Process flags */
98 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
99 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
100 #define PDB32_DOS_PROC 0x0010 /* Dos process */
101 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
102 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
103 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
105 static const WCHAR exeW[] = {'.','e','x','e',0};
106 static const WCHAR comW[] = {'.','c','o','m',0};
107 static const WCHAR batW[] = {'.','b','a','t',0};
108 static const WCHAR cmdW[] = {'.','c','m','d',0};
109 static const WCHAR pifW[] = {'.','p','i','f',0};
110 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
112 static void exec_process( LPCWSTR name );
114 extern void SHELL_LoadRegistry(void);
117 /***********************************************************************
118 * contains_path
120 static inline BOOL contains_path( LPCWSTR name )
122 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
126 /***********************************************************************
127 * is_special_env_var
129 * Check if an environment variable needs to be handled specially when
130 * passed through the Unix environment (i.e. prefixed with "WINE").
132 static inline BOOL is_special_env_var( const char *var )
134 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
135 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
136 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
137 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
138 !strncmp( var, "TMP=", sizeof("TMP=")-1 ) ||
139 !strncmp( var, "QT_", sizeof("QT_")-1 ) ||
140 !strncmp( var, "VK_", sizeof("VK_")-1 ));
144 /***********************************************************************
145 * is_path_prefix
147 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
149 unsigned int len = strlenW( prefix );
151 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
152 while (filename[len] == '\\') len++;
153 return len;
157 /***************************************************************************
158 * get_builtin_path
160 * Get the path of a builtin module when the native file does not exist.
162 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
163 UINT size, struct binary_info *binary_info )
165 WCHAR *file_part;
166 UINT len;
167 void *redir_disabled = 0;
168 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
170 /* builtin names cannot be empty or contain spaces */
171 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
173 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
174 Wow64RevertWow64FsRedirection( redir_disabled );
176 if (contains_path( libname ))
178 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
179 filename, &file_part ) > size * sizeof(WCHAR))
180 return FALSE; /* too long */
182 if ((len = is_path_prefix( DIR_System, filename )))
184 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
186 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
188 flags = 0;
190 else return FALSE;
192 if (filename + len != file_part) return FALSE;
194 else
196 len = strlenW( DIR_System );
197 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
198 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
199 file_part = filename + len;
200 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
201 strcpyW( file_part, libname );
202 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
204 if (ext && !strchrW( file_part, '.' ))
206 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
207 return FALSE; /* too long */
208 strcatW( file_part, ext );
210 binary_info->type = BINARY_UNIX_LIB;
211 binary_info->flags = flags;
212 binary_info->res_start = 0;
213 binary_info->res_end = 0;
214 /* assume current arch */
215 #if defined(__i386__) || defined(__x86_64__)
216 binary_info->arch = (flags & BINARY_FLAG_64BIT) ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
217 #elif defined(__powerpc__)
218 binary_info->arch = IMAGE_FILE_MACHINE_POWERPC;
219 #elif defined(__arm__) && !defined(__ARMEB__)
220 binary_info->arch = IMAGE_FILE_MACHINE_ARMNT;
221 #elif defined(__aarch64__)
222 binary_info->arch = IMAGE_FILE_MACHINE_ARM64;
223 #else
224 binary_info->arch = IMAGE_FILE_MACHINE_UNKNOWN;
225 #endif
226 return TRUE;
230 /***********************************************************************
231 * open_exe_file
233 * Open a specific exe file, taking load order into account.
234 * Returns the file handle or 0 for a builtin exe.
236 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
238 HANDLE handle;
240 TRACE("looking for %s\n", debugstr_w(name) );
242 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
243 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
245 WCHAR buffer[MAX_PATH];
246 /* file doesn't exist, check for builtin */
247 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
248 handle = 0;
250 else MODULE_get_binary_info( handle, binary_info );
252 return handle;
256 /***********************************************************************
257 * find_exe_file
259 * Open an exe file, and return the full name and file handle.
260 * Returns FALSE if file could not be found.
262 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
263 HANDLE *handle, struct binary_info *binary_info )
265 TRACE("looking for %s\n", debugstr_w(name) );
267 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
268 /* no builtin found, try native without extension in case it is a Unix app */
269 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
271 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
272 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
273 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
275 MODULE_get_binary_info( *handle, binary_info );
276 return TRUE;
278 return FALSE;
282 /***********************************************************************
283 * build_initial_environment
285 * Build the Win32 environment from the Unix environment
287 static BOOL build_initial_environment(void)
289 SIZE_T size = 1;
290 char **e;
291 WCHAR *p, *endptr;
292 void *ptr;
293 char **env = __wine_get_main_environment();
295 /* Compute the total size of the Unix environment */
296 for (e = env; *e; e++)
298 if (is_special_env_var( *e )) continue;
299 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
301 size *= sizeof(WCHAR);
303 /* Now allocate the environment */
304 ptr = NULL;
305 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
306 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
307 return FALSE;
309 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
310 endptr = p + size / sizeof(WCHAR);
312 /* And fill it with the Unix environment */
313 for (e = env; *e; e++)
315 char *str = *e;
317 /* skip Unix special variables and use the Wine variants instead */
318 if (!strncmp( str, "WINE", 4 ))
320 if (is_special_env_var( str + 4 )) str += 4;
321 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
323 else if (is_special_env_var( str )) continue; /* skip it */
325 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
326 p += strlenW(p) + 1;
328 *p = 0;
329 return TRUE;
333 /***********************************************************************
334 * set_registry_variables
336 * Set environment variables by enumerating the values of a key;
337 * helper for set_registry_environment().
338 * Note that Windows happily truncates the value if it's too big.
340 static void set_registry_variables( HANDLE hkey, ULONG type )
342 static const WCHAR pathW[] = {'P','A','T','H'};
343 static const WCHAR sep[] = {';',0};
344 UNICODE_STRING env_name, env_value;
345 NTSTATUS status;
346 DWORD size;
347 int index;
348 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
349 WCHAR tmpbuf[1024];
350 UNICODE_STRING tmp;
351 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
353 tmp.Buffer = tmpbuf;
354 tmp.MaximumLength = sizeof(tmpbuf);
356 for (index = 0; ; index++)
358 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
359 buffer, sizeof(buffer), &size );
360 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
361 break;
362 if (info->Type != type)
363 continue;
364 env_name.Buffer = info->Name;
365 env_name.Length = env_name.MaximumLength = info->NameLength;
366 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
367 env_value.Length = info->DataLength;
368 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
369 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
370 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
371 if (!env_value.Length) continue;
372 if (info->Type == REG_EXPAND_SZ)
374 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
375 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
376 RtlCopyUnicodeString( &env_value, &tmp );
378 /* PATH is magic */
379 if (env_name.Length == sizeof(pathW) &&
380 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
381 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
383 RtlAppendUnicodeToString( &tmp, sep );
384 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
385 RtlCopyUnicodeString( &env_value, &tmp );
387 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
392 /***********************************************************************
393 * set_registry_environment
395 * Set the environment variables specified in the registry.
397 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
398 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
399 * on the order in which the variables are processed. But on Windows it
400 * does not really matter since they only use %SystemDrive% and
401 * %SystemRoot% which are predefined. But Wine defines these in the
402 * registry, so we need two passes.
404 static BOOL set_registry_environment( BOOL volatile_only )
406 static const WCHAR env_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
407 'M','a','c','h','i','n','e','\\',
408 'S','y','s','t','e','m','\\',
409 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
410 'C','o','n','t','r','o','l','\\',
411 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
412 'E','n','v','i','r','o','n','m','e','n','t',0};
413 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
414 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};
416 OBJECT_ATTRIBUTES attr;
417 UNICODE_STRING nameW;
418 HANDLE hkey;
419 BOOL ret = FALSE;
421 attr.Length = sizeof(attr);
422 attr.RootDirectory = 0;
423 attr.ObjectName = &nameW;
424 attr.Attributes = 0;
425 attr.SecurityDescriptor = NULL;
426 attr.SecurityQualityOfService = NULL;
428 /* first the system environment variables */
429 RtlInitUnicodeString( &nameW, env_keyW );
430 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
432 set_registry_variables( hkey, REG_SZ );
433 set_registry_variables( hkey, REG_EXPAND_SZ );
434 NtClose( hkey );
435 ret = TRUE;
438 /* then the ones for the current user */
439 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
440 RtlInitUnicodeString( &nameW, envW );
441 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
443 set_registry_variables( hkey, REG_SZ );
444 set_registry_variables( hkey, REG_EXPAND_SZ );
445 NtClose( hkey );
448 RtlInitUnicodeString( &nameW, volatile_envW );
449 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
451 set_registry_variables( hkey, REG_SZ );
452 set_registry_variables( hkey, REG_EXPAND_SZ );
453 NtClose( hkey );
456 NtClose( attr.RootDirectory );
457 return ret;
461 /***********************************************************************
462 * get_reg_value
464 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
466 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
467 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
468 DWORD len, size = sizeof(buffer);
469 WCHAR *ret = NULL;
470 UNICODE_STRING nameW;
472 RtlInitUnicodeString( &nameW, name );
473 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
474 return NULL;
476 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
477 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
479 if (info->Type == REG_EXPAND_SZ)
481 UNICODE_STRING value, expanded;
483 value.MaximumLength = len * sizeof(WCHAR);
484 value.Buffer = (WCHAR *)info->Data;
485 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
486 value.Length = len * sizeof(WCHAR);
487 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
488 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
489 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
490 else RtlFreeUnicodeString( &expanded );
492 else if (info->Type == REG_SZ)
494 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
496 memcpy( ret, info->Data, len * sizeof(WCHAR) );
497 ret[len] = 0;
500 return ret;
504 /***********************************************************************
505 * set_additional_environment
507 * Set some additional environment variables not specified in the registry.
509 static void set_additional_environment(void)
511 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
512 'M','a','c','h','i','n','e','\\',
513 'S','o','f','t','w','a','r','e','\\',
514 'M','i','c','r','o','s','o','f','t','\\',
515 'W','i','n','d','o','w','s',' ','N','T','\\',
516 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
517 'P','r','o','f','i','l','e','L','i','s','t',0};
518 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
519 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
520 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
521 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
522 static const WCHAR programdataW[] = {'P','r','o','g','r','a','m','D','a','t','a',0};
523 OBJECT_ATTRIBUTES attr;
524 UNICODE_STRING nameW;
525 WCHAR *profile_dir = NULL, *all_users_dir = NULL, *program_data_dir = NULL;
526 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
527 HANDLE hkey;
528 DWORD len;
530 /* ComputerName */
531 len = sizeof(buf) / sizeof(WCHAR);
532 if (GetComputerNameW( buf, &len ))
533 SetEnvironmentVariableW( computernameW, buf );
535 /* set the ALLUSERSPROFILE variables */
537 attr.Length = sizeof(attr);
538 attr.RootDirectory = 0;
539 attr.ObjectName = &nameW;
540 attr.Attributes = 0;
541 attr.SecurityDescriptor = NULL;
542 attr.SecurityQualityOfService = NULL;
543 RtlInitUnicodeString( &nameW, profile_keyW );
544 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
546 profile_dir = get_reg_value( hkey, profiles_valueW );
547 all_users_dir = get_reg_value( hkey, all_users_valueW );
548 program_data_dir = get_reg_value( hkey, programdataW );
549 NtClose( hkey );
552 if (profile_dir && all_users_dir)
554 WCHAR *value, *p;
556 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
557 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
558 strcpyW( value, profile_dir );
559 p = value + strlenW(value);
560 if (p > value && p[-1] != '\\') *p++ = '\\';
561 strcpyW( p, all_users_dir );
562 SetEnvironmentVariableW( allusersW, value );
563 HeapFree( GetProcessHeap(), 0, value );
566 if (program_data_dir)
568 SetEnvironmentVariableW( programdataW, program_data_dir );
571 HeapFree( GetProcessHeap(), 0, all_users_dir );
572 HeapFree( GetProcessHeap(), 0, profile_dir );
573 HeapFree( GetProcessHeap(), 0, program_data_dir );
576 /***********************************************************************
577 * set_wow64_environment
579 * Set the environment variables that change across 32/64/Wow64.
581 static void set_wow64_environment(void)
583 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};
584 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};
585 static const WCHAR x86W[] = {'x','8','6',0};
586 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
587 'M','a','c','h','i','n','e','\\',
588 'S','o','f','t','w','a','r','e','\\',
589 'M','i','c','r','o','s','o','f','t','\\',
590 'W','i','n','d','o','w','s','\\',
591 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
592 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
593 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
594 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
595 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
596 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
597 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
598 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
599 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
601 OBJECT_ATTRIBUTES attr;
602 UNICODE_STRING nameW;
603 WCHAR arch[64];
604 WCHAR *value;
605 HANDLE hkey;
607 /* set the PROCESSOR_ARCHITECTURE variable */
609 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
611 if (is_win64)
613 SetEnvironmentVariableW( archW, arch );
614 SetEnvironmentVariableW( arch6432W, NULL );
617 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
619 if (is_wow64)
621 SetEnvironmentVariableW( arch6432W, arch );
622 SetEnvironmentVariableW( archW, x86W );
626 attr.Length = sizeof(attr);
627 attr.RootDirectory = 0;
628 attr.ObjectName = &nameW;
629 attr.Attributes = 0;
630 attr.SecurityDescriptor = NULL;
631 attr.SecurityQualityOfService = NULL;
632 RtlInitUnicodeString( &nameW, versionW );
633 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
635 /* set the ProgramFiles variables */
637 if ((value = get_reg_value( hkey, progdirW )))
639 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
640 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
641 HeapFree( GetProcessHeap(), 0, value );
643 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
645 SetEnvironmentVariableW( progfilesW, value );
646 HeapFree( GetProcessHeap(), 0, value );
649 /* set the CommonProgramFiles variables */
651 if ((value = get_reg_value( hkey, commondirW )))
653 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
654 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
655 HeapFree( GetProcessHeap(), 0, value );
657 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
659 SetEnvironmentVariableW( commonfilesW, value );
660 HeapFree( GetProcessHeap(), 0, value );
663 NtClose( hkey );
666 /***********************************************************************
667 * set_library_wargv
669 * Set the Wine library Unicode argv global variables.
671 static void set_library_wargv( char **argv )
673 int argc;
674 char *q;
675 WCHAR *p;
676 WCHAR **wargv;
677 DWORD total = 0;
679 for (argc = 0; argv[argc]; argc++)
680 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
682 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
683 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
684 p = (WCHAR *)(wargv + argc + 1);
685 for (argc = 0; argv[argc]; argc++)
687 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
688 wargv[argc] = p;
689 p += reslen;
690 total -= reslen;
692 wargv[argc] = NULL;
694 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
696 for (argc = 0; wargv[argc]; argc++)
697 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
699 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
700 q = (char *)(argv + argc + 1);
701 for (argc = 0; wargv[argc]; argc++)
703 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
704 argv[argc] = q;
705 q += reslen;
706 total -= reslen;
708 argv[argc] = NULL;
710 __wine_main_argc = argc;
711 __wine_main_argv = argv;
712 __wine_main_wargv = wargv;
716 /***********************************************************************
717 * update_library_argv0
719 * Update the argv[0] global variable with the binary we have found.
721 static void update_library_argv0( const WCHAR *argv0 )
723 DWORD len = strlenW( argv0 );
725 if (len > strlenW( __wine_main_wargv[0] ))
727 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
729 strcpyW( __wine_main_wargv[0], argv0 );
731 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
732 if (len > strlen( __wine_main_argv[0] ) + 1)
734 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
736 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
740 /***********************************************************************
741 * build_command_line
743 * Build the command line of a process from the argv array.
745 * Note that it does NOT necessarily include the file name.
746 * Sometimes we don't even have any command line options at all.
748 * We must quote and escape characters so that the argv array can be rebuilt
749 * from the command line:
750 * - spaces and tabs must be quoted
751 * 'a b' -> '"a b"'
752 * - quotes must be escaped
753 * '"' -> '\"'
754 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
755 * resulting in an odd number of '\' followed by a '"'
756 * '\"' -> '\\\"'
757 * '\\"' -> '\\\\\"'
758 * - '\'s are followed by the closing '"' must be doubled,
759 * resulting in an even number of '\' followed by a '"'
760 * ' \' -> '" \\"'
761 * ' \\' -> '" \\\\"'
762 * - '\'s that are not followed by a '"' can be left as is
763 * 'a\b' == 'a\b'
764 * 'a\\b' == 'a\\b'
766 static BOOL build_command_line( WCHAR **argv )
768 int len;
769 WCHAR **arg;
770 LPWSTR p;
771 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
773 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
775 len = 0;
776 for (arg = argv; *arg; arg++)
778 BOOL has_space;
779 int bcount;
780 WCHAR* a;
782 has_space=FALSE;
783 bcount=0;
784 a=*arg;
785 if( !*a ) has_space=TRUE;
786 while (*a!='\0') {
787 if (*a=='\\') {
788 bcount++;
789 } else {
790 if (*a==' ' || *a=='\t') {
791 has_space=TRUE;
792 } else if (*a=='"') {
793 /* doubling of '\' preceding a '"',
794 * plus escaping of said '"'
796 len+=2*bcount+1;
798 bcount=0;
800 a++;
802 len+=(a-*arg)+1 /* for the separating space */;
803 if (has_space)
804 len+=2+bcount; /* for the quotes and doubling of '\' preceding the closing quote */
807 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
808 return FALSE;
810 p = rupp->CommandLine.Buffer;
811 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
812 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
813 for (arg = argv; *arg; arg++)
815 BOOL has_space,has_quote;
816 WCHAR* a;
817 int bcount;
819 /* Check for quotes and spaces in this argument */
820 has_space=has_quote=FALSE;
821 a=*arg;
822 if( !*a ) has_space=TRUE;
823 while (*a!='\0') {
824 if (*a==' ' || *a=='\t') {
825 has_space=TRUE;
826 if (has_quote)
827 break;
828 } else if (*a=='"') {
829 has_quote=TRUE;
830 if (has_space)
831 break;
833 a++;
836 /* Now transfer it to the command line */
837 if (has_space)
838 *p++='"';
839 if (has_quote || has_space) {
840 bcount=0;
841 a=*arg;
842 while (*a!='\0') {
843 if (*a=='\\') {
844 *p++=*a;
845 bcount++;
846 } else {
847 if (*a=='"') {
848 int i;
850 /* Double all the '\\' preceding this '"', plus one */
851 for (i=0;i<=bcount;i++)
852 *p++='\\';
853 *p++='"';
854 } else {
855 *p++=*a;
857 bcount=0;
859 a++;
861 } else {
862 WCHAR* x = *arg;
863 while ((*p=*x++)) p++;
865 if (has_space) {
866 int i;
868 /* Double all the '\' preceding the closing quote */
869 for (i=0;i<bcount;i++)
870 *p++='\\';
871 *p++='"';
873 *p++=' ';
875 if (p > rupp->CommandLine.Buffer)
876 p--; /* remove last space */
877 *p = '\0';
879 return TRUE;
883 /***********************************************************************
884 * init_current_directory
886 * Initialize the current directory from the Unix cwd or the parent info.
888 static void init_current_directory( CURDIR *cur_dir )
890 UNICODE_STRING dir_str;
891 const char *pwd;
892 char *cwd;
893 int size;
895 /* if we received a cur dir from the parent, try this first */
897 if (cur_dir->DosPath.Length)
899 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
902 /* now try to get it from the Unix cwd */
904 for (size = 256; ; size *= 2)
906 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
907 if (getcwd( cwd, size )) break;
908 HeapFree( GetProcessHeap(), 0, cwd );
909 if (errno == ERANGE) continue;
910 cwd = NULL;
911 break;
914 /* try to use PWD if it is valid, so that we don't resolve symlinks */
916 pwd = getenv( "PWD" );
917 if (cwd)
919 struct stat st1, st2;
921 if (!pwd || stat( pwd, &st1 ) == -1 ||
922 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
923 pwd = cwd;
926 if (pwd)
928 ANSI_STRING unix_name;
929 UNICODE_STRING nt_name;
930 RtlInitAnsiString( &unix_name, pwd );
931 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
933 UNICODE_STRING dos_path;
934 /* skip the \??\ prefix, nt_name is 0 terminated */
935 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
936 RtlSetCurrentDirectory_U( &dos_path );
937 RtlFreeUnicodeString( &nt_name );
941 if (!cur_dir->DosPath.Length) /* still not initialized */
943 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
944 "starting in the Windows directory.\n", cwd ? cwd : "" );
945 RtlInitUnicodeString( &dir_str, DIR_Windows );
946 RtlSetCurrentDirectory_U( &dir_str );
948 HeapFree( GetProcessHeap(), 0, cwd );
950 done:
951 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
955 /***********************************************************************
956 * init_windows_dirs
958 * Create the windows and system directories if necessary.
960 static void init_windows_dirs(void)
962 static const WCHAR default_syswow64W[] = {'C',':','\\','w','i','n','d','o','w','s',
963 '\\','s','y','s','w','o','w','6','4',0};
965 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
966 ERR( "directory %s could not be created, error %u\n",
967 debugstr_w(DIR_Windows), GetLastError() );
968 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
969 ERR( "directory %s could not be created, error %u\n",
970 debugstr_w(DIR_System), GetLastError() );
972 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
974 DIR_SysWow64 = default_syswow64W;
975 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
976 ERR( "directory %s could not be created, error %u\n",
977 debugstr_w(DIR_SysWow64), GetLastError() );
982 /***********************************************************************
983 * start_wineboot
985 * Start the wineboot process if necessary. Return the handles to wait on.
987 static void start_wineboot( HANDLE handles[2] )
989 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
991 handles[1] = 0;
992 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
994 ERR( "failed to create wineboot event, expect trouble\n" );
995 return;
997 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
999 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1000 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1001 STARTUPINFOW si;
1002 PROCESS_INFORMATION pi;
1003 void *redir;
1004 WCHAR app[MAX_PATH];
1005 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1007 memset( &si, 0, sizeof(si) );
1008 si.cb = sizeof(si);
1009 si.dwFlags = STARTF_USESTDHANDLES;
1010 si.hStdInput = 0;
1011 si.hStdOutput = 0;
1012 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1014 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1015 lstrcatW( app, wineboot );
1017 Wow64DisableWow64FsRedirection( &redir );
1018 strcpyW( cmdline, app );
1019 strcatW( cmdline, args );
1020 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1022 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1023 CloseHandle( pi.hThread );
1024 handles[1] = pi.hProcess;
1026 else
1028 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1029 CloseHandle( handles[0] );
1030 handles[0] = 0;
1032 Wow64RevertWow64FsRedirection( redir );
1037 #ifdef __i386__
1038 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1039 __ASM_GLOBAL_FUNC( call_process_entry,
1040 "pushl %ebp\n\t"
1041 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1042 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1043 "movl %esp,%ebp\n\t"
1044 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1045 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1046 "pushl 8(%ebp)\n\t"
1047 "call *12(%ebp)\n\t"
1048 "leave\n\t"
1049 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1050 __ASM_CFI(".cfi_same_value %ebp\n\t")
1051 "ret" )
1053 extern void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb ) DECLSPEC_HIDDEN;
1054 extern void WINAPI start_process_wrapper(void) DECLSPEC_HIDDEN;
1055 __ASM_GLOBAL_FUNC( start_process_wrapper,
1056 "pushl %ebp\n\t"
1057 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1058 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1059 "movl %esp,%ebp\n\t"
1060 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1061 "pushl %ebx\n\t" /* arg */
1062 "pushl %eax\n\t" /* entry */
1063 "call " __ASM_NAME("start_process") )
1064 #else
1065 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1067 return entry( peb );
1069 static void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb );
1070 #define start_process_wrapper start_process
1071 #endif
1073 /***********************************************************************
1074 * start_process
1076 * Startup routine of a new process. Runs on the new process stack.
1078 void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb )
1080 BOOL being_debugged;
1082 if (!entry)
1084 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1085 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1086 ExitThread( 1 );
1089 TRACE_(relay)( "\1Starting process %s (entryproc=%p)\n",
1090 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1092 __TRY
1094 if (!CheckRemoteDebuggerPresent( GetCurrentProcess(), &being_debugged ))
1095 being_debugged = FALSE;
1097 SetLastError( 0 ); /* clear error code */
1098 if (being_debugged) DbgBreakPoint();
1099 ExitThread( call_process_entry( peb, entry ));
1101 __EXCEPT(UnhandledExceptionFilter)
1103 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1105 __ENDTRY
1106 abort(); /* should not be reached */
1110 /***********************************************************************
1111 * set_process_name
1113 * Change the process name in the ps output.
1115 static void set_process_name( int argc, char *argv[] )
1117 BOOL shift_strings;
1118 char *p, *name;
1119 int i;
1121 #ifdef HAVE_SETPROCTITLE
1122 setproctitle("-%s", argv[1]);
1123 shift_strings = FALSE;
1124 #else
1125 p = argv[0];
1127 shift_strings = (argc >= 2);
1128 for (i = 1; i < argc; i++)
1130 p += strlen(p) + 1;
1131 if (p != argv[i])
1133 shift_strings = FALSE;
1134 break;
1137 #endif
1139 if (shift_strings)
1141 int offset = argv[1] - argv[0];
1142 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1143 memmove( argv[0], argv[1], end - argv[1] );
1144 memset( end - offset, 0, offset );
1145 for (i = 1; i < argc; i++)
1146 argv[i-1] = argv[i] - offset;
1147 argv[i-1] = NULL;
1149 else
1151 /* remove argv[0] */
1152 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1155 name = argv[0];
1156 if ((p = strrchr( name, '\\' ))) name = p + 1;
1157 if ((p = strrchr( name, '/' ))) name = p + 1;
1159 #if defined(HAVE_SETPROGNAME)
1160 setprogname( name );
1161 #endif
1163 #ifdef HAVE_PRCTL
1164 #ifndef PR_SET_NAME
1165 # define PR_SET_NAME 15
1166 #endif
1167 prctl( PR_SET_NAME, name );
1168 #endif /* HAVE_PRCTL */
1172 /***********************************************************************
1173 * __wine_kernel_init
1175 * Wine initialisation: load and start the main exe file.
1177 void CDECL __wine_kernel_init(void)
1179 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1180 static const WCHAR dotW[] = {'.',0};
1182 WCHAR *p, main_exe_name[MAX_PATH+1];
1183 PEB *peb = NtCurrentTeb()->Peb;
1184 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1185 HANDLE boot_events[2];
1186 BOOL got_environment = TRUE;
1188 /* Initialize everything */
1190 setbuf(stdout,NULL);
1191 setbuf(stderr,NULL);
1192 kernel32_handle = GetModuleHandleW(kernel32W);
1193 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1195 LOCALE_Init();
1197 if (!params->Environment)
1199 /* Copy the parent environment */
1200 if (!build_initial_environment()) exit(1);
1202 /* convert old configuration to new format */
1203 convert_old_config();
1205 got_environment = set_registry_environment( FALSE );
1206 set_additional_environment();
1209 init_windows_dirs();
1210 init_current_directory( &params->CurrentDirectory );
1212 set_process_name( __wine_main_argc, __wine_main_argv );
1213 set_library_wargv( __wine_main_argv );
1214 boot_events[0] = boot_events[1] = 0;
1216 if (peb->ProcessParameters->ImagePathName.Buffer)
1218 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1220 else
1222 struct binary_info binary_info;
1224 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1225 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1227 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1228 ExitProcess( GetLastError() );
1230 update_library_argv0( main_exe_name );
1231 if (!build_command_line( __wine_main_wargv )) goto error;
1232 start_wineboot( boot_events );
1235 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1236 p = strrchrW( main_exe_name, '.' );
1237 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1239 TRACE( "starting process name=%s argv[0]=%s\n",
1240 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1242 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1243 MODULE_get_dll_load_path( main_exe_name, -1 ));
1245 if (boot_events[0])
1247 DWORD timeout = 2 * 60 * 1000, count = 1;
1249 if (boot_events[1]) count++;
1250 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1251 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1252 ERR( "boot event wait timed out\n" );
1253 CloseHandle( boot_events[0] );
1254 if (boot_events[1]) CloseHandle( boot_events[1] );
1255 /* reload environment now that wineboot has run */
1256 set_registry_environment( got_environment );
1257 set_additional_environment();
1259 set_wow64_environment();
1261 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1263 DWORD_PTR args[1];
1264 WCHAR msgW[1024];
1265 char msg[1024];
1266 DWORD error = GetLastError();
1268 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1269 if (error == ERROR_BAD_EXE_FORMAT ||
1270 error == ERROR_INVALID_ADDRESS ||
1271 error == ERROR_NOT_ENOUGH_MEMORY)
1273 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1274 /* if we get back here, it failed */
1276 else if (error == ERROR_MOD_NOT_FOUND)
1278 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1279 else p = main_exe_name;
1280 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1282 /* args 1 and 2 are --app-name full_path */
1283 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1284 debugstr_w(__wine_main_wargv[3]) );
1285 ExitProcess( ERROR_BAD_EXE_FORMAT );
1287 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1288 ExitProcess( ERROR_FILE_NOT_FOUND );
1290 args[0] = (DWORD_PTR)main_exe_name;
1291 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1292 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1293 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1294 MESSAGE( "wine: %s", msg );
1295 ExitProcess( error );
1298 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1300 LdrInitializeThunk( start_process_wrapper, 0, 0, 0 );
1302 error:
1303 ExitProcess( GetLastError() );
1307 /***********************************************************************
1308 * build_argv
1310 * Build an argv array from a command-line.
1311 * 'reserved' is the number of args to reserve before the first one.
1313 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1315 int argc;
1316 char** argv;
1317 char *arg,*s,*d,*cmdline;
1318 int in_quotes,bcount,len;
1320 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1321 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1322 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1324 argc=reserved+1;
1325 bcount=0;
1326 in_quotes=0;
1327 s=cmdline;
1328 while (1) {
1329 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1330 /* space */
1331 argc++;
1332 /* skip the remaining spaces */
1333 while (*s==' ' || *s=='\t') {
1334 s++;
1336 if (*s=='\0')
1337 break;
1338 bcount=0;
1339 continue;
1340 } else if (*s=='\\') {
1341 /* '\', count them */
1342 bcount++;
1343 } else if ((*s=='"') && ((bcount & 1)==0)) {
1344 /* unescaped '"' */
1345 in_quotes=!in_quotes;
1346 bcount=0;
1347 } else {
1348 /* a regular character */
1349 bcount=0;
1351 s++;
1353 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1355 HeapFree( GetProcessHeap(), 0, cmdline );
1356 return NULL;
1359 arg = d = s = (char *)(argv + argc);
1360 memcpy( d, cmdline, len );
1361 bcount=0;
1362 in_quotes=0;
1363 argc=reserved;
1364 while (*s) {
1365 if ((*s==' ' || *s=='\t') && !in_quotes) {
1366 /* Close the argument and copy it */
1367 *d=0;
1368 argv[argc++]=arg;
1370 /* skip the remaining spaces */
1371 do {
1372 s++;
1373 } while (*s==' ' || *s=='\t');
1375 /* Start with a new argument */
1376 arg=d=s;
1377 bcount=0;
1378 } else if (*s=='\\') {
1379 /* '\\' */
1380 *d++=*s++;
1381 bcount++;
1382 } else if (*s=='"') {
1383 /* '"' */
1384 if ((bcount & 1)==0) {
1385 /* Preceded by an even number of '\', this is half that
1386 * number of '\', plus a '"' which we discard.
1388 d-=bcount/2;
1389 s++;
1390 in_quotes=!in_quotes;
1391 } else {
1392 /* Preceded by an odd number of '\', this is half that
1393 * number of '\' followed by a '"'
1395 d=d-bcount/2-1;
1396 *d++='"';
1397 s++;
1399 bcount=0;
1400 } else {
1401 /* a regular character */
1402 *d++=*s++;
1403 bcount=0;
1406 if (*arg) {
1407 *d='\0';
1408 argv[argc++]=arg;
1410 argv[argc]=NULL;
1412 HeapFree( GetProcessHeap(), 0, cmdline );
1413 return argv;
1417 /***********************************************************************
1418 * build_envp
1420 * Build the environment of a new child process.
1422 static char **build_envp( const WCHAR *envW )
1424 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1426 const WCHAR *end;
1427 char **envp;
1428 char *env, *p;
1429 int count = 1, length;
1430 unsigned int i;
1432 for (end = envW; *end; count++) end += strlenW(end) + 1;
1433 end++;
1434 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1435 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1436 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1438 for (p = env; *p; p += strlen(p) + 1)
1439 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1441 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1443 if (!(p = getenv(unix_vars[i]))) continue;
1444 length += strlen(unix_vars[i]) + strlen(p) + 2;
1445 count++;
1448 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1450 char **envptr = envp;
1451 char *dst = (char *)(envp + count);
1453 /* some variables must not be modified, so we get them directly from the unix env */
1454 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1456 if (!(p = getenv(unix_vars[i]))) continue;
1457 *envptr++ = strcpy( dst, unix_vars[i] );
1458 strcat( dst, "=" );
1459 strcat( dst, p );
1460 dst += strlen(dst) + 1;
1463 /* now put the Windows environment strings */
1464 for (p = env; *p; p += strlen(p) + 1)
1466 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1467 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1468 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1469 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1470 if (is_special_env_var( p )) /* prefix it with "WINE" */
1472 *envptr++ = strcpy( dst, "WINE" );
1473 strcat( dst, p );
1475 else
1477 *envptr++ = strcpy( dst, p );
1479 dst += strlen(dst) + 1;
1481 *envptr = 0;
1483 HeapFree( GetProcessHeap(), 0, env );
1484 return envp;
1488 /***********************************************************************
1489 * fork_and_exec
1491 * Fork and exec a new Unix binary, checking for errors.
1493 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1494 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1496 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1497 int pid, err;
1498 char **argv, **envp;
1500 if (!env) env = GetEnvironmentStringsW();
1502 #ifdef HAVE_PIPE2
1503 if (pipe2( fd, O_CLOEXEC ) == -1)
1504 #endif
1506 if (pipe(fd) == -1)
1508 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1509 return -1;
1511 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1512 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1515 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1517 HANDLE hstdin, hstdout, hstderr;
1519 if (startup->dwFlags & STARTF_USESTDHANDLES)
1521 hstdin = startup->hStdInput;
1522 hstdout = startup->hStdOutput;
1523 hstderr = startup->hStdError;
1525 else
1527 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1528 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1529 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1532 if (is_console_handle( hstdin ))
1533 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1534 if (is_console_handle( hstdout ))
1535 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1536 if (is_console_handle( hstderr ))
1537 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1538 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1539 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1540 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1543 argv = build_argv( cmdline, 0 );
1544 envp = build_envp( env );
1546 if (!(pid = fork())) /* child */
1548 if (!(pid = fork())) /* grandchild */
1550 close( fd[0] );
1552 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1554 int nullfd = open( "/dev/null", O_RDWR );
1555 setsid();
1556 /* close stdin and stdout */
1557 if (nullfd != -1)
1559 dup2( nullfd, 0 );
1560 dup2( nullfd, 1 );
1561 close( nullfd );
1564 else
1566 if (stdin_fd != -1)
1568 dup2( stdin_fd, 0 );
1569 close( stdin_fd );
1571 if (stdout_fd != -1)
1573 dup2( stdout_fd, 1 );
1574 close( stdout_fd );
1576 if (stderr_fd != -1)
1578 dup2( stderr_fd, 2 );
1579 close( stderr_fd );
1583 /* Reset signals that we previously set to SIG_IGN */
1584 signal( SIGPIPE, SIG_DFL );
1586 if (newdir) chdir(newdir);
1588 if (argv && envp) execve( filename, argv, envp );
1591 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1593 err = errno;
1594 write( fd[1], &err, sizeof(err) );
1595 _exit(1);
1598 _exit(0); /* child if fork succeeded */
1600 HeapFree( GetProcessHeap(), 0, argv );
1601 HeapFree( GetProcessHeap(), 0, envp );
1602 if (stdin_fd != -1) close( stdin_fd );
1603 if (stdout_fd != -1) close( stdout_fd );
1604 if (stderr_fd != -1) close( stderr_fd );
1605 close( fd[1] );
1606 if (pid != -1)
1608 /* reap child */
1609 do {
1610 err = waitpid(pid, NULL, 0);
1611 } while (err < 0 && errno == EINTR);
1613 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1615 errno = err;
1616 pid = -1;
1619 if (pid == -1) FILE_SetDosError();
1620 close( fd[0] );
1621 return pid;
1625 static inline DWORD append_string( void **ptr, const WCHAR *str )
1627 DWORD len = strlenW( str );
1628 memcpy( *ptr, str, len * sizeof(WCHAR) );
1629 *ptr = (WCHAR *)*ptr + len;
1630 return len * sizeof(WCHAR);
1633 /***********************************************************************
1634 * create_startup_info
1636 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1637 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1638 const STARTUPINFOW *startup, DWORD *info_size )
1640 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1641 const WCHAR *title;
1642 startup_info_t *info;
1643 DWORD size;
1644 void *ptr;
1645 UNICODE_STRING newdir;
1646 WCHAR imagepath[MAX_PATH];
1647 HANDLE hstdin, hstdout, hstderr;
1649 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1650 lstrcpynW( imagepath, filename, MAX_PATH );
1651 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1652 lstrcpynW( imagepath, filename, MAX_PATH );
1654 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1656 newdir.Buffer = NULL;
1657 if (cur_dir)
1659 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1660 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1661 else
1662 cur_dir = NULL;
1664 if (!cur_dir)
1666 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1667 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1668 else
1669 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1671 title = startup->lpTitle ? startup->lpTitle : imagepath;
1673 size = sizeof(*info);
1674 size += strlenW( cur_dir ) * sizeof(WCHAR);
1675 size += cur_params->DllPath.Length;
1676 size += strlenW( imagepath ) * sizeof(WCHAR);
1677 size += strlenW( cmdline ) * sizeof(WCHAR);
1678 size += strlenW( title ) * sizeof(WCHAR);
1679 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1680 /* FIXME: shellinfo */
1681 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1682 size = (size + 1) & ~1;
1683 *info_size = size;
1685 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1687 info->console_flags = cur_params->ConsoleFlags;
1688 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1689 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1691 if (startup->dwFlags & STARTF_USESTDHANDLES)
1693 hstdin = startup->hStdInput;
1694 hstdout = startup->hStdOutput;
1695 hstderr = startup->hStdError;
1697 else if (flags & DETACHED_PROCESS)
1699 hstdin = INVALID_HANDLE_VALUE;
1700 hstdout = INVALID_HANDLE_VALUE;
1701 hstderr = INVALID_HANDLE_VALUE;
1703 else
1705 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1706 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1707 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1709 info->hstdin = wine_server_obj_handle( hstdin );
1710 info->hstdout = wine_server_obj_handle( hstdout );
1711 info->hstderr = wine_server_obj_handle( hstderr );
1712 if ((flags & CREATE_NEW_CONSOLE) != 0)
1714 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1715 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1716 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1717 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1719 else
1721 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1722 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1723 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1726 info->x = startup->dwX;
1727 info->y = startup->dwY;
1728 info->xsize = startup->dwXSize;
1729 info->ysize = startup->dwYSize;
1730 info->xchars = startup->dwXCountChars;
1731 info->ychars = startup->dwYCountChars;
1732 info->attribute = startup->dwFillAttribute;
1733 info->flags = startup->dwFlags;
1734 info->show = startup->wShowWindow;
1736 ptr = info + 1;
1737 info->curdir_len = append_string( &ptr, cur_dir );
1738 info->dllpath_len = cur_params->DllPath.Length;
1739 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1740 ptr = (char *)ptr + cur_params->DllPath.Length;
1741 info->imagepath_len = append_string( &ptr, imagepath );
1742 info->cmdline_len = append_string( &ptr, cmdline );
1743 info->title_len = append_string( &ptr, title );
1744 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1745 if (startup->lpReserved2 && startup->cbReserved2)
1747 info->runtime_len = startup->cbReserved2;
1748 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1751 done:
1752 RtlFreeUnicodeString( &newdir );
1753 return info;
1756 /***********************************************************************
1757 * get_alternate_loader
1759 * Get the name of the alternate (32 or 64 bit) Wine loader.
1761 static const char *get_alternate_loader( char **ret_env )
1763 char *env;
1764 const char *loader = NULL;
1765 const char *loader_env = getenv( "WINELOADER" );
1767 *ret_env = NULL;
1769 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1771 if (loader_env)
1773 int len = strlen( loader_env );
1774 if (!is_win64)
1776 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1777 strcpy( env, "WINELOADER=" );
1778 strcat( env, loader_env );
1779 strcat( env, "64" );
1781 else
1783 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1784 strcpy( env, "WINELOADER=" );
1785 strcat( env, loader_env );
1786 len += sizeof("WINELOADER=") - 1;
1787 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1789 if (!loader)
1791 if ((loader = strrchr( env, '/' ))) loader++;
1792 else loader = env;
1794 *ret_env = env;
1796 if (!loader) loader = is_win64 ? "wine" : "wine64";
1797 return loader;
1800 #ifdef __APPLE__
1801 /***********************************************************************
1802 * terminate_main_thread
1804 * On some versions of Mac OS X, the execve system call fails with
1805 * ENOTSUP if the process has multiple threads. Wine is always multi-
1806 * threaded on Mac OS X because it specifically reserves the main thread
1807 * for use by the system frameworks (see apple_main_thread() in
1808 * libs/wine/loader.c). So, when we need to exec without first forking,
1809 * we need to terminate the main thread first. We do this by installing
1810 * a custom run loop source onto the main run loop and signaling it.
1811 * The source's "perform" callback is pthread_exit and it will be
1812 * executed on the main thread, terminating it.
1814 * Returns TRUE if there's still hope the main thread has terminated or
1815 * will soon. Return FALSE if we've given up.
1817 static BOOL terminate_main_thread(void)
1819 static int delayms;
1821 if (!delayms)
1823 CFRunLoopSourceContext source_context = { 0 };
1824 CFRunLoopSourceRef source;
1826 source_context.perform = pthread_exit;
1827 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1828 return FALSE;
1830 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1831 CFRunLoopSourceSignal( source );
1832 CFRunLoopWakeUp( CFRunLoopGetMain() );
1833 CFRelease( source );
1835 delayms = 20;
1838 if (delayms > 1000)
1839 return FALSE;
1841 usleep(delayms * 1000);
1842 delayms *= 2;
1844 return TRUE;
1846 #endif
1848 /***********************************************************************
1849 * get_process_cpu
1851 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1853 switch (binary_info->arch)
1855 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1856 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1857 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1858 case IMAGE_FILE_MACHINE_ARM:
1859 case IMAGE_FILE_MACHINE_THUMB:
1860 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1861 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1863 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1864 return -1;
1867 /***********************************************************************
1868 * exec_loader
1870 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1871 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1872 const struct binary_info *binary_info, int exec_only )
1874 pid_t pid;
1875 char *wineloader = NULL;
1876 const char *loader = NULL;
1877 char **argv;
1879 argv = build_argv( cmd_line, 1 );
1881 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1882 loader = get_alternate_loader( &wineloader );
1884 if (exec_only || !(pid = fork())) /* child */
1886 if (exec_only || !(pid = fork())) /* grandchild */
1888 char preloader_reserve[64], socket_env[64];
1890 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1892 int fd = open( "/dev/null", O_RDWR );
1893 setsid();
1894 /* close stdin and stdout */
1895 if (fd != -1)
1897 dup2( fd, 0 );
1898 dup2( fd, 1 );
1899 close( fd );
1902 else
1904 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1905 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1908 if (stdin_fd != -1) close( stdin_fd );
1909 if (stdout_fd != -1) close( stdout_fd );
1911 /* Reset signals that we previously set to SIG_IGN */
1912 signal( SIGPIPE, SIG_DFL );
1914 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1915 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
1916 (ULONG)(binary_info->res_start >> 32), (ULONG)binary_info->res_start,
1917 (ULONG)(binary_info->res_end >> 32), (ULONG)binary_info->res_end );
1919 putenv( preloader_reserve );
1920 putenv( socket_env );
1921 if (winedebug) putenv( winedebug );
1922 if (wineloader) putenv( wineloader );
1923 if (unixdir) chdir(unixdir);
1925 if (argv)
1929 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1931 #ifdef __APPLE__
1932 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1933 #else
1934 while (0);
1935 #endif
1937 _exit(1);
1940 _exit(pid == -1);
1943 if (pid != -1)
1945 /* reap child */
1946 pid_t wret;
1947 do {
1948 wret = waitpid(pid, NULL, 0);
1949 } while (wret < 0 && errno == EINTR);
1952 HeapFree( GetProcessHeap(), 0, wineloader );
1953 HeapFree( GetProcessHeap(), 0, argv );
1954 return pid;
1957 /***********************************************************************
1958 * create_process
1960 * Create a new process. If hFile is a valid handle we have an exe
1961 * file, otherwise it is a Winelib app.
1963 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1964 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1965 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1966 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1967 const struct binary_info *binary_info, int exec_only )
1969 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1970 NTSTATUS status;
1971 BOOL success = FALSE;
1972 HANDLE process_info;
1973 WCHAR *env_end;
1974 char *winedebug = NULL;
1975 startup_info_t *startup_info;
1976 DWORD startup_info_size;
1977 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1978 pid_t pid;
1979 int err, cpu;
1981 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
1983 SetLastError( ERROR_BAD_EXE_FORMAT );
1984 return FALSE;
1987 /* create the socket for the new process */
1989 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1991 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1992 return FALSE;
1994 #ifdef SO_PASSCRED
1995 else
1997 int enable = 1;
1998 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2000 #endif
2002 if (exec_only) /* things are much simpler in this case */
2004 wine_server_send_fd( socketfd[1] );
2005 close( socketfd[1] );
2006 SERVER_START_REQ( new_process )
2008 req->create_flags = flags;
2009 req->socket_fd = socketfd[1];
2010 req->exe_file = wine_server_obj_handle( hFile );
2011 req->cpu = cpu;
2012 status = wine_server_call( req );
2014 SERVER_END_REQ;
2016 switch (status)
2018 case STATUS_INVALID_IMAGE_WIN_64:
2019 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2020 break;
2021 case STATUS_INVALID_IMAGE_FORMAT:
2022 ERR( "%s not supported on this installation (%s binary)\n",
2023 debugstr_w(filename), cpu_names[cpu] );
2024 break;
2025 case STATUS_SUCCESS:
2026 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2027 winedebug, binary_info, TRUE );
2029 close( socketfd[0] );
2030 SetLastError( RtlNtStatusToDosError( status ));
2031 return FALSE;
2034 RtlAcquirePebLock();
2036 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2037 &startup_info_size )))
2039 RtlReleasePebLock();
2040 close( socketfd[0] );
2041 close( socketfd[1] );
2042 return FALSE;
2044 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2045 env_end = env;
2046 while (*env_end)
2048 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2049 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2051 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2052 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2053 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2055 env_end += strlenW(env_end) + 1;
2057 env_end++;
2059 wine_server_send_fd( socketfd[1] );
2060 close( socketfd[1] );
2062 /* create the process on the server side */
2064 SERVER_START_REQ( new_process )
2066 req->inherit_all = inherit;
2067 req->create_flags = flags;
2068 req->socket_fd = socketfd[1];
2069 req->exe_file = wine_server_obj_handle( hFile );
2070 req->process_access = PROCESS_ALL_ACCESS;
2071 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2072 req->thread_access = THREAD_ALL_ACCESS;
2073 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2074 req->cpu = cpu;
2075 req->info_size = startup_info_size;
2077 wine_server_add_data( req, startup_info, startup_info_size );
2078 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2079 if (!(status = wine_server_call( req )))
2081 info->dwProcessId = (DWORD)reply->pid;
2082 info->dwThreadId = (DWORD)reply->tid;
2083 info->hProcess = wine_server_ptr_handle( reply->phandle );
2084 info->hThread = wine_server_ptr_handle( reply->thandle );
2086 process_info = wine_server_ptr_handle( reply->info );
2088 SERVER_END_REQ;
2090 RtlReleasePebLock();
2091 if (status)
2093 switch (status)
2095 case STATUS_INVALID_IMAGE_WIN_64:
2096 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2097 break;
2098 case STATUS_INVALID_IMAGE_FORMAT:
2099 ERR( "%s not supported on this installation (%s binary)\n",
2100 debugstr_w(filename), cpu_names[cpu] );
2101 break;
2103 close( socketfd[0] );
2104 HeapFree( GetProcessHeap(), 0, startup_info );
2105 HeapFree( GetProcessHeap(), 0, winedebug );
2106 SetLastError( RtlNtStatusToDosError( status ));
2107 return FALSE;
2110 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2112 if (startup_info->hstdin)
2113 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2114 FILE_READ_DATA, &stdin_fd, NULL );
2115 if (startup_info->hstdout)
2116 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2117 FILE_WRITE_DATA, &stdout_fd, NULL );
2119 HeapFree( GetProcessHeap(), 0, startup_info );
2121 /* create the child process */
2123 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2124 winedebug, binary_info, FALSE );
2126 if (stdin_fd != -1) close( stdin_fd );
2127 if (stdout_fd != -1) close( stdout_fd );
2128 close( socketfd[0] );
2129 HeapFree( GetProcessHeap(), 0, winedebug );
2130 if (pid == -1)
2132 FILE_SetDosError();
2133 goto error;
2136 /* wait for the new process info to be ready */
2138 WaitForSingleObject( process_info, INFINITE );
2139 SERVER_START_REQ( get_new_process_info )
2141 req->info = wine_server_obj_handle( process_info );
2142 wine_server_call( req );
2143 success = reply->success;
2144 err = reply->exit_code;
2146 SERVER_END_REQ;
2148 if (!success)
2150 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2151 goto error;
2153 CloseHandle( process_info );
2154 return success;
2156 error:
2157 CloseHandle( process_info );
2158 CloseHandle( info->hProcess );
2159 CloseHandle( info->hThread );
2160 info->hProcess = info->hThread = 0;
2161 info->dwProcessId = info->dwThreadId = 0;
2162 return FALSE;
2166 /***********************************************************************
2167 * create_vdm_process
2169 * Create a new VDM process for a 16-bit or DOS application.
2171 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2172 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2173 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2174 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2175 const struct binary_info *binary_info, int exec_only )
2177 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2179 BOOL ret;
2180 WCHAR buffer[MAX_PATH];
2181 LPWSTR new_cmd_line;
2183 if (!(ret = GetFullPathNameW(filename, MAX_PATH, buffer, NULL)))
2184 return FALSE;
2186 new_cmd_line = HeapAlloc(GetProcessHeap(), 0,
2187 (strlenW(buffer) + strlenW(cmd_line) + 30) * sizeof(WCHAR));
2189 if (!new_cmd_line)
2191 SetLastError( ERROR_OUTOFMEMORY );
2192 return FALSE;
2194 sprintfW(new_cmd_line, argsW, winevdmW, buffer, cmd_line);
2195 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2196 flags, startup, info, unixdir, binary_info, exec_only );
2197 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2198 return ret;
2202 /***********************************************************************
2203 * create_cmd_process
2205 * Create a new cmd shell process for a .BAT file.
2207 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2208 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2209 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2210 LPPROCESS_INFORMATION info )
2213 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2214 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2215 WCHAR comspec[MAX_PATH];
2216 WCHAR *newcmdline;
2217 BOOL ret;
2219 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2220 return FALSE;
2221 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2222 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2223 return FALSE;
2225 strcpyW( newcmdline, comspec );
2226 strcatW( newcmdline, slashcW );
2227 strcatW( newcmdline, cmd_line );
2228 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2229 flags, env, cur_dir, startup, info );
2230 HeapFree( GetProcessHeap(), 0, newcmdline );
2231 return ret;
2235 /*************************************************************************
2236 * get_file_name
2238 * Helper for CreateProcess: retrieve the file name to load from the
2239 * app name and command line. Store the file name in buffer, and
2240 * return a possibly modified command line.
2241 * Also returns a handle to the opened file if it's a Windows binary.
2243 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2244 int buflen, HANDLE *handle, struct binary_info *binary_info )
2246 static const WCHAR quotesW[] = {'"','%','s','"',0};
2248 WCHAR *name, *pos, *first_space, *ret = NULL;
2249 const WCHAR *p;
2251 /* if we have an app name, everything is easy */
2253 if (appname)
2255 /* use the unmodified app name as file name */
2256 lstrcpynW( buffer, appname, buflen );
2257 *handle = open_exe_file( buffer, binary_info );
2258 if (!(ret = cmdline) || !cmdline[0])
2260 /* no command-line, create one */
2261 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2262 sprintfW( ret, quotesW, appname );
2264 return ret;
2267 /* first check for a quoted file name */
2269 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2271 int len = p - cmdline - 1;
2272 /* extract the quoted portion as file name */
2273 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2274 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2275 name[len] = 0;
2277 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2278 ret = cmdline; /* no change necessary */
2279 goto done;
2282 /* now try the command-line word by word */
2284 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2285 return NULL;
2286 pos = name;
2287 p = cmdline;
2288 first_space = NULL;
2290 for (;;)
2292 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2293 *pos = 0;
2294 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2296 ret = cmdline;
2297 break;
2299 if (!first_space) first_space = pos;
2300 if (!(*pos++ = *p++)) break;
2303 if (!ret)
2305 SetLastError( ERROR_FILE_NOT_FOUND );
2307 else if (first_space) /* build a new command-line with quotes */
2309 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2310 goto done;
2311 sprintfW( ret, quotesW, name );
2312 strcatW( ret, p );
2315 done:
2316 HeapFree( GetProcessHeap(), 0, name );
2317 return ret;
2321 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2322 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2323 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2324 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2325 LPPROCESS_INFORMATION info )
2327 BOOL retv = FALSE;
2328 HANDLE hFile = 0;
2329 char *unixdir = NULL;
2330 WCHAR name[MAX_PATH];
2331 WCHAR *tidy_cmdline, *p, *envW = env;
2332 struct binary_info binary_info;
2334 /* Process the AppName and/or CmdLine to get module name and path */
2336 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2338 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2339 &hFile, &binary_info )))
2340 return FALSE;
2341 if (hFile == INVALID_HANDLE_VALUE) goto done;
2343 /* Warn if unsupported features are used */
2345 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2346 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2347 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2348 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2349 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2351 if (cur_dir)
2353 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2355 SetLastError(ERROR_DIRECTORY);
2356 goto done;
2359 else
2361 WCHAR buf[MAX_PATH];
2362 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2365 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2367 char *e = env;
2368 DWORD lenW;
2370 while (*e) e += strlen(e) + 1;
2371 e++; /* final null */
2372 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2373 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2374 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2375 flags |= CREATE_UNICODE_ENVIRONMENT;
2378 info->hThread = info->hProcess = 0;
2379 info->dwProcessId = info->dwThreadId = 0;
2381 if (binary_info.flags & BINARY_FLAG_DLL)
2383 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2384 SetLastError( ERROR_BAD_EXE_FORMAT );
2386 else switch (binary_info.type)
2388 case BINARY_PE:
2389 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x%s)\n",
2390 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2391 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2392 binary_info.arch, (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2393 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2394 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2395 break;
2396 case BINARY_OS216:
2397 case BINARY_WIN16:
2398 case BINARY_DOS:
2399 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2400 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2401 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2402 break;
2403 case BINARY_UNIX_LIB:
2404 TRACE( "starting %s as %d-bit Winelib app\n",
2405 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2406 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2407 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2408 break;
2409 case BINARY_UNKNOWN:
2410 /* check for .com or .bat extension */
2411 if ((p = strrchrW( name, '.' )))
2413 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2415 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2416 binary_info.type = BINARY_DOS;
2417 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2418 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2419 inherit, flags, startup_info, info, unixdir,
2420 &binary_info, FALSE );
2421 break;
2423 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2425 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2426 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2427 inherit, flags, startup_info, info );
2428 break;
2431 /* fall through */
2432 case BINARY_UNIX_EXE:
2434 /* unknown file, try as unix executable */
2435 char *unix_name;
2437 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2439 if ((unix_name = wine_get_unix_file_name( name )))
2441 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2442 HeapFree( GetProcessHeap(), 0, unix_name );
2445 break;
2447 if (hFile) CloseHandle( hFile );
2449 done:
2450 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2451 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2452 HeapFree( GetProcessHeap(), 0, unixdir );
2453 if (retv)
2454 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2455 return retv;
2459 /**********************************************************************
2460 * CreateProcessA (KERNEL32.@)
2462 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2463 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2464 DWORD flags, LPVOID env, LPCSTR cur_dir,
2465 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2467 BOOL ret = FALSE;
2468 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2469 UNICODE_STRING desktopW, titleW;
2470 STARTUPINFOW infoW;
2472 desktopW.Buffer = NULL;
2473 titleW.Buffer = NULL;
2474 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2475 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2476 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2478 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2479 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2481 memcpy( &infoW, startup_info, sizeof(infoW) );
2482 infoW.lpDesktop = desktopW.Buffer;
2483 infoW.lpTitle = titleW.Buffer;
2485 if (startup_info->lpReserved)
2486 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2487 debugstr_a(startup_info->lpReserved));
2489 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2490 inherit, flags, env, cur_dirW, &infoW, info );
2491 done:
2492 HeapFree( GetProcessHeap(), 0, app_nameW );
2493 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2494 HeapFree( GetProcessHeap(), 0, cur_dirW );
2495 RtlFreeUnicodeString( &desktopW );
2496 RtlFreeUnicodeString( &titleW );
2497 return ret;
2501 /**********************************************************************
2502 * CreateProcessW (KERNEL32.@)
2504 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2505 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2506 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2507 LPPROCESS_INFORMATION info )
2509 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2510 inherit, flags, env, cur_dir, startup_info, info);
2514 /**********************************************************************
2515 * exec_process
2517 static void exec_process( LPCWSTR name )
2519 HANDLE hFile;
2520 WCHAR *p;
2521 STARTUPINFOW startup_info;
2522 PROCESS_INFORMATION info;
2523 struct binary_info binary_info;
2525 hFile = open_exe_file( name, &binary_info );
2526 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2528 memset( &startup_info, 0, sizeof(startup_info) );
2529 startup_info.cb = sizeof(startup_info);
2531 /* Determine executable type */
2533 if (binary_info.flags & BINARY_FLAG_DLL)
2535 CloseHandle( hFile );
2536 return;
2539 switch (binary_info.type)
2541 case BINARY_PE:
2542 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x)\n",
2543 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2544 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2545 binary_info.arch );
2546 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2547 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2548 break;
2549 case BINARY_UNIX_LIB:
2550 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2551 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2552 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2553 break;
2554 case BINARY_UNKNOWN:
2555 /* check for .com or .pif extension */
2556 if (!(p = strrchrW( name, '.' ))) break;
2557 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2558 binary_info.type = BINARY_DOS;
2559 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2560 /* fall through */
2561 case BINARY_OS216:
2562 case BINARY_WIN16:
2563 case BINARY_DOS:
2564 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2565 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2566 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2567 break;
2568 default:
2569 break;
2571 CloseHandle( hFile );
2575 /***********************************************************************
2576 * wait_input_idle
2578 * Wrapper to call WaitForInputIdle USER function
2580 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2582 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2584 HMODULE mod = GetModuleHandleA( "user32.dll" );
2585 if (mod)
2587 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2588 if (ptr) return ptr( process, timeout );
2590 return 0;
2594 /***********************************************************************
2595 * WinExec (KERNEL32.@)
2597 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2599 PROCESS_INFORMATION info;
2600 STARTUPINFOA startup;
2601 char *cmdline;
2602 UINT ret;
2604 memset( &startup, 0, sizeof(startup) );
2605 startup.cb = sizeof(startup);
2606 startup.dwFlags = STARTF_USESHOWWINDOW;
2607 startup.wShowWindow = nCmdShow;
2609 /* cmdline needs to be writable for CreateProcess */
2610 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2611 strcpy( cmdline, lpCmdLine );
2613 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2614 0, NULL, NULL, &startup, &info ))
2616 /* Give 30 seconds to the app to come up */
2617 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2618 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2619 ret = 33;
2620 /* Close off the handles */
2621 CloseHandle( info.hThread );
2622 CloseHandle( info.hProcess );
2624 else if ((ret = GetLastError()) >= 32)
2626 FIXME("Strange error set by CreateProcess: %d\n", ret );
2627 ret = 11;
2629 HeapFree( GetProcessHeap(), 0, cmdline );
2630 return ret;
2634 /**********************************************************************
2635 * LoadModule (KERNEL32.@)
2637 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2639 LOADPARMS32 *params = paramBlock;
2640 PROCESS_INFORMATION info;
2641 STARTUPINFOA startup;
2642 DWORD ret;
2643 LPSTR cmdline, p;
2644 char filename[MAX_PATH];
2645 BYTE len;
2647 if (!name) return ERROR_FILE_NOT_FOUND;
2649 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2650 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2651 return GetLastError();
2653 len = (BYTE)params->lpCmdLine[0];
2654 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2655 return ERROR_NOT_ENOUGH_MEMORY;
2657 strcpy( cmdline, filename );
2658 p = cmdline + strlen(cmdline);
2659 *p++ = ' ';
2660 memcpy( p, params->lpCmdLine + 1, len );
2661 p[len] = 0;
2663 memset( &startup, 0, sizeof(startup) );
2664 startup.cb = sizeof(startup);
2665 if (params->lpCmdShow)
2667 startup.dwFlags = STARTF_USESHOWWINDOW;
2668 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2671 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2672 params->lpEnvAddress, NULL, &startup, &info ))
2674 /* Give 30 seconds to the app to come up */
2675 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2676 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2677 ret = 33;
2678 /* Close off the handles */
2679 CloseHandle( info.hThread );
2680 CloseHandle( info.hProcess );
2682 else if ((ret = GetLastError()) >= 32)
2684 FIXME("Strange error set by CreateProcess: %u\n", ret );
2685 ret = 11;
2688 HeapFree( GetProcessHeap(), 0, cmdline );
2689 return ret;
2693 /******************************************************************************
2694 * TerminateProcess (KERNEL32.@)
2696 * Terminates a process.
2698 * PARAMS
2699 * handle [I] Process to terminate.
2700 * exit_code [I] Exit code.
2702 * RETURNS
2703 * Success: TRUE.
2704 * Failure: FALSE, check GetLastError().
2706 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2708 NTSTATUS status;
2710 if (!handle)
2712 SetLastError( ERROR_INVALID_HANDLE );
2713 return FALSE;
2716 status = NtTerminateProcess( handle, exit_code );
2717 if (status) SetLastError( RtlNtStatusToDosError(status) );
2718 return !status;
2721 /***********************************************************************
2722 * ExitProcess (KERNEL32.@)
2724 * Exits the current process.
2726 * PARAMS
2727 * status [I] Status code to exit with.
2729 * RETURNS
2730 * Nothing.
2732 #ifdef __i386__
2733 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2734 "pushl %ebp\n\t"
2735 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2736 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2737 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2738 "pushl 8(%ebp)\n\t"
2739 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2740 "leave\n\t"
2741 "ret $4" )
2742 #else
2744 void WINAPI ExitProcess( DWORD status )
2746 RtlExitUserProcess( status );
2749 #endif
2751 /***********************************************************************
2752 * GetExitCodeProcess [KERNEL32.@]
2754 * Gets termination status of specified process.
2756 * PARAMS
2757 * hProcess [in] Handle to the process.
2758 * lpExitCode [out] Address to receive termination status.
2760 * RETURNS
2761 * Success: TRUE
2762 * Failure: FALSE
2764 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2766 NTSTATUS status;
2767 PROCESS_BASIC_INFORMATION pbi;
2769 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2770 sizeof(pbi), NULL);
2771 if (status == STATUS_SUCCESS)
2773 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2774 return TRUE;
2776 SetLastError( RtlNtStatusToDosError(status) );
2777 return FALSE;
2781 /***********************************************************************
2782 * SetErrorMode (KERNEL32.@)
2784 UINT WINAPI SetErrorMode( UINT mode )
2786 UINT old;
2788 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2789 &old, sizeof(old), NULL );
2790 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2791 &mode, sizeof(mode) );
2792 return old;
2795 /***********************************************************************
2796 * GetErrorMode (KERNEL32.@)
2798 UINT WINAPI GetErrorMode( void )
2800 UINT mode;
2802 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2803 &mode, sizeof(mode), NULL );
2804 return mode;
2807 /**********************************************************************
2808 * TlsAlloc [KERNEL32.@]
2810 * Allocates a thread local storage index.
2812 * RETURNS
2813 * Success: TLS index.
2814 * Failure: 0xFFFFFFFF
2816 DWORD WINAPI TlsAlloc( void )
2818 DWORD index;
2819 PEB * const peb = NtCurrentTeb()->Peb;
2821 RtlAcquirePebLock();
2822 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2823 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2824 else
2826 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2827 if (index != ~0U)
2829 if (!NtCurrentTeb()->TlsExpansionSlots &&
2830 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2831 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2833 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2834 index = ~0U;
2835 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2837 else
2839 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2840 index += TLS_MINIMUM_AVAILABLE;
2843 else SetLastError( ERROR_NO_MORE_ITEMS );
2845 RtlReleasePebLock();
2846 return index;
2850 /**********************************************************************
2851 * TlsFree [KERNEL32.@]
2853 * Releases a thread local storage index, making it available for reuse.
2855 * PARAMS
2856 * index [in] TLS index to free.
2858 * RETURNS
2859 * Success: TRUE
2860 * Failure: FALSE
2862 BOOL WINAPI TlsFree( DWORD index )
2864 BOOL ret;
2866 RtlAcquirePebLock();
2867 if (index >= TLS_MINIMUM_AVAILABLE)
2869 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2870 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2872 else
2874 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2875 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2877 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2878 else SetLastError( ERROR_INVALID_PARAMETER );
2879 RtlReleasePebLock();
2880 return ret;
2884 /**********************************************************************
2885 * TlsGetValue [KERNEL32.@]
2887 * Gets value in a thread's TLS slot.
2889 * PARAMS
2890 * index [in] TLS index to retrieve value for.
2892 * RETURNS
2893 * Success: Value stored in calling thread's TLS slot for index.
2894 * Failure: 0 and GetLastError() returns NO_ERROR.
2896 LPVOID WINAPI TlsGetValue( DWORD index )
2898 LPVOID ret;
2900 if (index < TLS_MINIMUM_AVAILABLE)
2902 ret = NtCurrentTeb()->TlsSlots[index];
2904 else
2906 index -= TLS_MINIMUM_AVAILABLE;
2907 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2909 SetLastError( ERROR_INVALID_PARAMETER );
2910 return NULL;
2912 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2913 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2915 SetLastError( ERROR_SUCCESS );
2916 return ret;
2920 /**********************************************************************
2921 * TlsSetValue [KERNEL32.@]
2923 * Stores a value in the thread's TLS slot.
2925 * PARAMS
2926 * index [in] TLS index to set value for.
2927 * value [in] Value to be stored.
2929 * RETURNS
2930 * Success: TRUE
2931 * Failure: FALSE
2933 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2935 if (index < TLS_MINIMUM_AVAILABLE)
2937 NtCurrentTeb()->TlsSlots[index] = value;
2939 else
2941 index -= TLS_MINIMUM_AVAILABLE;
2942 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2944 SetLastError( ERROR_INVALID_PARAMETER );
2945 return FALSE;
2947 if (!NtCurrentTeb()->TlsExpansionSlots &&
2948 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2949 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2951 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2952 return FALSE;
2954 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2956 return TRUE;
2960 /***********************************************************************
2961 * GetProcessFlags (KERNEL32.@)
2963 DWORD WINAPI GetProcessFlags( DWORD processid )
2965 IMAGE_NT_HEADERS *nt;
2966 DWORD flags = 0;
2968 if (processid && processid != GetCurrentProcessId()) return 0;
2970 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2972 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2973 flags |= PDB32_CONSOLE_PROC;
2975 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2976 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2977 return flags;
2981 /*********************************************************************
2982 * OpenProcess (KERNEL32.@)
2984 * Opens a handle to a process.
2986 * PARAMS
2987 * access [I] Desired access rights assigned to the returned handle.
2988 * inherit [I] Determines whether or not child processes will inherit the handle.
2989 * id [I] Process identifier of the process to get a handle to.
2991 * RETURNS
2992 * Success: Valid handle to the specified process.
2993 * Failure: NULL, check GetLastError().
2995 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2997 NTSTATUS status;
2998 HANDLE handle;
2999 OBJECT_ATTRIBUTES attr;
3000 CLIENT_ID cid;
3002 cid.UniqueProcess = ULongToHandle(id);
3003 cid.UniqueThread = 0; /* FIXME ? */
3005 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3006 attr.RootDirectory = NULL;
3007 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3008 attr.SecurityDescriptor = NULL;
3009 attr.SecurityQualityOfService = NULL;
3010 attr.ObjectName = NULL;
3012 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3014 status = NtOpenProcess(&handle, access, &attr, &cid);
3015 if (status != STATUS_SUCCESS)
3017 SetLastError( RtlNtStatusToDosError(status) );
3018 return NULL;
3020 return handle;
3024 /*********************************************************************
3025 * GetProcessId (KERNEL32.@)
3027 * Gets the a unique identifier of a process.
3029 * PARAMS
3030 * hProcess [I] Handle to the process.
3032 * RETURNS
3033 * Success: TRUE.
3034 * Failure: FALSE, check GetLastError().
3036 * NOTES
3038 * The identifier is unique only on the machine and only until the process
3039 * exits (including system shutdown).
3041 DWORD WINAPI GetProcessId( HANDLE hProcess )
3043 NTSTATUS status;
3044 PROCESS_BASIC_INFORMATION pbi;
3046 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3047 sizeof(pbi), NULL);
3048 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3049 SetLastError( RtlNtStatusToDosError(status) );
3050 return 0;
3054 /*********************************************************************
3055 * CloseHandle (KERNEL32.@)
3057 * Closes a handle.
3059 * PARAMS
3060 * handle [I] Handle to close.
3062 * RETURNS
3063 * Success: TRUE.
3064 * Failure: FALSE, check GetLastError().
3066 BOOL WINAPI CloseHandle( HANDLE handle )
3068 NTSTATUS status;
3070 /* stdio handles need special treatment */
3071 if (handle == (HANDLE)STD_INPUT_HANDLE)
3072 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3073 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3074 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3075 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3076 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3078 if (is_console_handle(handle))
3079 return CloseConsoleHandle(handle);
3081 status = NtClose( handle );
3082 if (status) SetLastError( RtlNtStatusToDosError(status) );
3083 return !status;
3087 /*********************************************************************
3088 * GetHandleInformation (KERNEL32.@)
3090 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3092 OBJECT_DATA_INFORMATION info;
3093 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3095 if (status) SetLastError( RtlNtStatusToDosError(status) );
3096 else if (flags)
3098 *flags = 0;
3099 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3100 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3102 return !status;
3106 /*********************************************************************
3107 * SetHandleInformation (KERNEL32.@)
3109 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3111 OBJECT_DATA_INFORMATION info;
3112 NTSTATUS status;
3114 /* if not setting both fields, retrieve current value first */
3115 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3116 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3118 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3120 SetLastError( RtlNtStatusToDosError(status) );
3121 return FALSE;
3124 if (mask & HANDLE_FLAG_INHERIT)
3125 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3126 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3127 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3129 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3130 if (status) SetLastError( RtlNtStatusToDosError(status) );
3131 return !status;
3135 /*********************************************************************
3136 * DuplicateHandle (KERNEL32.@)
3138 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3139 HANDLE dest_process, HANDLE *dest,
3140 DWORD access, BOOL inherit, DWORD options )
3142 NTSTATUS status;
3144 if (is_console_handle(source))
3146 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3147 if (source_process != dest_process ||
3148 source_process != GetCurrentProcess())
3150 SetLastError(ERROR_INVALID_PARAMETER);
3151 return FALSE;
3153 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3154 return (*dest != INVALID_HANDLE_VALUE);
3156 status = NtDuplicateObject( source_process, source, dest_process, dest,
3157 access, inherit ? OBJ_INHERIT : 0, options );
3158 if (status) SetLastError( RtlNtStatusToDosError(status) );
3159 return !status;
3163 /***********************************************************************
3164 * ConvertToGlobalHandle (KERNEL32.@)
3166 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3168 HANDLE ret = INVALID_HANDLE_VALUE;
3169 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3170 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3171 return ret;
3175 /***********************************************************************
3176 * SetHandleContext (KERNEL32.@)
3178 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3180 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3181 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3182 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3183 return FALSE;
3187 /***********************************************************************
3188 * GetHandleContext (KERNEL32.@)
3190 DWORD WINAPI GetHandleContext(HANDLE hnd)
3192 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3193 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3194 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3195 return 0;
3199 /***********************************************************************
3200 * CreateSocketHandle (KERNEL32.@)
3202 HANDLE WINAPI CreateSocketHandle(void)
3204 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3205 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3206 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3207 return INVALID_HANDLE_VALUE;
3211 /***********************************************************************
3212 * SetPriorityClass (KERNEL32.@)
3214 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3216 NTSTATUS status;
3217 PROCESS_PRIORITY_CLASS ppc;
3219 ppc.Foreground = FALSE;
3220 switch (priorityclass)
3222 case IDLE_PRIORITY_CLASS:
3223 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3224 case BELOW_NORMAL_PRIORITY_CLASS:
3225 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3226 case NORMAL_PRIORITY_CLASS:
3227 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3228 case ABOVE_NORMAL_PRIORITY_CLASS:
3229 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3230 case HIGH_PRIORITY_CLASS:
3231 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3232 case REALTIME_PRIORITY_CLASS:
3233 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3234 default:
3235 SetLastError(ERROR_INVALID_PARAMETER);
3236 return FALSE;
3239 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3240 &ppc, sizeof(ppc));
3242 if (status != STATUS_SUCCESS)
3244 SetLastError( RtlNtStatusToDosError(status) );
3245 return FALSE;
3247 return TRUE;
3251 /***********************************************************************
3252 * GetPriorityClass (KERNEL32.@)
3254 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3256 NTSTATUS status;
3257 PROCESS_BASIC_INFORMATION pbi;
3259 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3260 sizeof(pbi), NULL);
3261 if (status != STATUS_SUCCESS)
3263 SetLastError( RtlNtStatusToDosError(status) );
3264 return 0;
3266 switch (pbi.BasePriority)
3268 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3269 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3270 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3271 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3272 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3273 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3275 SetLastError( ERROR_INVALID_PARAMETER );
3276 return 0;
3280 /***********************************************************************
3281 * SetProcessAffinityMask (KERNEL32.@)
3283 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3285 NTSTATUS status;
3287 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3288 &affmask, sizeof(DWORD_PTR));
3289 if (status)
3291 SetLastError( RtlNtStatusToDosError(status) );
3292 return FALSE;
3294 return TRUE;
3298 /**********************************************************************
3299 * GetProcessAffinityMask (KERNEL32.@)
3301 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3303 NTSTATUS status = STATUS_SUCCESS;
3305 if (process_mask)
3307 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3308 process_mask, sizeof(*process_mask), NULL )))
3309 SetLastError( RtlNtStatusToDosError(status) );
3311 if (system_mask && status == STATUS_SUCCESS)
3313 SYSTEM_BASIC_INFORMATION info;
3315 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3316 SetLastError( RtlNtStatusToDosError(status) );
3317 else
3318 *system_mask = info.ActiveProcessorsAffinityMask;
3320 return !status;
3324 /***********************************************************************
3325 * GetProcessVersion (KERNEL32.@)
3327 DWORD WINAPI GetProcessVersion( DWORD pid )
3329 HANDLE process;
3330 NTSTATUS status;
3331 PROCESS_BASIC_INFORMATION pbi;
3332 SIZE_T count;
3333 PEB peb;
3334 IMAGE_DOS_HEADER dos;
3335 IMAGE_NT_HEADERS nt;
3336 DWORD ver = 0;
3338 if (!pid || pid == GetCurrentProcessId())
3340 IMAGE_NT_HEADERS *pnt;
3342 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3343 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3344 pnt->OptionalHeader.MinorSubsystemVersion);
3345 return 0;
3348 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3349 if (!process) return 0;
3351 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3352 if (status) goto err;
3354 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3355 if (status || count != sizeof(peb)) goto err;
3357 memset(&dos, 0, sizeof(dos));
3358 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3359 if (status || count != sizeof(dos)) goto err;
3360 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3362 memset(&nt, 0, sizeof(nt));
3363 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3364 if (status || count != sizeof(nt)) goto err;
3365 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3367 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3369 err:
3370 CloseHandle(process);
3372 if (status != STATUS_SUCCESS)
3373 SetLastError(RtlNtStatusToDosError(status));
3375 return ver;
3379 /***********************************************************************
3380 * SetProcessWorkingSetSize [KERNEL32.@]
3381 * Sets the min/max working set sizes for a specified process.
3383 * PARAMS
3384 * hProcess [I] Handle to the process of interest
3385 * minset [I] Specifies minimum working set size
3386 * maxset [I] Specifies maximum working set size
3388 * RETURNS
3389 * Success: TRUE
3390 * Failure: FALSE
3392 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3393 SIZE_T maxset)
3395 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3396 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3397 /* Trim the working set to zero */
3398 /* Swap the process out of physical RAM */
3400 return TRUE;
3403 /***********************************************************************
3404 * K32EmptyWorkingSet (KERNEL32.@)
3406 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3408 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3412 /***********************************************************************
3413 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3415 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3416 SIZE_T *maxset, DWORD *flags)
3418 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3419 /* 32 MB working set size */
3420 if (minset) *minset = 32*1024*1024;
3421 if (maxset) *maxset = 32*1024*1024;
3422 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3423 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3424 return TRUE;
3428 /***********************************************************************
3429 * GetProcessWorkingSetSize (KERNEL32.@)
3431 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3433 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3437 /***********************************************************************
3438 * SetProcessShutdownParameters (KERNEL32.@)
3440 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3442 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3443 shutdown_flags = flags;
3444 shutdown_priority = level;
3445 return TRUE;
3449 /***********************************************************************
3450 * GetProcessShutdownParameters (KERNEL32.@)
3453 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3455 *lpdwLevel = shutdown_priority;
3456 *lpdwFlags = shutdown_flags;
3457 return TRUE;
3461 /***********************************************************************
3462 * GetProcessPriorityBoost (KERNEL32.@)
3464 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3466 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3468 /* Report that no boost is present.. */
3469 *pDisablePriorityBoost = FALSE;
3471 return TRUE;
3474 /***********************************************************************
3475 * SetProcessPriorityBoost (KERNEL32.@)
3477 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3479 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3480 /* Say we can do it. I doubt the program will notice that we don't. */
3481 return TRUE;
3485 /***********************************************************************
3486 * ReadProcessMemory (KERNEL32.@)
3488 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3489 SIZE_T *bytes_read )
3491 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3492 if (status) SetLastError( RtlNtStatusToDosError(status) );
3493 return !status;
3497 /***********************************************************************
3498 * WriteProcessMemory (KERNEL32.@)
3500 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3501 SIZE_T *bytes_written )
3503 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3504 if (status) SetLastError( RtlNtStatusToDosError(status) );
3505 return !status;
3509 /****************************************************************************
3510 * FlushInstructionCache (KERNEL32.@)
3512 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3514 NTSTATUS status;
3515 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3516 if (status) SetLastError( RtlNtStatusToDosError(status) );
3517 return !status;
3521 /******************************************************************
3522 * GetProcessIoCounters (KERNEL32.@)
3524 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3526 NTSTATUS status;
3528 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3529 ioc, sizeof(*ioc), NULL);
3530 if (status) SetLastError( RtlNtStatusToDosError(status) );
3531 return !status;
3534 /******************************************************************
3535 * GetProcessHandleCount (KERNEL32.@)
3537 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3539 NTSTATUS status;
3541 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3542 cnt, sizeof(*cnt), NULL);
3543 if (status) SetLastError( RtlNtStatusToDosError(status) );
3544 return !status;
3547 /******************************************************************
3548 * QueryFullProcessImageNameA (KERNEL32.@)
3550 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3552 BOOL retval;
3553 DWORD pdwSizeW = *pdwSize;
3554 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3556 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3558 if(retval)
3559 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3560 lpExeName, *pdwSize, NULL, NULL));
3561 if(retval)
3562 *pdwSize = strlen(lpExeName);
3564 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3565 return retval;
3568 /******************************************************************
3569 * QueryFullProcessImageNameW (KERNEL32.@)
3571 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3573 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3574 UNICODE_STRING *dynamic_buffer = NULL;
3575 UNICODE_STRING *result = NULL;
3576 NTSTATUS status;
3577 DWORD needed;
3579 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3580 * is a DOS path and we depend on this. */
3581 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3582 sizeof(buffer) - sizeof(WCHAR), &needed);
3583 if (status == STATUS_INFO_LENGTH_MISMATCH)
3585 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3586 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3587 result = dynamic_buffer;
3589 else
3590 result = (PUNICODE_STRING)buffer;
3592 if (status) goto cleanup;
3594 if (dwFlags & PROCESS_NAME_NATIVE)
3596 WCHAR drive[3];
3597 WCHAR device[1024];
3598 DWORD ntlen, devlen;
3600 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3602 /* We cannot convert it to an NT device path so fail */
3603 status = STATUS_NO_SUCH_DEVICE;
3604 goto cleanup;
3607 /* Find this drive's NT device path */
3608 drive[0] = result->Buffer[0];
3609 drive[1] = ':';
3610 drive[2] = 0;
3611 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3613 status = STATUS_NO_SUCH_DEVICE;
3614 goto cleanup;
3617 devlen = lstrlenW(device);
3618 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3619 if (ntlen + 1 > *pdwSize)
3621 status = STATUS_BUFFER_TOO_SMALL;
3622 goto cleanup;
3624 *pdwSize = ntlen;
3626 memcpy(lpExeName, device, devlen * sizeof(*device));
3627 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3628 lpExeName[*pdwSize] = 0;
3629 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3631 else
3633 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3635 status = STATUS_BUFFER_TOO_SMALL;
3636 goto cleanup;
3639 *pdwSize = result->Length/sizeof(WCHAR);
3640 memcpy( lpExeName, result->Buffer, result->Length );
3641 lpExeName[*pdwSize] = 0;
3644 cleanup:
3645 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3646 if (status) SetLastError( RtlNtStatusToDosError(status) );
3647 return !status;
3650 /***********************************************************************
3651 * K32GetProcessImageFileNameA (KERNEL32.@)
3653 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3655 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3658 /***********************************************************************
3659 * K32GetProcessImageFileNameW (KERNEL32.@)
3661 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3663 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3666 /***********************************************************************
3667 * K32EnumProcesses (KERNEL32.@)
3669 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3671 SYSTEM_PROCESS_INFORMATION *spi;
3672 ULONG size = 0x4000;
3673 void *buf = NULL;
3674 NTSTATUS status;
3676 do {
3677 size *= 2;
3678 HeapFree(GetProcessHeap(), 0, buf);
3679 buf = HeapAlloc(GetProcessHeap(), 0, size);
3680 if (!buf)
3681 return FALSE;
3683 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3684 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3686 if (status != STATUS_SUCCESS)
3688 HeapFree(GetProcessHeap(), 0, buf);
3689 SetLastError(RtlNtStatusToDosError(status));
3690 return FALSE;
3693 spi = buf;
3695 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3697 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3698 *lpcbUsed += sizeof(DWORD);
3700 if (spi->NextEntryOffset == 0)
3701 break;
3703 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3706 HeapFree(GetProcessHeap(), 0, buf);
3707 return TRUE;
3710 /***********************************************************************
3711 * K32QueryWorkingSet (KERNEL32.@)
3713 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3715 NTSTATUS status;
3717 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3719 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3721 if (status)
3723 SetLastError( RtlNtStatusToDosError( status ) );
3724 return FALSE;
3726 return TRUE;
3729 /***********************************************************************
3730 * K32QueryWorkingSetEx (KERNEL32.@)
3732 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3734 NTSTATUS status;
3736 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3738 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3740 if (status)
3742 SetLastError( RtlNtStatusToDosError( status ) );
3743 return FALSE;
3745 return TRUE;
3748 /***********************************************************************
3749 * K32GetProcessMemoryInfo (KERNEL32.@)
3751 * Retrieve memory usage information for a given process
3754 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3755 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3757 NTSTATUS status;
3758 VM_COUNTERS vmc;
3760 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3762 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3763 return FALSE;
3766 status = NtQueryInformationProcess(process, ProcessVmCounters,
3767 &vmc, sizeof(vmc), NULL);
3769 if (status)
3771 SetLastError(RtlNtStatusToDosError(status));
3772 return FALSE;
3775 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3776 pmc->PageFaultCount = vmc.PageFaultCount;
3777 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3778 pmc->WorkingSetSize = vmc.WorkingSetSize;
3779 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3780 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3781 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3782 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3783 pmc->PagefileUsage = vmc.PagefileUsage;
3784 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3786 return TRUE;
3789 /***********************************************************************
3790 * ProcessIdToSessionId (KERNEL32.@)
3791 * This function is available on Terminal Server 4SP4 and Windows 2000
3793 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3795 if (procid != GetCurrentProcessId())
3796 FIXME("Unsupported for other processes.\n");
3798 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3799 return TRUE;
3803 /***********************************************************************
3804 * RegisterServiceProcess (KERNEL32.@)
3806 * A service process calls this function to ensure that it continues to run
3807 * even after a user logged off.
3809 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3811 /* I don't think that Wine needs to do anything in this function */
3812 return 1; /* success */
3816 /**********************************************************************
3817 * IsWow64Process (KERNEL32.@)
3819 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3821 ULONG_PTR pbi;
3822 NTSTATUS status;
3824 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3826 if (status != STATUS_SUCCESS)
3828 SetLastError( RtlNtStatusToDosError( status ) );
3829 return FALSE;
3831 *Wow64Process = (pbi != 0);
3832 return TRUE;
3836 /***********************************************************************
3837 * GetCurrentProcess (KERNEL32.@)
3839 * Get a handle to the current process.
3841 * PARAMS
3842 * None.
3844 * RETURNS
3845 * A handle representing the current process.
3847 #undef GetCurrentProcess
3848 HANDLE WINAPI GetCurrentProcess(void)
3850 return (HANDLE)~(ULONG_PTR)0;
3853 /***********************************************************************
3854 * GetLogicalProcessorInformation (KERNEL32.@)
3856 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3858 NTSTATUS status;
3860 TRACE("(%p,%p)\n", buffer, pBufLen);
3862 if(!pBufLen)
3864 SetLastError(ERROR_INVALID_PARAMETER);
3865 return FALSE;
3868 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3870 if (status == STATUS_INFO_LENGTH_MISMATCH)
3872 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3873 return FALSE;
3875 if (status != STATUS_SUCCESS)
3877 SetLastError( RtlNtStatusToDosError( status ) );
3878 return FALSE;
3880 return TRUE;
3883 /***********************************************************************
3884 * GetLogicalProcessorInformationEx (KERNEL32.@)
3886 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
3888 NTSTATUS status;
3890 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
3892 if (!len)
3894 SetLastError( ERROR_INVALID_PARAMETER );
3895 return FALSE;
3898 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
3899 buffer, *len, len );
3900 if (status == STATUS_INFO_LENGTH_MISMATCH)
3902 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3903 return FALSE;
3905 if (status != STATUS_SUCCESS)
3907 SetLastError( RtlNtStatusToDosError( status ) );
3908 return FALSE;
3910 return TRUE;
3913 /***********************************************************************
3914 * CmdBatNotification (KERNEL32.@)
3916 * Notifies the system that a batch file has started or finished.
3918 * PARAMS
3919 * bBatchRunning [I] TRUE if a batch file has started or
3920 * FALSE if a batch file has finished executing.
3922 * RETURNS
3923 * Unknown.
3925 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3927 FIXME("%d\n", bBatchRunning);
3928 return FALSE;
3932 /***********************************************************************
3933 * RegisterApplicationRestart (KERNEL32.@)
3935 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3937 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3939 return S_OK;
3942 /**********************************************************************
3943 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3945 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3947 static int once;
3948 if (!once++) FIXME("stub\n");
3949 /* Return current session id. */
3950 return NtCurrentTeb()->Peb->SessionId;
3953 /**********************************************************************
3954 * GetSystemDEPPolicy (KERNEL32.@)
3956 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3958 FIXME("stub\n");
3959 return OptIn;
3962 /**********************************************************************
3963 * SetProcessDEPPolicy (KERNEL32.@)
3965 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3967 FIXME("(%d): stub\n", newDEP);
3968 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3969 return FALSE;
3972 /**********************************************************************
3973 * ApplicationRecoveryFinished (KERNEL32.@)
3975 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3977 FIXME(": stub\n");
3978 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3981 /**********************************************************************
3982 * ApplicationRecoveryInProgress (KERNEL32.@)
3984 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3986 FIXME(":%p stub\n", canceled);
3987 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3988 return E_FAIL;
3991 /**********************************************************************
3992 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3994 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3996 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
3997 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3998 return E_FAIL;
4001 /**********************************************************************
4002 * GetNumaHighestNodeNumber (KERNEL32.@)
4004 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4006 *highestnode = 0;
4007 FIXME("(%p): semi-stub\n", highestnode);
4008 return TRUE;
4011 /**********************************************************************
4012 * GetNumaNodeProcessorMask (KERNEL32.@)
4014 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4016 FIXME("(%c %p): stub\n", node, mask);
4017 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4018 return FALSE;
4021 /**********************************************************************
4022 * GetNumaNodeProcessorMaskEx (KERNEL32.@)
4024 BOOL WINAPI GetNumaNodeProcessorMaskEx(USHORT node, PGROUP_AFFINITY mask)
4026 FIXME("(%hu %p): stub\n", node, mask);
4027 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4028 return FALSE;
4031 /**********************************************************************
4032 * GetNumaAvailableMemoryNode (KERNEL32.@)
4034 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4036 FIXME("(%c %p): stub\n", node, available_bytes);
4037 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4038 return FALSE;
4041 /***********************************************************************
4042 * GetNumaProcessorNode (KERNEL32.@)
4044 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4046 SYSTEM_INFO si;
4048 TRACE("(%d, %p)\n", processor, node);
4050 GetSystemInfo( &si );
4051 if (processor < si.dwNumberOfProcessors)
4053 *node = 0;
4054 return TRUE;
4057 *node = 0xFF;
4058 SetLastError(ERROR_INVALID_PARAMETER);
4059 return FALSE;
4062 /**********************************************************************
4063 * GetProcessDEPPolicy (KERNEL32.@)
4065 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4067 NTSTATUS status;
4068 ULONG dep_flags;
4070 TRACE("(%p %p %p)\n", process, flags, permanent);
4072 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4073 &dep_flags, sizeof(dep_flags), NULL );
4074 if (!status)
4077 if (flags)
4079 *flags = 0;
4080 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4081 *flags |= PROCESS_DEP_ENABLE;
4082 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4083 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4086 if (permanent)
4087 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4090 if (status) SetLastError( RtlNtStatusToDosError(status) );
4091 return !status;
4094 /**********************************************************************
4095 * FlushProcessWriteBuffers (KERNEL32.@)
4097 VOID WINAPI FlushProcessWriteBuffers(void)
4099 static int once = 0;
4101 if (!once++)
4102 FIXME(": stub\n");
4105 /***********************************************************************
4106 * UnregisterApplicationRestart (KERNEL32.@)
4108 HRESULT WINAPI UnregisterApplicationRestart(void)
4110 FIXME(": stub\n");
4111 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4112 return S_OK;
4115 /***********************************************************************
4116 * GetSystemFirmwareTable (KERNEL32.@)
4118 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4120 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4121 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4122 return 0;
4125 struct proc_thread_attr
4127 DWORD_PTR attr;
4128 SIZE_T size;
4129 void *value;
4132 struct _PROC_THREAD_ATTRIBUTE_LIST
4134 DWORD mask; /* bitmask of items in list */
4135 DWORD size; /* max number of items in list */
4136 DWORD count; /* number of items in list */
4137 DWORD pad;
4138 DWORD_PTR unk;
4139 struct proc_thread_attr attrs[1];
4142 /***********************************************************************
4143 * InitializeProcThreadAttributeList (KERNEL32.@)
4145 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4146 DWORD count, DWORD flags, SIZE_T *size)
4148 SIZE_T needed;
4149 BOOL ret = FALSE;
4151 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4153 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4154 if (list && *size >= needed)
4156 list->mask = 0;
4157 list->size = count;
4158 list->count = 0;
4159 list->unk = 0;
4160 ret = TRUE;
4162 else
4163 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4165 *size = needed;
4166 return ret;
4169 /***********************************************************************
4170 * UpdateProcThreadAttribute (KERNEL32.@)
4172 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4173 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4174 void *prev_ret, SIZE_T *size_ret)
4176 DWORD mask;
4177 struct proc_thread_attr *entry;
4179 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4181 if (list->count >= list->size)
4183 SetLastError(ERROR_GEN_FAILURE);
4184 return FALSE;
4187 switch (attr)
4189 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4190 if (size != sizeof(HANDLE))
4192 SetLastError(ERROR_BAD_LENGTH);
4193 return FALSE;
4195 break;
4197 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4198 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4200 SetLastError(ERROR_BAD_LENGTH);
4201 return FALSE;
4203 break;
4205 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4206 if (size != sizeof(PROCESSOR_NUMBER))
4208 SetLastError(ERROR_BAD_LENGTH);
4209 return FALSE;
4211 break;
4213 default:
4214 SetLastError(ERROR_NOT_SUPPORTED);
4215 return FALSE;
4218 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4220 if (list->mask & mask)
4222 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4223 return FALSE;
4226 list->mask |= mask;
4228 entry = list->attrs + list->count;
4229 entry->attr = attr;
4230 entry->size = size;
4231 entry->value = value;
4232 list->count++;
4234 return TRUE;
4237 /***********************************************************************
4238 * CreateUmsCompletionList (KERNEL32.@)
4240 BOOL WINAPI CreateUmsCompletionList(PUMS_COMPLETION_LIST *list)
4242 FIXME( "%p: stub\n", list );
4243 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4244 return FALSE;
4247 /***********************************************************************
4248 * CreateUmsThreadContext (KERNEL32.@)
4250 BOOL WINAPI CreateUmsThreadContext(PUMS_CONTEXT *ctx)
4252 FIXME( "%p: stub\n", ctx );
4253 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4254 return FALSE;
4257 /***********************************************************************
4258 * DeleteProcThreadAttributeList (KERNEL32.@)
4260 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4262 return;
4265 /***********************************************************************
4266 * DeleteUmsCompletionList (KERNEL32.@)
4268 BOOL WINAPI DeleteUmsCompletionList(PUMS_COMPLETION_LIST list)
4270 FIXME( "%p: stub\n", list );
4271 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4272 return FALSE;
4275 /***********************************************************************
4276 * DeleteUmsThreadContext (KERNEL32.@)
4278 BOOL WINAPI DeleteUmsThreadContext(PUMS_CONTEXT ctx)
4280 FIXME( "%p: stub\n", ctx );
4281 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4282 return FALSE;
4285 /***********************************************************************
4286 * DequeueUmsCompletionListItems (KERNEL32.@)
4288 BOOL WINAPI DequeueUmsCompletionListItems(void *list, DWORD timeout, PUMS_CONTEXT *ctx)
4290 FIXME( "%p,%08x,%p: stub\n", list, timeout, ctx );
4291 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4292 return FALSE;
4295 /***********************************************************************
4296 * EnterUmsSchedulingMode (KERNEL32.@)
4298 BOOL WINAPI EnterUmsSchedulingMode(UMS_SCHEDULER_STARTUP_INFO *info)
4300 FIXME( "%p: stub\n", info );
4301 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4302 return FALSE;
4305 /***********************************************************************
4306 * ExecuteUmsThread (KERNEL32.@)
4308 BOOL WINAPI ExecuteUmsThread(PUMS_CONTEXT ctx)
4310 FIXME( "%p: stub\n", ctx );
4311 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4312 return FALSE;
4315 /***********************************************************************
4316 * GetCurrentUmsThread (KERNEL32.@)
4318 PUMS_CONTEXT WINAPI GetCurrentUmsThread(void)
4320 FIXME( "stub\n" );
4321 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4322 return FALSE;
4325 /***********************************************************************
4326 * GetNextUmsListItem (KERNEL32.@)
4328 PUMS_CONTEXT WINAPI GetNextUmsListItem(PUMS_CONTEXT ctx)
4330 FIXME( "%p: stub\n", ctx );
4331 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4332 return NULL;
4335 /***********************************************************************
4336 * GetUmsCompletionListEvent (KERNEL32.@)
4338 BOOL WINAPI GetUmsCompletionListEvent(PUMS_COMPLETION_LIST list, HANDLE *event)
4340 FIXME( "%p,%p: stub\n", list, event );
4341 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4342 return FALSE;
4345 /***********************************************************************
4346 * QueryUmsThreadInformation (KERNEL32.@)
4348 BOOL WINAPI QueryUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4349 void *buf, ULONG length, ULONG *ret_length)
4351 FIXME( "%p,%08x,%p,%08x,%p: stub\n", ctx, class, buf, length, ret_length );
4352 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4353 return FALSE;
4356 /***********************************************************************
4357 * SetUmsThreadInformation (KERNEL32.@)
4359 BOOL WINAPI SetUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4360 void *buf, ULONG length)
4362 FIXME( "%p,%08x,%p,%08x: stub\n", ctx, class, buf, length );
4363 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4364 return FALSE;
4367 /***********************************************************************
4368 * UmsThreadYield (KERNEL32.@)
4370 BOOL WINAPI UmsThreadYield(void *param)
4372 FIXME( "%p: stub\n", param );
4373 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4374 return FALSE;
4377 /**********************************************************************
4378 * BaseFlushAppcompatCache (KERNEL32.@)
4380 BOOL WINAPI BaseFlushAppcompatCache(void)
4382 FIXME(": stub\n");
4383 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4384 return FALSE;