kernel32: Fix CreateProcess behavior when batch script command contains '"' characters.
[wine.git] / dlls / kernel32 / process.c
blobdf3426b30b0197278fd101736bfb71776a0b4c35
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 slashscW[] = {' ','/','s','/','c',' ',0};
2215 static const WCHAR quotW[] = {'"',0};
2216 WCHAR comspec[MAX_PATH];
2217 WCHAR *newcmdline;
2218 BOOL ret;
2220 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2221 return FALSE;
2222 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2223 (strlenW(comspec) + 7 + strlenW(cmd_line) + 2) * sizeof(WCHAR))))
2224 return FALSE;
2226 strcpyW( newcmdline, comspec );
2227 strcatW( newcmdline, slashscW );
2228 strcatW( newcmdline, quotW );
2229 strcatW( newcmdline, cmd_line );
2230 strcatW( newcmdline, quotW );
2231 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2232 flags, env, cur_dir, startup, info );
2233 HeapFree( GetProcessHeap(), 0, newcmdline );
2234 return ret;
2238 /*************************************************************************
2239 * get_file_name
2241 * Helper for CreateProcess: retrieve the file name to load from the
2242 * app name and command line. Store the file name in buffer, and
2243 * return a possibly modified command line.
2244 * Also returns a handle to the opened file if it's a Windows binary.
2246 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2247 int buflen, HANDLE *handle, struct binary_info *binary_info )
2249 static const WCHAR quotesW[] = {'"','%','s','"',0};
2251 WCHAR *name, *pos, *first_space, *ret = NULL;
2252 const WCHAR *p;
2254 /* if we have an app name, everything is easy */
2256 if (appname)
2258 /* use the unmodified app name as file name */
2259 lstrcpynW( buffer, appname, buflen );
2260 *handle = open_exe_file( buffer, binary_info );
2261 if (!(ret = cmdline) || !cmdline[0])
2263 /* no command-line, create one */
2264 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2265 sprintfW( ret, quotesW, appname );
2267 return ret;
2270 /* first check for a quoted file name */
2272 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2274 int len = p - cmdline - 1;
2275 /* extract the quoted portion as file name */
2276 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2277 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2278 name[len] = 0;
2280 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2281 ret = cmdline; /* no change necessary */
2282 goto done;
2285 /* now try the command-line word by word */
2287 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2288 return NULL;
2289 pos = name;
2290 p = cmdline;
2291 first_space = NULL;
2293 for (;;)
2295 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2296 *pos = 0;
2297 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2299 ret = cmdline;
2300 break;
2302 if (!first_space) first_space = pos;
2303 if (!(*pos++ = *p++)) break;
2306 if (!ret)
2308 SetLastError( ERROR_FILE_NOT_FOUND );
2310 else if (first_space) /* build a new command-line with quotes */
2312 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2313 goto done;
2314 sprintfW( ret, quotesW, name );
2315 strcatW( ret, p );
2318 done:
2319 HeapFree( GetProcessHeap(), 0, name );
2320 return ret;
2324 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2325 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2326 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2327 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2328 LPPROCESS_INFORMATION info )
2330 BOOL retv = FALSE;
2331 HANDLE hFile = 0;
2332 char *unixdir = NULL;
2333 WCHAR name[MAX_PATH];
2334 WCHAR *tidy_cmdline, *p, *envW = env;
2335 struct binary_info binary_info;
2337 /* Process the AppName and/or CmdLine to get module name and path */
2339 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2341 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2342 &hFile, &binary_info )))
2343 return FALSE;
2344 if (hFile == INVALID_HANDLE_VALUE) goto done;
2346 /* Warn if unsupported features are used */
2348 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2349 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2350 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2351 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2352 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2354 if (cur_dir)
2356 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2358 SetLastError(ERROR_DIRECTORY);
2359 goto done;
2362 else
2364 WCHAR buf[MAX_PATH];
2365 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2368 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2370 char *e = env;
2371 DWORD lenW;
2373 while (*e) e += strlen(e) + 1;
2374 e++; /* final null */
2375 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2376 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2377 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2378 flags |= CREATE_UNICODE_ENVIRONMENT;
2381 info->hThread = info->hProcess = 0;
2382 info->dwProcessId = info->dwThreadId = 0;
2384 if (binary_info.flags & BINARY_FLAG_DLL)
2386 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2387 SetLastError( ERROR_BAD_EXE_FORMAT );
2389 else switch (binary_info.type)
2391 case BINARY_PE:
2392 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x%s)\n",
2393 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2394 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2395 binary_info.arch, (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2396 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2397 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2398 break;
2399 case BINARY_OS216:
2400 case BINARY_WIN16:
2401 case BINARY_DOS:
2402 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2403 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2404 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2405 break;
2406 case BINARY_UNIX_LIB:
2407 TRACE( "starting %s as %d-bit Winelib app\n",
2408 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2409 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2410 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2411 break;
2412 case BINARY_UNKNOWN:
2413 /* check for .com or .bat extension */
2414 if ((p = strrchrW( name, '.' )))
2416 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2418 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2419 binary_info.type = BINARY_DOS;
2420 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2421 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2422 inherit, flags, startup_info, info, unixdir,
2423 &binary_info, FALSE );
2424 break;
2426 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2428 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2429 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2430 inherit, flags, startup_info, info );
2431 break;
2434 /* fall through */
2435 case BINARY_UNIX_EXE:
2437 /* unknown file, try as unix executable */
2438 char *unix_name;
2440 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2442 if ((unix_name = wine_get_unix_file_name( name )))
2444 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2445 HeapFree( GetProcessHeap(), 0, unix_name );
2448 break;
2450 if (hFile) CloseHandle( hFile );
2452 done:
2453 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2454 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2455 HeapFree( GetProcessHeap(), 0, unixdir );
2456 if (retv)
2457 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2458 return retv;
2462 /**********************************************************************
2463 * CreateProcessA (KERNEL32.@)
2465 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2466 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2467 DWORD flags, LPVOID env, LPCSTR cur_dir,
2468 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2470 BOOL ret = FALSE;
2471 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2472 UNICODE_STRING desktopW, titleW;
2473 STARTUPINFOW infoW;
2475 desktopW.Buffer = NULL;
2476 titleW.Buffer = NULL;
2477 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2478 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2479 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2481 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2482 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2484 memcpy( &infoW, startup_info, sizeof(infoW) );
2485 infoW.lpDesktop = desktopW.Buffer;
2486 infoW.lpTitle = titleW.Buffer;
2488 if (startup_info->lpReserved)
2489 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2490 debugstr_a(startup_info->lpReserved));
2492 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2493 inherit, flags, env, cur_dirW, &infoW, info );
2494 done:
2495 HeapFree( GetProcessHeap(), 0, app_nameW );
2496 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2497 HeapFree( GetProcessHeap(), 0, cur_dirW );
2498 RtlFreeUnicodeString( &desktopW );
2499 RtlFreeUnicodeString( &titleW );
2500 return ret;
2504 /**********************************************************************
2505 * CreateProcessW (KERNEL32.@)
2507 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2508 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2509 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2510 LPPROCESS_INFORMATION info )
2512 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2513 inherit, flags, env, cur_dir, startup_info, info);
2517 /**********************************************************************
2518 * exec_process
2520 static void exec_process( LPCWSTR name )
2522 HANDLE hFile;
2523 WCHAR *p;
2524 STARTUPINFOW startup_info;
2525 PROCESS_INFORMATION info;
2526 struct binary_info binary_info;
2528 hFile = open_exe_file( name, &binary_info );
2529 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2531 memset( &startup_info, 0, sizeof(startup_info) );
2532 startup_info.cb = sizeof(startup_info);
2534 /* Determine executable type */
2536 if (binary_info.flags & BINARY_FLAG_DLL)
2538 CloseHandle( hFile );
2539 return;
2542 switch (binary_info.type)
2544 case BINARY_PE:
2545 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x)\n",
2546 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2547 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2548 binary_info.arch );
2549 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2550 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2551 break;
2552 case BINARY_UNIX_LIB:
2553 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2554 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2555 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2556 break;
2557 case BINARY_UNKNOWN:
2558 /* check for .com or .pif extension */
2559 if (!(p = strrchrW( name, '.' ))) break;
2560 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2561 binary_info.type = BINARY_DOS;
2562 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2563 /* fall through */
2564 case BINARY_OS216:
2565 case BINARY_WIN16:
2566 case BINARY_DOS:
2567 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2568 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2569 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2570 break;
2571 default:
2572 break;
2574 CloseHandle( hFile );
2578 /***********************************************************************
2579 * wait_input_idle
2581 * Wrapper to call WaitForInputIdle USER function
2583 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2585 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2587 HMODULE mod = GetModuleHandleA( "user32.dll" );
2588 if (mod)
2590 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2591 if (ptr) return ptr( process, timeout );
2593 return 0;
2597 /***********************************************************************
2598 * WinExec (KERNEL32.@)
2600 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2602 PROCESS_INFORMATION info;
2603 STARTUPINFOA startup;
2604 char *cmdline;
2605 UINT ret;
2607 memset( &startup, 0, sizeof(startup) );
2608 startup.cb = sizeof(startup);
2609 startup.dwFlags = STARTF_USESHOWWINDOW;
2610 startup.wShowWindow = nCmdShow;
2612 /* cmdline needs to be writable for CreateProcess */
2613 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2614 strcpy( cmdline, lpCmdLine );
2616 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2617 0, NULL, NULL, &startup, &info ))
2619 /* Give 30 seconds to the app to come up */
2620 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2621 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2622 ret = 33;
2623 /* Close off the handles */
2624 CloseHandle( info.hThread );
2625 CloseHandle( info.hProcess );
2627 else if ((ret = GetLastError()) >= 32)
2629 FIXME("Strange error set by CreateProcess: %d\n", ret );
2630 ret = 11;
2632 HeapFree( GetProcessHeap(), 0, cmdline );
2633 return ret;
2637 /**********************************************************************
2638 * LoadModule (KERNEL32.@)
2640 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2642 LOADPARMS32 *params = paramBlock;
2643 PROCESS_INFORMATION info;
2644 STARTUPINFOA startup;
2645 DWORD ret;
2646 LPSTR cmdline, p;
2647 char filename[MAX_PATH];
2648 BYTE len;
2650 if (!name) return ERROR_FILE_NOT_FOUND;
2652 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2653 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2654 return GetLastError();
2656 len = (BYTE)params->lpCmdLine[0];
2657 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2658 return ERROR_NOT_ENOUGH_MEMORY;
2660 strcpy( cmdline, filename );
2661 p = cmdline + strlen(cmdline);
2662 *p++ = ' ';
2663 memcpy( p, params->lpCmdLine + 1, len );
2664 p[len] = 0;
2666 memset( &startup, 0, sizeof(startup) );
2667 startup.cb = sizeof(startup);
2668 if (params->lpCmdShow)
2670 startup.dwFlags = STARTF_USESHOWWINDOW;
2671 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2674 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2675 params->lpEnvAddress, NULL, &startup, &info ))
2677 /* Give 30 seconds to the app to come up */
2678 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2679 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2680 ret = 33;
2681 /* Close off the handles */
2682 CloseHandle( info.hThread );
2683 CloseHandle( info.hProcess );
2685 else if ((ret = GetLastError()) >= 32)
2687 FIXME("Strange error set by CreateProcess: %u\n", ret );
2688 ret = 11;
2691 HeapFree( GetProcessHeap(), 0, cmdline );
2692 return ret;
2696 /******************************************************************************
2697 * TerminateProcess (KERNEL32.@)
2699 * Terminates a process.
2701 * PARAMS
2702 * handle [I] Process to terminate.
2703 * exit_code [I] Exit code.
2705 * RETURNS
2706 * Success: TRUE.
2707 * Failure: FALSE, check GetLastError().
2709 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2711 NTSTATUS status;
2713 if (!handle)
2715 SetLastError( ERROR_INVALID_HANDLE );
2716 return FALSE;
2719 status = NtTerminateProcess( handle, exit_code );
2720 if (status) SetLastError( RtlNtStatusToDosError(status) );
2721 return !status;
2724 /***********************************************************************
2725 * ExitProcess (KERNEL32.@)
2727 * Exits the current process.
2729 * PARAMS
2730 * status [I] Status code to exit with.
2732 * RETURNS
2733 * Nothing.
2735 #ifdef __i386__
2736 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2737 "pushl %ebp\n\t"
2738 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2739 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2740 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2741 "pushl 8(%ebp)\n\t"
2742 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2743 "leave\n\t"
2744 "ret $4" )
2745 #else
2747 void WINAPI ExitProcess( DWORD status )
2749 RtlExitUserProcess( status );
2752 #endif
2754 /***********************************************************************
2755 * GetExitCodeProcess [KERNEL32.@]
2757 * Gets termination status of specified process.
2759 * PARAMS
2760 * hProcess [in] Handle to the process.
2761 * lpExitCode [out] Address to receive termination status.
2763 * RETURNS
2764 * Success: TRUE
2765 * Failure: FALSE
2767 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2769 NTSTATUS status;
2770 PROCESS_BASIC_INFORMATION pbi;
2772 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2773 sizeof(pbi), NULL);
2774 if (status == STATUS_SUCCESS)
2776 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2777 return TRUE;
2779 SetLastError( RtlNtStatusToDosError(status) );
2780 return FALSE;
2784 /***********************************************************************
2785 * SetErrorMode (KERNEL32.@)
2787 UINT WINAPI SetErrorMode( UINT mode )
2789 UINT old;
2791 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2792 &old, sizeof(old), NULL );
2793 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2794 &mode, sizeof(mode) );
2795 return old;
2798 /***********************************************************************
2799 * GetErrorMode (KERNEL32.@)
2801 UINT WINAPI GetErrorMode( void )
2803 UINT mode;
2805 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2806 &mode, sizeof(mode), NULL );
2807 return mode;
2810 /**********************************************************************
2811 * TlsAlloc [KERNEL32.@]
2813 * Allocates a thread local storage index.
2815 * RETURNS
2816 * Success: TLS index.
2817 * Failure: 0xFFFFFFFF
2819 DWORD WINAPI TlsAlloc( void )
2821 DWORD index;
2822 PEB * const peb = NtCurrentTeb()->Peb;
2824 RtlAcquirePebLock();
2825 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2826 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2827 else
2829 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2830 if (index != ~0U)
2832 if (!NtCurrentTeb()->TlsExpansionSlots &&
2833 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2834 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2836 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2837 index = ~0U;
2838 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2840 else
2842 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2843 index += TLS_MINIMUM_AVAILABLE;
2846 else SetLastError( ERROR_NO_MORE_ITEMS );
2848 RtlReleasePebLock();
2849 return index;
2853 /**********************************************************************
2854 * TlsFree [KERNEL32.@]
2856 * Releases a thread local storage index, making it available for reuse.
2858 * PARAMS
2859 * index [in] TLS index to free.
2861 * RETURNS
2862 * Success: TRUE
2863 * Failure: FALSE
2865 BOOL WINAPI TlsFree( DWORD index )
2867 BOOL ret;
2869 RtlAcquirePebLock();
2870 if (index >= TLS_MINIMUM_AVAILABLE)
2872 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2873 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2875 else
2877 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2878 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2880 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2881 else SetLastError( ERROR_INVALID_PARAMETER );
2882 RtlReleasePebLock();
2883 return ret;
2887 /**********************************************************************
2888 * TlsGetValue [KERNEL32.@]
2890 * Gets value in a thread's TLS slot.
2892 * PARAMS
2893 * index [in] TLS index to retrieve value for.
2895 * RETURNS
2896 * Success: Value stored in calling thread's TLS slot for index.
2897 * Failure: 0 and GetLastError() returns NO_ERROR.
2899 LPVOID WINAPI TlsGetValue( DWORD index )
2901 LPVOID ret;
2903 if (index < TLS_MINIMUM_AVAILABLE)
2905 ret = NtCurrentTeb()->TlsSlots[index];
2907 else
2909 index -= TLS_MINIMUM_AVAILABLE;
2910 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2912 SetLastError( ERROR_INVALID_PARAMETER );
2913 return NULL;
2915 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2916 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2918 SetLastError( ERROR_SUCCESS );
2919 return ret;
2923 /**********************************************************************
2924 * TlsSetValue [KERNEL32.@]
2926 * Stores a value in the thread's TLS slot.
2928 * PARAMS
2929 * index [in] TLS index to set value for.
2930 * value [in] Value to be stored.
2932 * RETURNS
2933 * Success: TRUE
2934 * Failure: FALSE
2936 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2938 if (index < TLS_MINIMUM_AVAILABLE)
2940 NtCurrentTeb()->TlsSlots[index] = value;
2942 else
2944 index -= TLS_MINIMUM_AVAILABLE;
2945 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2947 SetLastError( ERROR_INVALID_PARAMETER );
2948 return FALSE;
2950 if (!NtCurrentTeb()->TlsExpansionSlots &&
2951 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2952 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2954 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2955 return FALSE;
2957 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2959 return TRUE;
2963 /***********************************************************************
2964 * GetProcessFlags (KERNEL32.@)
2966 DWORD WINAPI GetProcessFlags( DWORD processid )
2968 IMAGE_NT_HEADERS *nt;
2969 DWORD flags = 0;
2971 if (processid && processid != GetCurrentProcessId()) return 0;
2973 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2975 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2976 flags |= PDB32_CONSOLE_PROC;
2978 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2979 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2980 return flags;
2984 /*********************************************************************
2985 * OpenProcess (KERNEL32.@)
2987 * Opens a handle to a process.
2989 * PARAMS
2990 * access [I] Desired access rights assigned to the returned handle.
2991 * inherit [I] Determines whether or not child processes will inherit the handle.
2992 * id [I] Process identifier of the process to get a handle to.
2994 * RETURNS
2995 * Success: Valid handle to the specified process.
2996 * Failure: NULL, check GetLastError().
2998 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
3000 NTSTATUS status;
3001 HANDLE handle;
3002 OBJECT_ATTRIBUTES attr;
3003 CLIENT_ID cid;
3005 cid.UniqueProcess = ULongToHandle(id);
3006 cid.UniqueThread = 0; /* FIXME ? */
3008 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3009 attr.RootDirectory = NULL;
3010 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3011 attr.SecurityDescriptor = NULL;
3012 attr.SecurityQualityOfService = NULL;
3013 attr.ObjectName = NULL;
3015 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3017 status = NtOpenProcess(&handle, access, &attr, &cid);
3018 if (status != STATUS_SUCCESS)
3020 SetLastError( RtlNtStatusToDosError(status) );
3021 return NULL;
3023 return handle;
3027 /*********************************************************************
3028 * GetProcessId (KERNEL32.@)
3030 * Gets the a unique identifier of a process.
3032 * PARAMS
3033 * hProcess [I] Handle to the process.
3035 * RETURNS
3036 * Success: TRUE.
3037 * Failure: FALSE, check GetLastError().
3039 * NOTES
3041 * The identifier is unique only on the machine and only until the process
3042 * exits (including system shutdown).
3044 DWORD WINAPI GetProcessId( HANDLE hProcess )
3046 NTSTATUS status;
3047 PROCESS_BASIC_INFORMATION pbi;
3049 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3050 sizeof(pbi), NULL);
3051 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3052 SetLastError( RtlNtStatusToDosError(status) );
3053 return 0;
3057 /*********************************************************************
3058 * CloseHandle (KERNEL32.@)
3060 * Closes a handle.
3062 * PARAMS
3063 * handle [I] Handle to close.
3065 * RETURNS
3066 * Success: TRUE.
3067 * Failure: FALSE, check GetLastError().
3069 BOOL WINAPI CloseHandle( HANDLE handle )
3071 NTSTATUS status;
3073 /* stdio handles need special treatment */
3074 if (handle == (HANDLE)STD_INPUT_HANDLE)
3075 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3076 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3077 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3078 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3079 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3081 if (is_console_handle(handle))
3082 return CloseConsoleHandle(handle);
3084 status = NtClose( handle );
3085 if (status) SetLastError( RtlNtStatusToDosError(status) );
3086 return !status;
3090 /*********************************************************************
3091 * GetHandleInformation (KERNEL32.@)
3093 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3095 OBJECT_DATA_INFORMATION info;
3096 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3098 if (status) SetLastError( RtlNtStatusToDosError(status) );
3099 else if (flags)
3101 *flags = 0;
3102 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3103 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3105 return !status;
3109 /*********************************************************************
3110 * SetHandleInformation (KERNEL32.@)
3112 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3114 OBJECT_DATA_INFORMATION info;
3115 NTSTATUS status;
3117 /* if not setting both fields, retrieve current value first */
3118 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3119 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3121 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3123 SetLastError( RtlNtStatusToDosError(status) );
3124 return FALSE;
3127 if (mask & HANDLE_FLAG_INHERIT)
3128 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3129 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3130 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3132 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3133 if (status) SetLastError( RtlNtStatusToDosError(status) );
3134 return !status;
3138 /*********************************************************************
3139 * DuplicateHandle (KERNEL32.@)
3141 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3142 HANDLE dest_process, HANDLE *dest,
3143 DWORD access, BOOL inherit, DWORD options )
3145 NTSTATUS status;
3147 if (is_console_handle(source))
3149 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3150 if (source_process != dest_process ||
3151 source_process != GetCurrentProcess())
3153 SetLastError(ERROR_INVALID_PARAMETER);
3154 return FALSE;
3156 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3157 return (*dest != INVALID_HANDLE_VALUE);
3159 status = NtDuplicateObject( source_process, source, dest_process, dest,
3160 access, inherit ? OBJ_INHERIT : 0, options );
3161 if (status) SetLastError( RtlNtStatusToDosError(status) );
3162 return !status;
3166 /***********************************************************************
3167 * ConvertToGlobalHandle (KERNEL32.@)
3169 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3171 HANDLE ret = INVALID_HANDLE_VALUE;
3172 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3173 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3174 return ret;
3178 /***********************************************************************
3179 * SetHandleContext (KERNEL32.@)
3181 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3183 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3184 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3185 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3186 return FALSE;
3190 /***********************************************************************
3191 * GetHandleContext (KERNEL32.@)
3193 DWORD WINAPI GetHandleContext(HANDLE hnd)
3195 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3196 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3197 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3198 return 0;
3202 /***********************************************************************
3203 * CreateSocketHandle (KERNEL32.@)
3205 HANDLE WINAPI CreateSocketHandle(void)
3207 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3208 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3209 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3210 return INVALID_HANDLE_VALUE;
3214 /***********************************************************************
3215 * SetPriorityClass (KERNEL32.@)
3217 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3219 NTSTATUS status;
3220 PROCESS_PRIORITY_CLASS ppc;
3222 ppc.Foreground = FALSE;
3223 switch (priorityclass)
3225 case IDLE_PRIORITY_CLASS:
3226 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3227 case BELOW_NORMAL_PRIORITY_CLASS:
3228 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3229 case NORMAL_PRIORITY_CLASS:
3230 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3231 case ABOVE_NORMAL_PRIORITY_CLASS:
3232 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3233 case HIGH_PRIORITY_CLASS:
3234 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3235 case REALTIME_PRIORITY_CLASS:
3236 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3237 default:
3238 SetLastError(ERROR_INVALID_PARAMETER);
3239 return FALSE;
3242 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3243 &ppc, sizeof(ppc));
3245 if (status != STATUS_SUCCESS)
3247 SetLastError( RtlNtStatusToDosError(status) );
3248 return FALSE;
3250 return TRUE;
3254 /***********************************************************************
3255 * GetPriorityClass (KERNEL32.@)
3257 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3259 NTSTATUS status;
3260 PROCESS_BASIC_INFORMATION pbi;
3262 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3263 sizeof(pbi), NULL);
3264 if (status != STATUS_SUCCESS)
3266 SetLastError( RtlNtStatusToDosError(status) );
3267 return 0;
3269 switch (pbi.BasePriority)
3271 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3272 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3273 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3274 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3275 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3276 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3278 SetLastError( ERROR_INVALID_PARAMETER );
3279 return 0;
3283 /***********************************************************************
3284 * SetProcessAffinityMask (KERNEL32.@)
3286 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3288 NTSTATUS status;
3290 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3291 &affmask, sizeof(DWORD_PTR));
3292 if (status)
3294 SetLastError( RtlNtStatusToDosError(status) );
3295 return FALSE;
3297 return TRUE;
3301 /**********************************************************************
3302 * GetProcessAffinityMask (KERNEL32.@)
3304 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3306 NTSTATUS status = STATUS_SUCCESS;
3308 if (process_mask)
3310 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3311 process_mask, sizeof(*process_mask), NULL )))
3312 SetLastError( RtlNtStatusToDosError(status) );
3314 if (system_mask && status == STATUS_SUCCESS)
3316 SYSTEM_BASIC_INFORMATION info;
3318 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3319 SetLastError( RtlNtStatusToDosError(status) );
3320 else
3321 *system_mask = info.ActiveProcessorsAffinityMask;
3323 return !status;
3327 /***********************************************************************
3328 * GetProcessVersion (KERNEL32.@)
3330 DWORD WINAPI GetProcessVersion( DWORD pid )
3332 HANDLE process;
3333 NTSTATUS status;
3334 PROCESS_BASIC_INFORMATION pbi;
3335 SIZE_T count;
3336 PEB peb;
3337 IMAGE_DOS_HEADER dos;
3338 IMAGE_NT_HEADERS nt;
3339 DWORD ver = 0;
3341 if (!pid || pid == GetCurrentProcessId())
3343 IMAGE_NT_HEADERS *pnt;
3345 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3346 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3347 pnt->OptionalHeader.MinorSubsystemVersion);
3348 return 0;
3351 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3352 if (!process) return 0;
3354 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3355 if (status) goto err;
3357 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3358 if (status || count != sizeof(peb)) goto err;
3360 memset(&dos, 0, sizeof(dos));
3361 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3362 if (status || count != sizeof(dos)) goto err;
3363 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3365 memset(&nt, 0, sizeof(nt));
3366 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3367 if (status || count != sizeof(nt)) goto err;
3368 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3370 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3372 err:
3373 CloseHandle(process);
3375 if (status != STATUS_SUCCESS)
3376 SetLastError(RtlNtStatusToDosError(status));
3378 return ver;
3382 /***********************************************************************
3383 * SetProcessWorkingSetSize [KERNEL32.@]
3384 * Sets the min/max working set sizes for a specified process.
3386 * PARAMS
3387 * hProcess [I] Handle to the process of interest
3388 * minset [I] Specifies minimum working set size
3389 * maxset [I] Specifies maximum working set size
3391 * RETURNS
3392 * Success: TRUE
3393 * Failure: FALSE
3395 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3396 SIZE_T maxset)
3398 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3399 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3400 /* Trim the working set to zero */
3401 /* Swap the process out of physical RAM */
3403 return TRUE;
3406 /***********************************************************************
3407 * K32EmptyWorkingSet (KERNEL32.@)
3409 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3411 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3415 /***********************************************************************
3416 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3418 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3419 SIZE_T *maxset, DWORD *flags)
3421 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3422 /* 32 MB working set size */
3423 if (minset) *minset = 32*1024*1024;
3424 if (maxset) *maxset = 32*1024*1024;
3425 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3426 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3427 return TRUE;
3431 /***********************************************************************
3432 * GetProcessWorkingSetSize (KERNEL32.@)
3434 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3436 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3440 /***********************************************************************
3441 * SetProcessShutdownParameters (KERNEL32.@)
3443 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3445 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3446 shutdown_flags = flags;
3447 shutdown_priority = level;
3448 return TRUE;
3452 /***********************************************************************
3453 * GetProcessShutdownParameters (KERNEL32.@)
3456 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3458 *lpdwLevel = shutdown_priority;
3459 *lpdwFlags = shutdown_flags;
3460 return TRUE;
3464 /***********************************************************************
3465 * GetProcessPriorityBoost (KERNEL32.@)
3467 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3469 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3471 /* Report that no boost is present.. */
3472 *pDisablePriorityBoost = FALSE;
3474 return TRUE;
3477 /***********************************************************************
3478 * SetProcessPriorityBoost (KERNEL32.@)
3480 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3482 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3483 /* Say we can do it. I doubt the program will notice that we don't. */
3484 return TRUE;
3488 /***********************************************************************
3489 * ReadProcessMemory (KERNEL32.@)
3491 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3492 SIZE_T *bytes_read )
3494 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3495 if (status) SetLastError( RtlNtStatusToDosError(status) );
3496 return !status;
3500 /***********************************************************************
3501 * WriteProcessMemory (KERNEL32.@)
3503 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3504 SIZE_T *bytes_written )
3506 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3507 if (status) SetLastError( RtlNtStatusToDosError(status) );
3508 return !status;
3512 /****************************************************************************
3513 * FlushInstructionCache (KERNEL32.@)
3515 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3517 NTSTATUS status;
3518 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3519 if (status) SetLastError( RtlNtStatusToDosError(status) );
3520 return !status;
3524 /******************************************************************
3525 * GetProcessIoCounters (KERNEL32.@)
3527 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3529 NTSTATUS status;
3531 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3532 ioc, sizeof(*ioc), NULL);
3533 if (status) SetLastError( RtlNtStatusToDosError(status) );
3534 return !status;
3537 /******************************************************************
3538 * GetProcessHandleCount (KERNEL32.@)
3540 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3542 NTSTATUS status;
3544 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3545 cnt, sizeof(*cnt), NULL);
3546 if (status) SetLastError( RtlNtStatusToDosError(status) );
3547 return !status;
3550 /******************************************************************
3551 * QueryFullProcessImageNameA (KERNEL32.@)
3553 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3555 BOOL retval;
3556 DWORD pdwSizeW = *pdwSize;
3557 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3559 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3561 if(retval)
3562 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3563 lpExeName, *pdwSize, NULL, NULL));
3564 if(retval)
3565 *pdwSize = strlen(lpExeName);
3567 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3568 return retval;
3571 /******************************************************************
3572 * QueryFullProcessImageNameW (KERNEL32.@)
3574 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3576 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3577 UNICODE_STRING *dynamic_buffer = NULL;
3578 UNICODE_STRING *result = NULL;
3579 NTSTATUS status;
3580 DWORD needed;
3582 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3583 * is a DOS path and we depend on this. */
3584 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3585 sizeof(buffer) - sizeof(WCHAR), &needed);
3586 if (status == STATUS_INFO_LENGTH_MISMATCH)
3588 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3589 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3590 result = dynamic_buffer;
3592 else
3593 result = (PUNICODE_STRING)buffer;
3595 if (status) goto cleanup;
3597 if (dwFlags & PROCESS_NAME_NATIVE)
3599 WCHAR drive[3];
3600 WCHAR device[1024];
3601 DWORD ntlen, devlen;
3603 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3605 /* We cannot convert it to an NT device path so fail */
3606 status = STATUS_NO_SUCH_DEVICE;
3607 goto cleanup;
3610 /* Find this drive's NT device path */
3611 drive[0] = result->Buffer[0];
3612 drive[1] = ':';
3613 drive[2] = 0;
3614 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3616 status = STATUS_NO_SUCH_DEVICE;
3617 goto cleanup;
3620 devlen = lstrlenW(device);
3621 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3622 if (ntlen + 1 > *pdwSize)
3624 status = STATUS_BUFFER_TOO_SMALL;
3625 goto cleanup;
3627 *pdwSize = ntlen;
3629 memcpy(lpExeName, device, devlen * sizeof(*device));
3630 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3631 lpExeName[*pdwSize] = 0;
3632 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3634 else
3636 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3638 status = STATUS_BUFFER_TOO_SMALL;
3639 goto cleanup;
3642 *pdwSize = result->Length/sizeof(WCHAR);
3643 memcpy( lpExeName, result->Buffer, result->Length );
3644 lpExeName[*pdwSize] = 0;
3647 cleanup:
3648 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3649 if (status) SetLastError( RtlNtStatusToDosError(status) );
3650 return !status;
3653 /***********************************************************************
3654 * K32GetProcessImageFileNameA (KERNEL32.@)
3656 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3658 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3661 /***********************************************************************
3662 * K32GetProcessImageFileNameW (KERNEL32.@)
3664 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3666 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3669 /***********************************************************************
3670 * K32EnumProcesses (KERNEL32.@)
3672 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3674 SYSTEM_PROCESS_INFORMATION *spi;
3675 ULONG size = 0x4000;
3676 void *buf = NULL;
3677 NTSTATUS status;
3679 do {
3680 size *= 2;
3681 HeapFree(GetProcessHeap(), 0, buf);
3682 buf = HeapAlloc(GetProcessHeap(), 0, size);
3683 if (!buf)
3684 return FALSE;
3686 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3687 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3689 if (status != STATUS_SUCCESS)
3691 HeapFree(GetProcessHeap(), 0, buf);
3692 SetLastError(RtlNtStatusToDosError(status));
3693 return FALSE;
3696 spi = buf;
3698 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3700 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3701 *lpcbUsed += sizeof(DWORD);
3703 if (spi->NextEntryOffset == 0)
3704 break;
3706 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3709 HeapFree(GetProcessHeap(), 0, buf);
3710 return TRUE;
3713 /***********************************************************************
3714 * K32QueryWorkingSet (KERNEL32.@)
3716 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3718 NTSTATUS status;
3720 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3722 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3724 if (status)
3726 SetLastError( RtlNtStatusToDosError( status ) );
3727 return FALSE;
3729 return TRUE;
3732 /***********************************************************************
3733 * K32QueryWorkingSetEx (KERNEL32.@)
3735 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3737 NTSTATUS status;
3739 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3741 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3743 if (status)
3745 SetLastError( RtlNtStatusToDosError( status ) );
3746 return FALSE;
3748 return TRUE;
3751 /***********************************************************************
3752 * K32GetProcessMemoryInfo (KERNEL32.@)
3754 * Retrieve memory usage information for a given process
3757 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3758 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3760 NTSTATUS status;
3761 VM_COUNTERS vmc;
3763 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3765 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3766 return FALSE;
3769 status = NtQueryInformationProcess(process, ProcessVmCounters,
3770 &vmc, sizeof(vmc), NULL);
3772 if (status)
3774 SetLastError(RtlNtStatusToDosError(status));
3775 return FALSE;
3778 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3779 pmc->PageFaultCount = vmc.PageFaultCount;
3780 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3781 pmc->WorkingSetSize = vmc.WorkingSetSize;
3782 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3783 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3784 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3785 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3786 pmc->PagefileUsage = vmc.PagefileUsage;
3787 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3789 return TRUE;
3792 /***********************************************************************
3793 * ProcessIdToSessionId (KERNEL32.@)
3794 * This function is available on Terminal Server 4SP4 and Windows 2000
3796 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3798 if (procid != GetCurrentProcessId())
3799 FIXME("Unsupported for other processes.\n");
3801 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3802 return TRUE;
3806 /***********************************************************************
3807 * RegisterServiceProcess (KERNEL32.@)
3809 * A service process calls this function to ensure that it continues to run
3810 * even after a user logged off.
3812 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3814 /* I don't think that Wine needs to do anything in this function */
3815 return 1; /* success */
3819 /**********************************************************************
3820 * IsWow64Process (KERNEL32.@)
3822 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3824 ULONG_PTR pbi;
3825 NTSTATUS status;
3827 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3829 if (status != STATUS_SUCCESS)
3831 SetLastError( RtlNtStatusToDosError( status ) );
3832 return FALSE;
3834 *Wow64Process = (pbi != 0);
3835 return TRUE;
3839 /***********************************************************************
3840 * GetCurrentProcess (KERNEL32.@)
3842 * Get a handle to the current process.
3844 * PARAMS
3845 * None.
3847 * RETURNS
3848 * A handle representing the current process.
3850 #undef GetCurrentProcess
3851 HANDLE WINAPI GetCurrentProcess(void)
3853 return (HANDLE)~(ULONG_PTR)0;
3856 /***********************************************************************
3857 * GetLogicalProcessorInformation (KERNEL32.@)
3859 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3861 NTSTATUS status;
3863 TRACE("(%p,%p)\n", buffer, pBufLen);
3865 if(!pBufLen)
3867 SetLastError(ERROR_INVALID_PARAMETER);
3868 return FALSE;
3871 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3873 if (status == STATUS_INFO_LENGTH_MISMATCH)
3875 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3876 return FALSE;
3878 if (status != STATUS_SUCCESS)
3880 SetLastError( RtlNtStatusToDosError( status ) );
3881 return FALSE;
3883 return TRUE;
3886 /***********************************************************************
3887 * GetLogicalProcessorInformationEx (KERNEL32.@)
3889 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
3891 NTSTATUS status;
3893 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
3895 if (!len)
3897 SetLastError( ERROR_INVALID_PARAMETER );
3898 return FALSE;
3901 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
3902 buffer, *len, len );
3903 if (status == STATUS_INFO_LENGTH_MISMATCH)
3905 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3906 return FALSE;
3908 if (status != STATUS_SUCCESS)
3910 SetLastError( RtlNtStatusToDosError( status ) );
3911 return FALSE;
3913 return TRUE;
3916 /***********************************************************************
3917 * CmdBatNotification (KERNEL32.@)
3919 * Notifies the system that a batch file has started or finished.
3921 * PARAMS
3922 * bBatchRunning [I] TRUE if a batch file has started or
3923 * FALSE if a batch file has finished executing.
3925 * RETURNS
3926 * Unknown.
3928 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3930 FIXME("%d\n", bBatchRunning);
3931 return FALSE;
3935 /***********************************************************************
3936 * RegisterApplicationRestart (KERNEL32.@)
3938 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3940 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3942 return S_OK;
3945 /**********************************************************************
3946 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3948 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3950 static int once;
3951 if (!once++) FIXME("stub\n");
3952 /* Return current session id. */
3953 return NtCurrentTeb()->Peb->SessionId;
3956 /**********************************************************************
3957 * GetSystemDEPPolicy (KERNEL32.@)
3959 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3961 FIXME("stub\n");
3962 return OptIn;
3965 /**********************************************************************
3966 * SetProcessDEPPolicy (KERNEL32.@)
3968 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
3970 FIXME("(%d): stub\n", newDEP);
3971 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3972 return FALSE;
3975 /**********************************************************************
3976 * ApplicationRecoveryFinished (KERNEL32.@)
3978 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
3980 FIXME(": stub\n");
3981 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3984 /**********************************************************************
3985 * ApplicationRecoveryInProgress (KERNEL32.@)
3987 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
3989 FIXME(":%p stub\n", canceled);
3990 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3991 return E_FAIL;
3994 /**********************************************************************
3995 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3997 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
3999 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
4000 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4001 return E_FAIL;
4004 /**********************************************************************
4005 * GetNumaHighestNodeNumber (KERNEL32.@)
4007 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4009 *highestnode = 0;
4010 FIXME("(%p): semi-stub\n", highestnode);
4011 return TRUE;
4014 /**********************************************************************
4015 * GetNumaNodeProcessorMask (KERNEL32.@)
4017 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4019 FIXME("(%c %p): stub\n", node, mask);
4020 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4021 return FALSE;
4024 /**********************************************************************
4025 * GetNumaNodeProcessorMaskEx (KERNEL32.@)
4027 BOOL WINAPI GetNumaNodeProcessorMaskEx(USHORT node, PGROUP_AFFINITY mask)
4029 FIXME("(%hu %p): stub\n", node, mask);
4030 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4031 return FALSE;
4034 /**********************************************************************
4035 * GetNumaAvailableMemoryNode (KERNEL32.@)
4037 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4039 FIXME("(%c %p): stub\n", node, available_bytes);
4040 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4041 return FALSE;
4044 /***********************************************************************
4045 * GetNumaProcessorNode (KERNEL32.@)
4047 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4049 SYSTEM_INFO si;
4051 TRACE("(%d, %p)\n", processor, node);
4053 GetSystemInfo( &si );
4054 if (processor < si.dwNumberOfProcessors)
4056 *node = 0;
4057 return TRUE;
4060 *node = 0xFF;
4061 SetLastError(ERROR_INVALID_PARAMETER);
4062 return FALSE;
4065 /**********************************************************************
4066 * GetProcessDEPPolicy (KERNEL32.@)
4068 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4070 NTSTATUS status;
4071 ULONG dep_flags;
4073 TRACE("(%p %p %p)\n", process, flags, permanent);
4075 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4076 &dep_flags, sizeof(dep_flags), NULL );
4077 if (!status)
4080 if (flags)
4082 *flags = 0;
4083 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4084 *flags |= PROCESS_DEP_ENABLE;
4085 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4086 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4089 if (permanent)
4090 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4093 if (status) SetLastError( RtlNtStatusToDosError(status) );
4094 return !status;
4097 /**********************************************************************
4098 * FlushProcessWriteBuffers (KERNEL32.@)
4100 VOID WINAPI FlushProcessWriteBuffers(void)
4102 static int once = 0;
4104 if (!once++)
4105 FIXME(": stub\n");
4108 /***********************************************************************
4109 * UnregisterApplicationRestart (KERNEL32.@)
4111 HRESULT WINAPI UnregisterApplicationRestart(void)
4113 FIXME(": stub\n");
4114 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4115 return S_OK;
4118 /***********************************************************************
4119 * GetSystemFirmwareTable (KERNEL32.@)
4121 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4123 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4124 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4125 return 0;
4128 struct proc_thread_attr
4130 DWORD_PTR attr;
4131 SIZE_T size;
4132 void *value;
4135 struct _PROC_THREAD_ATTRIBUTE_LIST
4137 DWORD mask; /* bitmask of items in list */
4138 DWORD size; /* max number of items in list */
4139 DWORD count; /* number of items in list */
4140 DWORD pad;
4141 DWORD_PTR unk;
4142 struct proc_thread_attr attrs[1];
4145 /***********************************************************************
4146 * InitializeProcThreadAttributeList (KERNEL32.@)
4148 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4149 DWORD count, DWORD flags, SIZE_T *size)
4151 SIZE_T needed;
4152 BOOL ret = FALSE;
4154 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4156 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4157 if (list && *size >= needed)
4159 list->mask = 0;
4160 list->size = count;
4161 list->count = 0;
4162 list->unk = 0;
4163 ret = TRUE;
4165 else
4166 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4168 *size = needed;
4169 return ret;
4172 /***********************************************************************
4173 * UpdateProcThreadAttribute (KERNEL32.@)
4175 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4176 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4177 void *prev_ret, SIZE_T *size_ret)
4179 DWORD mask;
4180 struct proc_thread_attr *entry;
4182 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4184 if (list->count >= list->size)
4186 SetLastError(ERROR_GEN_FAILURE);
4187 return FALSE;
4190 switch (attr)
4192 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4193 if (size != sizeof(HANDLE))
4195 SetLastError(ERROR_BAD_LENGTH);
4196 return FALSE;
4198 break;
4200 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4201 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4203 SetLastError(ERROR_BAD_LENGTH);
4204 return FALSE;
4206 break;
4208 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4209 if (size != sizeof(PROCESSOR_NUMBER))
4211 SetLastError(ERROR_BAD_LENGTH);
4212 return FALSE;
4214 break;
4216 default:
4217 SetLastError(ERROR_NOT_SUPPORTED);
4218 return FALSE;
4221 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4223 if (list->mask & mask)
4225 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4226 return FALSE;
4229 list->mask |= mask;
4231 entry = list->attrs + list->count;
4232 entry->attr = attr;
4233 entry->size = size;
4234 entry->value = value;
4235 list->count++;
4237 return TRUE;
4240 /***********************************************************************
4241 * CreateUmsCompletionList (KERNEL32.@)
4243 BOOL WINAPI CreateUmsCompletionList(PUMS_COMPLETION_LIST *list)
4245 FIXME( "%p: stub\n", list );
4246 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4247 return FALSE;
4250 /***********************************************************************
4251 * CreateUmsThreadContext (KERNEL32.@)
4253 BOOL WINAPI CreateUmsThreadContext(PUMS_CONTEXT *ctx)
4255 FIXME( "%p: stub\n", ctx );
4256 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4257 return FALSE;
4260 /***********************************************************************
4261 * DeleteProcThreadAttributeList (KERNEL32.@)
4263 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4265 return;
4268 /***********************************************************************
4269 * DeleteUmsCompletionList (KERNEL32.@)
4271 BOOL WINAPI DeleteUmsCompletionList(PUMS_COMPLETION_LIST list)
4273 FIXME( "%p: stub\n", list );
4274 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4275 return FALSE;
4278 /***********************************************************************
4279 * DeleteUmsThreadContext (KERNEL32.@)
4281 BOOL WINAPI DeleteUmsThreadContext(PUMS_CONTEXT ctx)
4283 FIXME( "%p: stub\n", ctx );
4284 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4285 return FALSE;
4288 /***********************************************************************
4289 * DequeueUmsCompletionListItems (KERNEL32.@)
4291 BOOL WINAPI DequeueUmsCompletionListItems(void *list, DWORD timeout, PUMS_CONTEXT *ctx)
4293 FIXME( "%p,%08x,%p: stub\n", list, timeout, ctx );
4294 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4295 return FALSE;
4298 /***********************************************************************
4299 * EnterUmsSchedulingMode (KERNEL32.@)
4301 BOOL WINAPI EnterUmsSchedulingMode(UMS_SCHEDULER_STARTUP_INFO *info)
4303 FIXME( "%p: stub\n", info );
4304 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4305 return FALSE;
4308 /***********************************************************************
4309 * ExecuteUmsThread (KERNEL32.@)
4311 BOOL WINAPI ExecuteUmsThread(PUMS_CONTEXT ctx)
4313 FIXME( "%p: stub\n", ctx );
4314 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4315 return FALSE;
4318 /***********************************************************************
4319 * GetCurrentUmsThread (KERNEL32.@)
4321 PUMS_CONTEXT WINAPI GetCurrentUmsThread(void)
4323 FIXME( "stub\n" );
4324 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4325 return FALSE;
4328 /***********************************************************************
4329 * GetNextUmsListItem (KERNEL32.@)
4331 PUMS_CONTEXT WINAPI GetNextUmsListItem(PUMS_CONTEXT ctx)
4333 FIXME( "%p: stub\n", ctx );
4334 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4335 return NULL;
4338 /***********************************************************************
4339 * GetUmsCompletionListEvent (KERNEL32.@)
4341 BOOL WINAPI GetUmsCompletionListEvent(PUMS_COMPLETION_LIST list, HANDLE *event)
4343 FIXME( "%p,%p: stub\n", list, event );
4344 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4345 return FALSE;
4348 /***********************************************************************
4349 * QueryUmsThreadInformation (KERNEL32.@)
4351 BOOL WINAPI QueryUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4352 void *buf, ULONG length, ULONG *ret_length)
4354 FIXME( "%p,%08x,%p,%08x,%p: stub\n", ctx, class, buf, length, ret_length );
4355 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4356 return FALSE;
4359 /***********************************************************************
4360 * SetUmsThreadInformation (KERNEL32.@)
4362 BOOL WINAPI SetUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4363 void *buf, ULONG length)
4365 FIXME( "%p,%08x,%p,%08x: stub\n", ctx, class, buf, length );
4366 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4367 return FALSE;
4370 /***********************************************************************
4371 * UmsThreadYield (KERNEL32.@)
4373 BOOL WINAPI UmsThreadYield(void *param)
4375 FIXME( "%p: stub\n", param );
4376 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4377 return FALSE;
4380 /**********************************************************************
4381 * BaseFlushAppcompatCache (KERNEL32.@)
4383 BOOL WINAPI BaseFlushAppcompatCache(void)
4385 FIXME(": stub\n");
4386 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4387 return FALSE;