ntdll: Hardcode the windows and system directories.
[wine.git] / dlls / kernel32 / process.c
blobbbadae0302ae317ecc67982360171b354941822f
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(file);
68 WINE_DECLARE_DEBUG_CHANNEL(relay);
70 #ifdef __APPLE__
71 extern char **__wine_get_main_environment(void);
72 #else
73 extern char **__wine_main_environ;
74 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
75 #endif
77 typedef struct
79 LPSTR lpEnvAddress;
80 LPSTR lpCmdLine;
81 LPSTR lpCmdShow;
82 DWORD dwReserved;
83 } LOADPARMS32;
85 static DWORD shutdown_flags = 0;
86 static DWORD shutdown_priority = 0x280;
87 static BOOL is_wow64;
88 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
90 HMODULE kernel32_handle = 0;
91 SYSTEM_BASIC_INFORMATION system_info = { 0 };
93 const WCHAR *DIR_Windows = NULL;
94 const WCHAR *DIR_System = NULL;
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 ));
143 /***********************************************************************
144 * is_path_prefix
146 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
148 unsigned int len = strlenW( prefix );
150 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
151 while (filename[len] == '\\') len++;
152 return len;
156 /***************************************************************************
157 * get_builtin_path
159 * Get the path of a builtin module when the native file does not exist.
161 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
162 UINT size, struct binary_info *binary_info )
164 WCHAR *file_part;
165 UINT len;
166 void *redir_disabled = 0;
167 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
169 /* builtin names cannot be empty or contain spaces */
170 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
172 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
173 Wow64RevertWow64FsRedirection( redir_disabled );
175 if (contains_path( libname ))
177 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
178 filename, &file_part ) > size * sizeof(WCHAR))
179 return FALSE; /* too long */
181 if ((len = is_path_prefix( DIR_System, filename )))
183 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
185 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
187 flags = 0;
189 else return FALSE;
191 if (filename + len != file_part) return FALSE;
193 else
195 len = strlenW( DIR_System );
196 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
197 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
198 file_part = filename + len;
199 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
200 strcpyW( file_part, libname );
201 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
203 if (ext && !strchrW( file_part, '.' ))
205 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
206 return FALSE; /* too long */
207 strcatW( file_part, ext );
209 binary_info->type = BINARY_UNIX_LIB;
210 binary_info->flags = flags;
211 binary_info->res_start = 0;
212 binary_info->res_end = 0;
213 /* assume current arch */
214 #if defined(__i386__) || defined(__x86_64__)
215 binary_info->arch = (flags & BINARY_FLAG_64BIT) ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
216 #elif defined(__powerpc__)
217 binary_info->arch = IMAGE_FILE_MACHINE_POWERPC;
218 #elif defined(__arm__) && !defined(__ARMEB__)
219 binary_info->arch = IMAGE_FILE_MACHINE_ARMNT;
220 #elif defined(__aarch64__)
221 binary_info->arch = IMAGE_FILE_MACHINE_ARM64;
222 #else
223 binary_info->arch = IMAGE_FILE_MACHINE_UNKNOWN;
224 #endif
225 return TRUE;
229 /***********************************************************************
230 * open_exe_file
232 * Open a specific exe file, taking load order into account.
233 * Returns the file handle or 0 for a builtin exe.
235 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
237 HANDLE handle;
239 TRACE("looking for %s\n", debugstr_w(name) );
241 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
242 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
244 WCHAR buffer[MAX_PATH];
245 /* file doesn't exist, check for builtin */
246 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
247 handle = 0;
249 else MODULE_get_binary_info( handle, binary_info );
251 return handle;
255 /***********************************************************************
256 * find_exe_file
258 * Open an exe file, and return the full name and file handle.
259 * Returns FALSE if file could not be found.
261 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
262 HANDLE *handle, struct binary_info *binary_info )
264 TRACE("looking for %s\n", debugstr_w(name) );
266 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
267 /* no builtin found, try native without extension in case it is a Unix app */
268 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
270 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
271 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
272 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
274 MODULE_get_binary_info( *handle, binary_info );
275 return TRUE;
277 return FALSE;
281 /***********************************************************************
282 * build_initial_environment
284 * Build the Win32 environment from the Unix environment
286 static BOOL build_initial_environment(void)
288 SIZE_T size = 1;
289 char **e;
290 WCHAR *p, *endptr;
291 void *ptr;
292 char **env = __wine_get_main_environment();
294 /* Compute the total size of the Unix environment */
295 for (e = env; *e; e++)
297 if (is_special_env_var( *e )) continue;
298 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
300 size *= sizeof(WCHAR);
302 /* Now allocate the environment */
303 ptr = NULL;
304 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
305 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
306 return FALSE;
308 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
309 endptr = p + size / sizeof(WCHAR);
311 /* And fill it with the Unix environment */
312 for (e = env; *e; e++)
314 char *str = *e;
316 /* skip Unix special variables and use the Wine variants instead */
317 if (!strncmp( str, "WINE", 4 ))
319 if (is_special_env_var( str + 4 )) str += 4;
320 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
322 else if (is_special_env_var( str )) continue; /* skip it */
324 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
325 p += strlenW(p) + 1;
327 *p = 0;
328 return TRUE;
332 /***********************************************************************
333 * set_registry_variables
335 * Set environment variables by enumerating the values of a key;
336 * helper for set_registry_environment().
337 * Note that Windows happily truncates the value if it's too big.
339 static void set_registry_variables( HANDLE hkey, ULONG type )
341 static const WCHAR pathW[] = {'P','A','T','H'};
342 static const WCHAR sep[] = {';',0};
343 UNICODE_STRING env_name, env_value;
344 NTSTATUS status;
345 DWORD size;
346 int index;
347 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
348 WCHAR tmpbuf[1024];
349 UNICODE_STRING tmp;
350 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
352 tmp.Buffer = tmpbuf;
353 tmp.MaximumLength = sizeof(tmpbuf);
355 for (index = 0; ; index++)
357 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
358 buffer, sizeof(buffer), &size );
359 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
360 break;
361 if (info->Type != type)
362 continue;
363 env_name.Buffer = info->Name;
364 env_name.Length = env_name.MaximumLength = info->NameLength;
365 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
366 env_value.Length = info->DataLength;
367 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
368 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
369 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
370 if (!env_value.Length) continue;
371 if (info->Type == REG_EXPAND_SZ)
373 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
374 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
375 RtlCopyUnicodeString( &env_value, &tmp );
377 /* PATH is magic */
378 if (env_name.Length == sizeof(pathW) &&
379 !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
380 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
382 RtlAppendUnicodeToString( &tmp, sep );
383 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
384 RtlCopyUnicodeString( &env_value, &tmp );
386 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
391 /***********************************************************************
392 * set_registry_environment
394 * Set the environment variables specified in the registry.
396 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
397 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
398 * on the order in which the variables are processed. But on Windows it
399 * does not really matter since they only use %SystemDrive% and
400 * %SystemRoot% which are predefined. But Wine defines these in the
401 * registry, so we need two passes.
403 static BOOL set_registry_environment( BOOL volatile_only )
405 static const WCHAR env_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
406 'M','a','c','h','i','n','e','\\',
407 'S','y','s','t','e','m','\\',
408 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
409 'C','o','n','t','r','o','l','\\',
410 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
411 'E','n','v','i','r','o','n','m','e','n','t',0};
412 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
413 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};
415 OBJECT_ATTRIBUTES attr;
416 UNICODE_STRING nameW;
417 HANDLE hkey;
418 BOOL ret = FALSE;
420 attr.Length = sizeof(attr);
421 attr.RootDirectory = 0;
422 attr.ObjectName = &nameW;
423 attr.Attributes = 0;
424 attr.SecurityDescriptor = NULL;
425 attr.SecurityQualityOfService = NULL;
427 /* first the system environment variables */
428 RtlInitUnicodeString( &nameW, env_keyW );
429 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
431 set_registry_variables( hkey, REG_SZ );
432 set_registry_variables( hkey, REG_EXPAND_SZ );
433 NtClose( hkey );
434 ret = TRUE;
437 /* then the ones for the current user */
438 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
439 RtlInitUnicodeString( &nameW, envW );
440 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
442 set_registry_variables( hkey, REG_SZ );
443 set_registry_variables( hkey, REG_EXPAND_SZ );
444 NtClose( hkey );
447 RtlInitUnicodeString( &nameW, volatile_envW );
448 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
450 set_registry_variables( hkey, REG_SZ );
451 set_registry_variables( hkey, REG_EXPAND_SZ );
452 NtClose( hkey );
455 NtClose( attr.RootDirectory );
456 return ret;
460 /***********************************************************************
461 * get_reg_value
463 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
465 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
466 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
467 DWORD len, size = sizeof(buffer);
468 WCHAR *ret = NULL;
469 UNICODE_STRING nameW;
471 RtlInitUnicodeString( &nameW, name );
472 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
473 return NULL;
475 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
476 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
478 if (info->Type == REG_EXPAND_SZ)
480 UNICODE_STRING value, expanded;
482 value.MaximumLength = len * sizeof(WCHAR);
483 value.Buffer = (WCHAR *)info->Data;
484 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
485 value.Length = len * sizeof(WCHAR);
486 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
487 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
488 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
489 else RtlFreeUnicodeString( &expanded );
491 else if (info->Type == REG_SZ)
493 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
495 memcpy( ret, info->Data, len * sizeof(WCHAR) );
496 ret[len] = 0;
499 return ret;
503 /***********************************************************************
504 * set_additional_environment
506 * Set some additional environment variables not specified in the registry.
508 static void set_additional_environment(void)
510 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
511 'M','a','c','h','i','n','e','\\',
512 'S','o','f','t','w','a','r','e','\\',
513 'M','i','c','r','o','s','o','f','t','\\',
514 'W','i','n','d','o','w','s',' ','N','T','\\',
515 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
516 'P','r','o','f','i','l','e','L','i','s','t',0};
517 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
518 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
519 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
520 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
521 static const WCHAR programdataW[] = {'P','r','o','g','r','a','m','D','a','t','a',0};
522 OBJECT_ATTRIBUTES attr;
523 UNICODE_STRING nameW;
524 WCHAR *profile_dir = NULL, *all_users_dir = NULL, *program_data_dir = NULL;
525 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
526 HANDLE hkey;
527 DWORD len;
529 /* ComputerName */
530 len = sizeof(buf) / sizeof(WCHAR);
531 if (GetComputerNameW( buf, &len ))
532 SetEnvironmentVariableW( computernameW, buf );
534 /* set the ALLUSERSPROFILE variables */
536 attr.Length = sizeof(attr);
537 attr.RootDirectory = 0;
538 attr.ObjectName = &nameW;
539 attr.Attributes = 0;
540 attr.SecurityDescriptor = NULL;
541 attr.SecurityQualityOfService = NULL;
542 RtlInitUnicodeString( &nameW, profile_keyW );
543 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
545 profile_dir = get_reg_value( hkey, profiles_valueW );
546 all_users_dir = get_reg_value( hkey, all_users_valueW );
547 program_data_dir = get_reg_value( hkey, programdataW );
548 NtClose( hkey );
551 if (profile_dir && all_users_dir)
553 WCHAR *value, *p;
555 len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
556 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
557 strcpyW( value, profile_dir );
558 p = value + strlenW(value);
559 if (p > value && p[-1] != '\\') *p++ = '\\';
560 strcpyW( p, all_users_dir );
561 SetEnvironmentVariableW( allusersW, value );
562 HeapFree( GetProcessHeap(), 0, value );
565 if (program_data_dir)
567 SetEnvironmentVariableW( programdataW, program_data_dir );
570 HeapFree( GetProcessHeap(), 0, all_users_dir );
571 HeapFree( GetProcessHeap(), 0, profile_dir );
572 HeapFree( GetProcessHeap(), 0, program_data_dir );
575 /***********************************************************************
576 * set_wow64_environment
578 * Set the environment variables that change across 32/64/Wow64.
580 static void set_wow64_environment(void)
582 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};
583 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};
584 static const WCHAR x86W[] = {'x','8','6',0};
585 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
586 'M','a','c','h','i','n','e','\\',
587 'S','o','f','t','w','a','r','e','\\',
588 'M','i','c','r','o','s','o','f','t','\\',
589 'W','i','n','d','o','w','s','\\',
590 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
591 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
592 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
593 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
594 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
595 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
596 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
597 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
598 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
600 OBJECT_ATTRIBUTES attr;
601 UNICODE_STRING nameW;
602 WCHAR arch[64];
603 WCHAR *value;
604 HANDLE hkey;
606 /* set the PROCESSOR_ARCHITECTURE variable */
608 if (GetEnvironmentVariableW( arch6432W, arch, sizeof(arch)/sizeof(WCHAR) ))
610 if (is_win64)
612 SetEnvironmentVariableW( archW, arch );
613 SetEnvironmentVariableW( arch6432W, NULL );
616 else if (GetEnvironmentVariableW( archW, arch, sizeof(arch)/sizeof(WCHAR) ))
618 if (is_wow64)
620 SetEnvironmentVariableW( arch6432W, arch );
621 SetEnvironmentVariableW( archW, x86W );
625 attr.Length = sizeof(attr);
626 attr.RootDirectory = 0;
627 attr.ObjectName = &nameW;
628 attr.Attributes = 0;
629 attr.SecurityDescriptor = NULL;
630 attr.SecurityQualityOfService = NULL;
631 RtlInitUnicodeString( &nameW, versionW );
632 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
634 /* set the ProgramFiles variables */
636 if ((value = get_reg_value( hkey, progdirW )))
638 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
639 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
640 HeapFree( GetProcessHeap(), 0, value );
642 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
644 SetEnvironmentVariableW( progfilesW, value );
645 HeapFree( GetProcessHeap(), 0, value );
648 /* set the CommonProgramFiles variables */
650 if ((value = get_reg_value( hkey, commondirW )))
652 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
653 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
654 HeapFree( GetProcessHeap(), 0, value );
656 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
658 SetEnvironmentVariableW( commonfilesW, value );
659 HeapFree( GetProcessHeap(), 0, value );
662 NtClose( hkey );
665 /***********************************************************************
666 * set_library_wargv
668 * Set the Wine library Unicode argv global variables.
670 static void set_library_wargv( char **argv )
672 int argc;
673 char *q;
674 WCHAR *p;
675 WCHAR **wargv;
676 DWORD total = 0;
678 for (argc = 0; argv[argc]; argc++)
679 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
681 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
682 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
683 p = (WCHAR *)(wargv + argc + 1);
684 for (argc = 0; argv[argc]; argc++)
686 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
687 wargv[argc] = p;
688 p += reslen;
689 total -= reslen;
691 wargv[argc] = NULL;
693 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
695 for (argc = 0; wargv[argc]; argc++)
696 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
698 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
699 q = (char *)(argv + argc + 1);
700 for (argc = 0; wargv[argc]; argc++)
702 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
703 argv[argc] = q;
704 q += reslen;
705 total -= reslen;
707 argv[argc] = NULL;
709 __wine_main_argc = argc;
710 __wine_main_argv = argv;
711 __wine_main_wargv = wargv;
715 /***********************************************************************
716 * update_library_argv0
718 * Update the argv[0] global variable with the binary we have found.
720 static void update_library_argv0( const WCHAR *argv0 )
722 DWORD len = strlenW( argv0 );
724 if (len > strlenW( __wine_main_wargv[0] ))
726 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
728 strcpyW( __wine_main_wargv[0], argv0 );
730 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
731 if (len > strlen( __wine_main_argv[0] ) + 1)
733 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
735 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
739 /***********************************************************************
740 * build_command_line
742 * Build the command line of a process from the argv array.
744 * Note that it does NOT necessarily include the file name.
745 * Sometimes we don't even have any command line options at all.
747 * We must quote and escape characters so that the argv array can be rebuilt
748 * from the command line:
749 * - spaces and tabs must be quoted
750 * 'a b' -> '"a b"'
751 * - quotes must be escaped
752 * '"' -> '\"'
753 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
754 * resulting in an odd number of '\' followed by a '"'
755 * '\"' -> '\\\"'
756 * '\\"' -> '\\\\\"'
757 * - '\'s are followed by the closing '"' must be doubled,
758 * resulting in an even number of '\' followed by a '"'
759 * ' \' -> '" \\"'
760 * ' \\' -> '" \\\\"'
761 * - '\'s that are not followed by a '"' can be left as is
762 * 'a\b' == 'a\b'
763 * 'a\\b' == 'a\\b'
765 static BOOL build_command_line( WCHAR **argv )
767 int len;
768 WCHAR **arg;
769 LPWSTR p;
770 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
772 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
774 len = 0;
775 for (arg = argv; *arg; arg++)
777 BOOL has_space;
778 int bcount;
779 WCHAR* a;
781 has_space=FALSE;
782 bcount=0;
783 a=*arg;
784 if( !*a ) has_space=TRUE;
785 while (*a!='\0') {
786 if (*a=='\\') {
787 bcount++;
788 } else {
789 if (*a==' ' || *a=='\t') {
790 has_space=TRUE;
791 } else if (*a=='"') {
792 /* doubling of '\' preceding a '"',
793 * plus escaping of said '"'
795 len+=2*bcount+1;
797 bcount=0;
799 a++;
801 len+=(a-*arg)+1 /* for the separating space */;
802 if (has_space)
803 len+=2+bcount; /* for the quotes and doubling of '\' preceding the closing quote */
806 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
807 return FALSE;
809 p = rupp->CommandLine.Buffer;
810 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
811 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
812 for (arg = argv; *arg; arg++)
814 BOOL has_space,has_quote;
815 WCHAR* a;
816 int bcount;
818 /* Check for quotes and spaces in this argument */
819 has_space=has_quote=FALSE;
820 a=*arg;
821 if( !*a ) has_space=TRUE;
822 while (*a!='\0') {
823 if (*a==' ' || *a=='\t') {
824 has_space=TRUE;
825 if (has_quote)
826 break;
827 } else if (*a=='"') {
828 has_quote=TRUE;
829 if (has_space)
830 break;
832 a++;
835 /* Now transfer it to the command line */
836 if (has_space)
837 *p++='"';
838 if (has_quote || has_space) {
839 bcount=0;
840 a=*arg;
841 while (*a!='\0') {
842 if (*a=='\\') {
843 *p++=*a;
844 bcount++;
845 } else {
846 if (*a=='"') {
847 int i;
849 /* Double all the '\\' preceding this '"', plus one */
850 for (i=0;i<=bcount;i++)
851 *p++='\\';
852 *p++='"';
853 } else {
854 *p++=*a;
856 bcount=0;
858 a++;
860 } else {
861 WCHAR* x = *arg;
862 while ((*p=*x++)) p++;
864 if (has_space) {
865 int i;
867 /* Double all the '\' preceding the closing quote */
868 for (i=0;i<bcount;i++)
869 *p++='\\';
870 *p++='"';
872 *p++=' ';
874 if (p > rupp->CommandLine.Buffer)
875 p--; /* remove last space */
876 *p = '\0';
878 return TRUE;
882 /***********************************************************************
883 * init_current_directory
885 * Initialize the current directory from the Unix cwd or the parent info.
887 static void init_current_directory( CURDIR *cur_dir )
889 UNICODE_STRING dir_str;
890 const char *pwd;
891 char *cwd;
892 int size;
894 /* if we received a cur dir from the parent, try this first */
896 if (cur_dir->DosPath.Length)
898 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
901 /* now try to get it from the Unix cwd */
903 for (size = 256; ; size *= 2)
905 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
906 if (getcwd( cwd, size )) break;
907 HeapFree( GetProcessHeap(), 0, cwd );
908 if (errno == ERANGE) continue;
909 cwd = NULL;
910 break;
913 /* try to use PWD if it is valid, so that we don't resolve symlinks */
915 pwd = getenv( "PWD" );
916 if (cwd)
918 struct stat st1, st2;
920 if (!pwd || stat( pwd, &st1 ) == -1 ||
921 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
922 pwd = cwd;
925 if (pwd)
927 ANSI_STRING unix_name;
928 UNICODE_STRING nt_name;
929 RtlInitAnsiString( &unix_name, pwd );
930 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
932 UNICODE_STRING dos_path;
933 /* skip the \??\ prefix, nt_name is 0 terminated */
934 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
935 RtlSetCurrentDirectory_U( &dos_path );
936 RtlFreeUnicodeString( &nt_name );
940 if (!cur_dir->DosPath.Length) /* still not initialized */
942 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
943 "starting in the Windows directory.\n", cwd ? cwd : "" );
944 RtlInitUnicodeString( &dir_str, DIR_Windows );
945 RtlSetCurrentDirectory_U( &dir_str );
947 HeapFree( GetProcessHeap(), 0, cwd );
949 done:
950 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
954 /***********************************************************************
955 * init_windows_dirs
957 * Initialize the windows and system directories from the environment.
959 static void init_windows_dirs(void)
961 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
962 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
963 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
964 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
965 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
967 DWORD len;
968 WCHAR *buffer;
970 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
972 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
973 GetEnvironmentVariableW( windirW, buffer, len );
974 DIR_Windows = buffer;
976 else DIR_Windows = default_windirW;
978 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
980 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
981 GetEnvironmentVariableW( winsysdirW, buffer, len );
982 DIR_System = buffer;
984 else
986 len = strlenW( DIR_Windows );
987 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
988 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
989 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
990 DIR_System = buffer;
993 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
994 ERR( "directory %s could not be created, error %u\n",
995 debugstr_w(DIR_Windows), GetLastError() );
996 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
997 ERR( "directory %s could not be created, error %u\n",
998 debugstr_w(DIR_System), GetLastError() );
1000 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
1002 len = strlenW( DIR_Windows );
1003 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
1004 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
1005 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
1006 DIR_SysWow64 = buffer;
1007 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1008 ERR( "directory %s could not be created, error %u\n",
1009 debugstr_w(DIR_SysWow64), GetLastError() );
1012 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
1013 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
1017 /***********************************************************************
1018 * start_wineboot
1020 * Start the wineboot process if necessary. Return the handles to wait on.
1022 static void start_wineboot( HANDLE handles[2] )
1024 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1026 handles[1] = 0;
1027 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1029 ERR( "failed to create wineboot event, expect trouble\n" );
1030 return;
1032 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1034 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1035 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1036 STARTUPINFOW si;
1037 PROCESS_INFORMATION pi;
1038 void *redir;
1039 WCHAR app[MAX_PATH];
1040 WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
1042 memset( &si, 0, sizeof(si) );
1043 si.cb = sizeof(si);
1044 si.dwFlags = STARTF_USESTDHANDLES;
1045 si.hStdInput = 0;
1046 si.hStdOutput = 0;
1047 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1049 GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
1050 lstrcatW( app, wineboot );
1052 Wow64DisableWow64FsRedirection( &redir );
1053 strcpyW( cmdline, app );
1054 strcatW( cmdline, args );
1055 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1057 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1058 CloseHandle( pi.hThread );
1059 handles[1] = pi.hProcess;
1061 else
1063 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1064 CloseHandle( handles[0] );
1065 handles[0] = 0;
1067 Wow64RevertWow64FsRedirection( redir );
1072 #ifdef __i386__
1073 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1074 __ASM_GLOBAL_FUNC( call_process_entry,
1075 "pushl %ebp\n\t"
1076 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1077 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1078 "movl %esp,%ebp\n\t"
1079 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1080 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1081 "pushl 8(%ebp)\n\t"
1082 "call *12(%ebp)\n\t"
1083 "leave\n\t"
1084 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1085 __ASM_CFI(".cfi_same_value %ebp\n\t")
1086 "ret" )
1088 extern void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb ) DECLSPEC_HIDDEN;
1089 extern void WINAPI start_process_wrapper(void) DECLSPEC_HIDDEN;
1090 __ASM_GLOBAL_FUNC( start_process_wrapper,
1091 "pushl %ebp\n\t"
1092 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1093 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1094 "movl %esp,%ebp\n\t"
1095 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1096 "pushl %ebx\n\t" /* arg */
1097 "pushl %eax\n\t" /* entry */
1098 "call " __ASM_NAME("start_process") )
1099 #else
1100 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1102 return entry( peb );
1104 static void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb );
1105 #define start_process_wrapper start_process
1106 #endif
1108 /***********************************************************************
1109 * start_process
1111 * Startup routine of a new process. Runs on the new process stack.
1113 void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb )
1115 BOOL being_debugged;
1117 if (!entry)
1119 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1120 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1121 ExitThread( 1 );
1124 TRACE_(relay)( "\1Starting process %s (entryproc=%p)\n",
1125 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1127 __TRY
1129 if (!CheckRemoteDebuggerPresent( GetCurrentProcess(), &being_debugged ))
1130 being_debugged = FALSE;
1132 SetLastError( 0 ); /* clear error code */
1133 if (being_debugged) DbgBreakPoint();
1134 ExitThread( call_process_entry( peb, entry ));
1136 __EXCEPT(UnhandledExceptionFilter)
1138 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1140 __ENDTRY
1141 abort(); /* should not be reached */
1145 /***********************************************************************
1146 * set_process_name
1148 * Change the process name in the ps output.
1150 static void set_process_name( int argc, char *argv[] )
1152 BOOL shift_strings;
1153 char *p, *name;
1154 int i;
1156 #ifdef HAVE_SETPROCTITLE
1157 setproctitle("-%s", argv[1]);
1158 shift_strings = FALSE;
1159 #else
1160 p = argv[0];
1162 shift_strings = (argc >= 2);
1163 for (i = 1; i < argc; i++)
1165 p += strlen(p) + 1;
1166 if (p != argv[i])
1168 shift_strings = FALSE;
1169 break;
1172 #endif
1174 if (shift_strings)
1176 int offset = argv[1] - argv[0];
1177 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1178 memmove( argv[0], argv[1], end - argv[1] );
1179 memset( end - offset, 0, offset );
1180 for (i = 1; i < argc; i++)
1181 argv[i-1] = argv[i] - offset;
1182 argv[i-1] = NULL;
1184 else
1186 /* remove argv[0] */
1187 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1190 name = argv[0];
1191 if ((p = strrchr( name, '\\' ))) name = p + 1;
1192 if ((p = strrchr( name, '/' ))) name = p + 1;
1194 #if defined(HAVE_SETPROGNAME)
1195 setprogname( name );
1196 #endif
1198 #ifdef HAVE_PRCTL
1199 #ifndef PR_SET_NAME
1200 # define PR_SET_NAME 15
1201 #endif
1202 prctl( PR_SET_NAME, name );
1203 #endif /* HAVE_PRCTL */
1207 /***********************************************************************
1208 * __wine_kernel_init
1210 * Wine initialisation: load and start the main exe file.
1212 void CDECL __wine_kernel_init(void)
1214 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1215 static const WCHAR dotW[] = {'.',0};
1217 WCHAR *p, main_exe_name[MAX_PATH+1];
1218 PEB *peb = NtCurrentTeb()->Peb;
1219 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1220 HANDLE boot_events[2];
1221 BOOL got_environment = TRUE;
1223 /* Initialize everything */
1225 setbuf(stdout,NULL);
1226 setbuf(stderr,NULL);
1227 kernel32_handle = GetModuleHandleW(kernel32W);
1228 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1230 LOCALE_Init();
1232 if (!params->Environment)
1234 /* Copy the parent environment */
1235 if (!build_initial_environment()) exit(1);
1237 /* convert old configuration to new format */
1238 convert_old_config();
1240 got_environment = set_registry_environment( FALSE );
1241 set_additional_environment();
1244 init_windows_dirs();
1245 init_current_directory( &params->CurrentDirectory );
1247 set_process_name( __wine_main_argc, __wine_main_argv );
1248 set_library_wargv( __wine_main_argv );
1249 boot_events[0] = boot_events[1] = 0;
1251 if (peb->ProcessParameters->ImagePathName.Buffer)
1253 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1255 else
1257 struct binary_info binary_info;
1259 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1260 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1262 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1263 ExitProcess( GetLastError() );
1265 update_library_argv0( main_exe_name );
1266 if (!build_command_line( __wine_main_wargv )) goto error;
1267 start_wineboot( boot_events );
1270 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1271 p = strrchrW( main_exe_name, '.' );
1272 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1274 TRACE( "starting process name=%s argv[0]=%s\n",
1275 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1277 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1278 MODULE_get_dll_load_path( main_exe_name, -1 ));
1280 if (boot_events[0])
1282 DWORD timeout = 2 * 60 * 1000, count = 1;
1284 if (boot_events[1]) count++;
1285 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1286 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1287 ERR( "boot event wait timed out\n" );
1288 CloseHandle( boot_events[0] );
1289 if (boot_events[1]) CloseHandle( boot_events[1] );
1290 /* reload environment now that wineboot has run */
1291 set_registry_environment( got_environment );
1292 set_additional_environment();
1294 set_wow64_environment();
1296 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1298 DWORD_PTR args[1];
1299 WCHAR msgW[1024];
1300 char msg[1024];
1301 DWORD error = GetLastError();
1303 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1304 if (error == ERROR_BAD_EXE_FORMAT ||
1305 error == ERROR_INVALID_ADDRESS ||
1306 error == ERROR_NOT_ENOUGH_MEMORY)
1308 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1309 /* if we get back here, it failed */
1311 else if (error == ERROR_MOD_NOT_FOUND)
1313 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1314 else p = main_exe_name;
1315 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1317 /* args 1 and 2 are --app-name full_path */
1318 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1319 debugstr_w(__wine_main_wargv[3]) );
1320 ExitProcess( ERROR_BAD_EXE_FORMAT );
1322 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1323 ExitProcess( ERROR_FILE_NOT_FOUND );
1325 args[0] = (DWORD_PTR)main_exe_name;
1326 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1327 NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1328 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1329 MESSAGE( "wine: %s", msg );
1330 ExitProcess( error );
1333 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1335 LdrInitializeThunk( start_process_wrapper, 0, 0, 0 );
1337 error:
1338 ExitProcess( GetLastError() );
1342 /***********************************************************************
1343 * build_argv
1345 * Build an argv array from a command-line.
1346 * 'reserved' is the number of args to reserve before the first one.
1348 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1350 int argc;
1351 char** argv;
1352 char *arg,*s,*d,*cmdline;
1353 int in_quotes,bcount,len;
1355 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1356 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1357 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1359 argc=reserved+1;
1360 bcount=0;
1361 in_quotes=0;
1362 s=cmdline;
1363 while (1) {
1364 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1365 /* space */
1366 argc++;
1367 /* skip the remaining spaces */
1368 while (*s==' ' || *s=='\t') {
1369 s++;
1371 if (*s=='\0')
1372 break;
1373 bcount=0;
1374 continue;
1375 } else if (*s=='\\') {
1376 /* '\', count them */
1377 bcount++;
1378 } else if ((*s=='"') && ((bcount & 1)==0)) {
1379 /* unescaped '"' */
1380 in_quotes=!in_quotes;
1381 bcount=0;
1382 } else {
1383 /* a regular character */
1384 bcount=0;
1386 s++;
1388 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1390 HeapFree( GetProcessHeap(), 0, cmdline );
1391 return NULL;
1394 arg = d = s = (char *)(argv + argc);
1395 memcpy( d, cmdline, len );
1396 bcount=0;
1397 in_quotes=0;
1398 argc=reserved;
1399 while (*s) {
1400 if ((*s==' ' || *s=='\t') && !in_quotes) {
1401 /* Close the argument and copy it */
1402 *d=0;
1403 argv[argc++]=arg;
1405 /* skip the remaining spaces */
1406 do {
1407 s++;
1408 } while (*s==' ' || *s=='\t');
1410 /* Start with a new argument */
1411 arg=d=s;
1412 bcount=0;
1413 } else if (*s=='\\') {
1414 /* '\\' */
1415 *d++=*s++;
1416 bcount++;
1417 } else if (*s=='"') {
1418 /* '"' */
1419 if ((bcount & 1)==0) {
1420 /* Preceded by an even number of '\', this is half that
1421 * number of '\', plus a '"' which we discard.
1423 d-=bcount/2;
1424 s++;
1425 in_quotes=!in_quotes;
1426 } else {
1427 /* Preceded by an odd number of '\', this is half that
1428 * number of '\' followed by a '"'
1430 d=d-bcount/2-1;
1431 *d++='"';
1432 s++;
1434 bcount=0;
1435 } else {
1436 /* a regular character */
1437 *d++=*s++;
1438 bcount=0;
1441 if (*arg) {
1442 *d='\0';
1443 argv[argc++]=arg;
1445 argv[argc]=NULL;
1447 HeapFree( GetProcessHeap(), 0, cmdline );
1448 return argv;
1452 /***********************************************************************
1453 * build_envp
1455 * Build the environment of a new child process.
1457 static char **build_envp( const WCHAR *envW )
1459 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1461 const WCHAR *end;
1462 char **envp;
1463 char *env, *p;
1464 int count = 1, length;
1465 unsigned int i;
1467 for (end = envW; *end; count++) end += strlenW(end) + 1;
1468 end++;
1469 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1470 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1471 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1473 for (p = env; *p; p += strlen(p) + 1)
1474 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1476 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1478 if (!(p = getenv(unix_vars[i]))) continue;
1479 length += strlen(unix_vars[i]) + strlen(p) + 2;
1480 count++;
1483 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1485 char **envptr = envp;
1486 char *dst = (char *)(envp + count);
1488 /* some variables must not be modified, so we get them directly from the unix env */
1489 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1491 if (!(p = getenv(unix_vars[i]))) continue;
1492 *envptr++ = strcpy( dst, unix_vars[i] );
1493 strcat( dst, "=" );
1494 strcat( dst, p );
1495 dst += strlen(dst) + 1;
1498 /* now put the Windows environment strings */
1499 for (p = env; *p; p += strlen(p) + 1)
1501 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1502 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1503 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1504 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1505 if (is_special_env_var( p )) /* prefix it with "WINE" */
1507 *envptr++ = strcpy( dst, "WINE" );
1508 strcat( dst, p );
1510 else
1512 *envptr++ = strcpy( dst, p );
1514 dst += strlen(dst) + 1;
1516 *envptr = 0;
1518 HeapFree( GetProcessHeap(), 0, env );
1519 return envp;
1523 /***********************************************************************
1524 * fork_and_exec
1526 * Fork and exec a new Unix binary, checking for errors.
1528 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1529 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1531 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1532 int pid, err;
1533 char **argv, **envp;
1535 if (!env) env = GetEnvironmentStringsW();
1537 #ifdef HAVE_PIPE2
1538 if (pipe2( fd, O_CLOEXEC ) == -1)
1539 #endif
1541 if (pipe(fd) == -1)
1543 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1544 return -1;
1546 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1547 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1550 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1552 HANDLE hstdin, hstdout, hstderr;
1554 if (startup->dwFlags & STARTF_USESTDHANDLES)
1556 hstdin = startup->hStdInput;
1557 hstdout = startup->hStdOutput;
1558 hstderr = startup->hStdError;
1560 else
1562 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1563 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1564 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1567 if (is_console_handle( hstdin ))
1568 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1569 if (is_console_handle( hstdout ))
1570 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1571 if (is_console_handle( hstderr ))
1572 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1573 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1574 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1575 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1578 argv = build_argv( cmdline, 0 );
1579 envp = build_envp( env );
1581 if (!(pid = fork())) /* child */
1583 if (!(pid = fork())) /* grandchild */
1585 close( fd[0] );
1587 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1589 int nullfd = open( "/dev/null", O_RDWR );
1590 setsid();
1591 /* close stdin and stdout */
1592 if (nullfd != -1)
1594 dup2( nullfd, 0 );
1595 dup2( nullfd, 1 );
1596 close( nullfd );
1599 else
1601 if (stdin_fd != -1)
1603 dup2( stdin_fd, 0 );
1604 close( stdin_fd );
1606 if (stdout_fd != -1)
1608 dup2( stdout_fd, 1 );
1609 close( stdout_fd );
1611 if (stderr_fd != -1)
1613 dup2( stderr_fd, 2 );
1614 close( stderr_fd );
1618 /* Reset signals that we previously set to SIG_IGN */
1619 signal( SIGPIPE, SIG_DFL );
1621 if (newdir) chdir(newdir);
1623 if (argv && envp) execve( filename, argv, envp );
1626 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1628 err = errno;
1629 write( fd[1], &err, sizeof(err) );
1630 _exit(1);
1633 _exit(0); /* child if fork succeeded */
1635 HeapFree( GetProcessHeap(), 0, argv );
1636 HeapFree( GetProcessHeap(), 0, envp );
1637 if (stdin_fd != -1) close( stdin_fd );
1638 if (stdout_fd != -1) close( stdout_fd );
1639 if (stderr_fd != -1) close( stderr_fd );
1640 close( fd[1] );
1641 if (pid != -1)
1643 /* reap child */
1644 do {
1645 err = waitpid(pid, NULL, 0);
1646 } while (err < 0 && errno == EINTR);
1648 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1650 errno = err;
1651 pid = -1;
1654 if (pid == -1) FILE_SetDosError();
1655 close( fd[0] );
1656 return pid;
1660 static inline DWORD append_string( void **ptr, const WCHAR *str )
1662 DWORD len = strlenW( str );
1663 memcpy( *ptr, str, len * sizeof(WCHAR) );
1664 *ptr = (WCHAR *)*ptr + len;
1665 return len * sizeof(WCHAR);
1668 /***********************************************************************
1669 * create_startup_info
1671 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1672 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1673 const STARTUPINFOW *startup, DWORD *info_size )
1675 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1676 const WCHAR *title;
1677 startup_info_t *info;
1678 DWORD size;
1679 void *ptr;
1680 UNICODE_STRING newdir;
1681 WCHAR imagepath[MAX_PATH];
1682 HANDLE hstdin, hstdout, hstderr;
1684 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1685 lstrcpynW( imagepath, filename, MAX_PATH );
1686 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1687 lstrcpynW( imagepath, filename, MAX_PATH );
1689 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1691 newdir.Buffer = NULL;
1692 if (cur_dir)
1694 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1695 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1696 else
1697 cur_dir = NULL;
1699 if (!cur_dir)
1701 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1702 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1703 else
1704 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1706 title = startup->lpTitle ? startup->lpTitle : imagepath;
1708 size = sizeof(*info);
1709 size += strlenW( cur_dir ) * sizeof(WCHAR);
1710 size += cur_params->DllPath.Length;
1711 size += strlenW( imagepath ) * sizeof(WCHAR);
1712 size += strlenW( cmdline ) * sizeof(WCHAR);
1713 size += strlenW( title ) * sizeof(WCHAR);
1714 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1715 /* FIXME: shellinfo */
1716 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1717 size = (size + 1) & ~1;
1718 *info_size = size;
1720 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1722 info->console_flags = cur_params->ConsoleFlags;
1723 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1724 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1726 if (startup->dwFlags & STARTF_USESTDHANDLES)
1728 hstdin = startup->hStdInput;
1729 hstdout = startup->hStdOutput;
1730 hstderr = startup->hStdError;
1732 else if (flags & DETACHED_PROCESS)
1734 hstdin = INVALID_HANDLE_VALUE;
1735 hstdout = INVALID_HANDLE_VALUE;
1736 hstderr = INVALID_HANDLE_VALUE;
1738 else
1740 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1741 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1742 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1744 info->hstdin = wine_server_obj_handle( hstdin );
1745 info->hstdout = wine_server_obj_handle( hstdout );
1746 info->hstderr = wine_server_obj_handle( hstderr );
1747 if ((flags & CREATE_NEW_CONSOLE) != 0)
1749 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1750 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1751 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1752 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1754 else
1756 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1757 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1758 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1761 info->x = startup->dwX;
1762 info->y = startup->dwY;
1763 info->xsize = startup->dwXSize;
1764 info->ysize = startup->dwYSize;
1765 info->xchars = startup->dwXCountChars;
1766 info->ychars = startup->dwYCountChars;
1767 info->attribute = startup->dwFillAttribute;
1768 info->flags = startup->dwFlags;
1769 info->show = startup->wShowWindow;
1771 ptr = info + 1;
1772 info->curdir_len = append_string( &ptr, cur_dir );
1773 info->dllpath_len = cur_params->DllPath.Length;
1774 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1775 ptr = (char *)ptr + cur_params->DllPath.Length;
1776 info->imagepath_len = append_string( &ptr, imagepath );
1777 info->cmdline_len = append_string( &ptr, cmdline );
1778 info->title_len = append_string( &ptr, title );
1779 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1780 if (startup->lpReserved2 && startup->cbReserved2)
1782 info->runtime_len = startup->cbReserved2;
1783 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1786 done:
1787 RtlFreeUnicodeString( &newdir );
1788 return info;
1791 /***********************************************************************
1792 * get_alternate_loader
1794 * Get the name of the alternate (32 or 64 bit) Wine loader.
1796 static const char *get_alternate_loader( char **ret_env )
1798 char *env;
1799 const char *loader = NULL;
1800 const char *loader_env = getenv( "WINELOADER" );
1802 *ret_env = NULL;
1804 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1806 if (loader_env)
1808 int len = strlen( loader_env );
1809 if (!is_win64)
1811 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1812 strcpy( env, "WINELOADER=" );
1813 strcat( env, loader_env );
1814 strcat( env, "64" );
1816 else
1818 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1819 strcpy( env, "WINELOADER=" );
1820 strcat( env, loader_env );
1821 len += sizeof("WINELOADER=") - 1;
1822 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1824 if (!loader)
1826 if ((loader = strrchr( env, '/' ))) loader++;
1827 else loader = env;
1829 *ret_env = env;
1831 if (!loader) loader = is_win64 ? "wine" : "wine64";
1832 return loader;
1835 #ifdef __APPLE__
1836 /***********************************************************************
1837 * terminate_main_thread
1839 * On some versions of Mac OS X, the execve system call fails with
1840 * ENOTSUP if the process has multiple threads. Wine is always multi-
1841 * threaded on Mac OS X because it specifically reserves the main thread
1842 * for use by the system frameworks (see apple_main_thread() in
1843 * libs/wine/loader.c). So, when we need to exec without first forking,
1844 * we need to terminate the main thread first. We do this by installing
1845 * a custom run loop source onto the main run loop and signaling it.
1846 * The source's "perform" callback is pthread_exit and it will be
1847 * executed on the main thread, terminating it.
1849 * Returns TRUE if there's still hope the main thread has terminated or
1850 * will soon. Return FALSE if we've given up.
1852 static BOOL terminate_main_thread(void)
1854 static int delayms;
1856 if (!delayms)
1858 CFRunLoopSourceContext source_context = { 0 };
1859 CFRunLoopSourceRef source;
1861 source_context.perform = pthread_exit;
1862 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1863 return FALSE;
1865 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1866 CFRunLoopSourceSignal( source );
1867 CFRunLoopWakeUp( CFRunLoopGetMain() );
1868 CFRelease( source );
1870 delayms = 20;
1873 if (delayms > 1000)
1874 return FALSE;
1876 usleep(delayms * 1000);
1877 delayms *= 2;
1879 return TRUE;
1881 #endif
1883 /***********************************************************************
1884 * get_process_cpu
1886 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1888 switch (binary_info->arch)
1890 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1891 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1892 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1893 case IMAGE_FILE_MACHINE_ARM:
1894 case IMAGE_FILE_MACHINE_THUMB:
1895 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1896 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1898 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1899 return -1;
1902 /***********************************************************************
1903 * exec_loader
1905 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1906 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1907 const struct binary_info *binary_info, int exec_only )
1909 pid_t pid;
1910 char *wineloader = NULL;
1911 const char *loader = NULL;
1912 char **argv;
1914 argv = build_argv( cmd_line, 1 );
1916 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1917 loader = get_alternate_loader( &wineloader );
1919 if (exec_only || !(pid = fork())) /* child */
1921 if (exec_only || !(pid = fork())) /* grandchild */
1923 char preloader_reserve[64], socket_env[64];
1925 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1927 int fd = open( "/dev/null", O_RDWR );
1928 setsid();
1929 /* close stdin and stdout */
1930 if (fd != -1)
1932 dup2( fd, 0 );
1933 dup2( fd, 1 );
1934 close( fd );
1937 else
1939 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1940 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1943 if (stdin_fd != -1) close( stdin_fd );
1944 if (stdout_fd != -1) close( stdout_fd );
1946 /* Reset signals that we previously set to SIG_IGN */
1947 signal( SIGPIPE, SIG_DFL );
1949 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1950 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
1951 (ULONG)(binary_info->res_start >> 32), (ULONG)binary_info->res_start,
1952 (ULONG)(binary_info->res_end >> 32), (ULONG)binary_info->res_end );
1954 putenv( preloader_reserve );
1955 putenv( socket_env );
1956 if (winedebug) putenv( winedebug );
1957 if (wineloader) putenv( wineloader );
1958 if (unixdir) chdir(unixdir);
1960 if (argv)
1964 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1966 #ifdef __APPLE__
1967 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1968 #else
1969 while (0);
1970 #endif
1972 _exit(1);
1975 _exit(pid == -1);
1978 if (pid != -1)
1980 /* reap child */
1981 pid_t wret;
1982 do {
1983 wret = waitpid(pid, NULL, 0);
1984 } while (wret < 0 && errno == EINTR);
1987 HeapFree( GetProcessHeap(), 0, wineloader );
1988 HeapFree( GetProcessHeap(), 0, argv );
1989 return pid;
1992 /***********************************************************************
1993 * create_process
1995 * Create a new process. If hFile is a valid handle we have an exe
1996 * file, otherwise it is a Winelib app.
1998 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1999 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2000 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2001 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2002 const struct binary_info *binary_info, int exec_only )
2004 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
2005 NTSTATUS status;
2006 BOOL success = FALSE;
2007 HANDLE process_info;
2008 WCHAR *env_end;
2009 char *winedebug = NULL;
2010 startup_info_t *startup_info;
2011 DWORD startup_info_size;
2012 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
2013 pid_t pid;
2014 int err, cpu;
2016 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
2018 SetLastError( ERROR_BAD_EXE_FORMAT );
2019 return FALSE;
2022 /* create the socket for the new process */
2024 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2026 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2027 return FALSE;
2029 #ifdef SO_PASSCRED
2030 else
2032 int enable = 1;
2033 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2035 #endif
2037 if (exec_only) /* things are much simpler in this case */
2039 wine_server_send_fd( socketfd[1] );
2040 close( socketfd[1] );
2041 SERVER_START_REQ( new_process )
2043 req->create_flags = flags;
2044 req->socket_fd = socketfd[1];
2045 req->exe_file = wine_server_obj_handle( hFile );
2046 req->cpu = cpu;
2047 status = wine_server_call( req );
2049 SERVER_END_REQ;
2051 switch (status)
2053 case STATUS_INVALID_IMAGE_WIN_64:
2054 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2055 break;
2056 case STATUS_INVALID_IMAGE_FORMAT:
2057 ERR( "%s not supported on this installation (%s binary)\n",
2058 debugstr_w(filename), cpu_names[cpu] );
2059 break;
2060 case STATUS_SUCCESS:
2061 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2062 winedebug, binary_info, TRUE );
2064 close( socketfd[0] );
2065 SetLastError( RtlNtStatusToDosError( status ));
2066 return FALSE;
2069 RtlAcquirePebLock();
2071 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2072 &startup_info_size )))
2074 RtlReleasePebLock();
2075 close( socketfd[0] );
2076 close( socketfd[1] );
2077 return FALSE;
2079 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2080 env_end = env;
2081 while (*env_end)
2083 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2084 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
2086 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2087 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2088 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2090 env_end += strlenW(env_end) + 1;
2092 env_end++;
2094 wine_server_send_fd( socketfd[1] );
2095 close( socketfd[1] );
2097 /* create the process on the server side */
2099 SERVER_START_REQ( new_process )
2101 req->inherit_all = inherit;
2102 req->create_flags = flags;
2103 req->socket_fd = socketfd[1];
2104 req->exe_file = wine_server_obj_handle( hFile );
2105 req->process_access = PROCESS_ALL_ACCESS;
2106 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2107 req->thread_access = THREAD_ALL_ACCESS;
2108 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
2109 req->cpu = cpu;
2110 req->info_size = startup_info_size;
2112 wine_server_add_data( req, startup_info, startup_info_size );
2113 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2114 if (!(status = wine_server_call( req )))
2116 info->dwProcessId = (DWORD)reply->pid;
2117 info->dwThreadId = (DWORD)reply->tid;
2118 info->hProcess = wine_server_ptr_handle( reply->phandle );
2119 info->hThread = wine_server_ptr_handle( reply->thandle );
2121 process_info = wine_server_ptr_handle( reply->info );
2123 SERVER_END_REQ;
2125 RtlReleasePebLock();
2126 if (status)
2128 switch (status)
2130 case STATUS_INVALID_IMAGE_WIN_64:
2131 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2132 break;
2133 case STATUS_INVALID_IMAGE_FORMAT:
2134 ERR( "%s not supported on this installation (%s binary)\n",
2135 debugstr_w(filename), cpu_names[cpu] );
2136 break;
2138 close( socketfd[0] );
2139 HeapFree( GetProcessHeap(), 0, startup_info );
2140 HeapFree( GetProcessHeap(), 0, winedebug );
2141 SetLastError( RtlNtStatusToDosError( status ));
2142 return FALSE;
2145 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2147 if (startup_info->hstdin)
2148 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2149 FILE_READ_DATA, &stdin_fd, NULL );
2150 if (startup_info->hstdout)
2151 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2152 FILE_WRITE_DATA, &stdout_fd, NULL );
2154 HeapFree( GetProcessHeap(), 0, startup_info );
2156 /* create the child process */
2158 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2159 winedebug, binary_info, FALSE );
2161 if (stdin_fd != -1) close( stdin_fd );
2162 if (stdout_fd != -1) close( stdout_fd );
2163 close( socketfd[0] );
2164 HeapFree( GetProcessHeap(), 0, winedebug );
2165 if (pid == -1)
2167 FILE_SetDosError();
2168 goto error;
2171 /* wait for the new process info to be ready */
2173 WaitForSingleObject( process_info, INFINITE );
2174 SERVER_START_REQ( get_new_process_info )
2176 req->info = wine_server_obj_handle( process_info );
2177 wine_server_call( req );
2178 success = reply->success;
2179 err = reply->exit_code;
2181 SERVER_END_REQ;
2183 if (!success)
2185 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2186 goto error;
2188 CloseHandle( process_info );
2189 return success;
2191 error:
2192 CloseHandle( process_info );
2193 CloseHandle( info->hProcess );
2194 CloseHandle( info->hThread );
2195 info->hProcess = info->hThread = 0;
2196 info->dwProcessId = info->dwThreadId = 0;
2197 return FALSE;
2201 /***********************************************************************
2202 * create_vdm_process
2204 * Create a new VDM process for a 16-bit or DOS application.
2206 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2207 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2208 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2209 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2210 const struct binary_info *binary_info, int exec_only )
2212 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2214 BOOL ret;
2215 WCHAR buffer[MAX_PATH];
2216 LPWSTR new_cmd_line;
2218 if (!(ret = GetFullPathNameW(filename, MAX_PATH, buffer, NULL)))
2219 return FALSE;
2221 new_cmd_line = HeapAlloc(GetProcessHeap(), 0,
2222 (strlenW(buffer) + strlenW(cmd_line) + 30) * sizeof(WCHAR));
2224 if (!new_cmd_line)
2226 SetLastError( ERROR_OUTOFMEMORY );
2227 return FALSE;
2229 sprintfW(new_cmd_line, argsW, winevdmW, buffer, cmd_line);
2230 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2231 flags, startup, info, unixdir, binary_info, exec_only );
2232 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2233 return ret;
2237 /***********************************************************************
2238 * create_cmd_process
2240 * Create a new cmd shell process for a .BAT file.
2242 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2243 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2244 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2245 LPPROCESS_INFORMATION info )
2248 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2249 static const WCHAR slashcW[] = {' ','/','c',' ',0};
2250 WCHAR comspec[MAX_PATH];
2251 WCHAR *newcmdline;
2252 BOOL ret;
2254 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
2255 return FALSE;
2256 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2257 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
2258 return FALSE;
2260 strcpyW( newcmdline, comspec );
2261 strcatW( newcmdline, slashcW );
2262 strcatW( newcmdline, cmd_line );
2263 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2264 flags, env, cur_dir, startup, info );
2265 HeapFree( GetProcessHeap(), 0, newcmdline );
2266 return ret;
2270 /*************************************************************************
2271 * get_file_name
2273 * Helper for CreateProcess: retrieve the file name to load from the
2274 * app name and command line. Store the file name in buffer, and
2275 * return a possibly modified command line.
2276 * Also returns a handle to the opened file if it's a Windows binary.
2278 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2279 int buflen, HANDLE *handle, struct binary_info *binary_info )
2281 static const WCHAR quotesW[] = {'"','%','s','"',0};
2283 WCHAR *name, *pos, *first_space, *ret = NULL;
2284 const WCHAR *p;
2286 /* if we have an app name, everything is easy */
2288 if (appname)
2290 /* use the unmodified app name as file name */
2291 lstrcpynW( buffer, appname, buflen );
2292 *handle = open_exe_file( buffer, binary_info );
2293 if (!(ret = cmdline) || !cmdline[0])
2295 /* no command-line, create one */
2296 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2297 sprintfW( ret, quotesW, appname );
2299 return ret;
2302 /* first check for a quoted file name */
2304 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2306 int len = p - cmdline - 1;
2307 /* extract the quoted portion as file name */
2308 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2309 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2310 name[len] = 0;
2312 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2313 ret = cmdline; /* no change necessary */
2314 goto done;
2317 /* now try the command-line word by word */
2319 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2320 return NULL;
2321 pos = name;
2322 p = cmdline;
2323 first_space = NULL;
2325 for (;;)
2327 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2328 *pos = 0;
2329 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2331 ret = cmdline;
2332 break;
2334 if (!first_space) first_space = pos;
2335 if (!(*pos++ = *p++)) break;
2338 if (!ret)
2340 SetLastError( ERROR_FILE_NOT_FOUND );
2342 else if (first_space) /* build a new command-line with quotes */
2344 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2345 goto done;
2346 sprintfW( ret, quotesW, name );
2347 strcatW( ret, p );
2350 done:
2351 HeapFree( GetProcessHeap(), 0, name );
2352 return ret;
2356 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2357 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2358 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2359 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2360 LPPROCESS_INFORMATION info )
2362 BOOL retv = FALSE;
2363 HANDLE hFile = 0;
2364 char *unixdir = NULL;
2365 WCHAR name[MAX_PATH];
2366 WCHAR *tidy_cmdline, *p, *envW = env;
2367 struct binary_info binary_info;
2369 /* Process the AppName and/or CmdLine to get module name and path */
2371 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2373 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2374 &hFile, &binary_info )))
2375 return FALSE;
2376 if (hFile == INVALID_HANDLE_VALUE) goto done;
2378 /* Warn if unsupported features are used */
2380 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2381 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2382 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2383 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2384 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2386 if (cur_dir)
2388 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2390 SetLastError(ERROR_DIRECTORY);
2391 goto done;
2394 else
2396 WCHAR buf[MAX_PATH];
2397 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2400 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2402 char *e = env;
2403 DWORD lenW;
2405 while (*e) e += strlen(e) + 1;
2406 e++; /* final null */
2407 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2408 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2409 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2410 flags |= CREATE_UNICODE_ENVIRONMENT;
2413 info->hThread = info->hProcess = 0;
2414 info->dwProcessId = info->dwThreadId = 0;
2416 if (binary_info.flags & BINARY_FLAG_DLL)
2418 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2419 SetLastError( ERROR_BAD_EXE_FORMAT );
2421 else switch (binary_info.type)
2423 case BINARY_PE:
2424 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x%s)\n",
2425 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2426 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2427 binary_info.arch, (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2428 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2429 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2430 break;
2431 case BINARY_OS216:
2432 case BINARY_WIN16:
2433 case BINARY_DOS:
2434 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2435 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2436 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2437 break;
2438 case BINARY_UNIX_LIB:
2439 TRACE( "starting %s as %d-bit Winelib app\n",
2440 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2441 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2442 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2443 break;
2444 case BINARY_UNKNOWN:
2445 /* check for .com or .bat extension */
2446 if ((p = strrchrW( name, '.' )))
2448 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2450 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2451 binary_info.type = BINARY_DOS;
2452 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2453 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2454 inherit, flags, startup_info, info, unixdir,
2455 &binary_info, FALSE );
2456 break;
2458 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2460 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2461 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2462 inherit, flags, startup_info, info );
2463 break;
2466 /* fall through */
2467 case BINARY_UNIX_EXE:
2469 /* unknown file, try as unix executable */
2470 char *unix_name;
2472 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2474 if ((unix_name = wine_get_unix_file_name( name )))
2476 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2477 HeapFree( GetProcessHeap(), 0, unix_name );
2480 break;
2482 if (hFile) CloseHandle( hFile );
2484 done:
2485 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2486 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2487 HeapFree( GetProcessHeap(), 0, unixdir );
2488 if (retv)
2489 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2490 return retv;
2494 /**********************************************************************
2495 * CreateProcessA (KERNEL32.@)
2497 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2498 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2499 DWORD flags, LPVOID env, LPCSTR cur_dir,
2500 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2502 BOOL ret = FALSE;
2503 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2504 UNICODE_STRING desktopW, titleW;
2505 STARTUPINFOW infoW;
2507 desktopW.Buffer = NULL;
2508 titleW.Buffer = NULL;
2509 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2510 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2511 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2513 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2514 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2516 memcpy( &infoW, startup_info, sizeof(infoW) );
2517 infoW.lpDesktop = desktopW.Buffer;
2518 infoW.lpTitle = titleW.Buffer;
2520 if (startup_info->lpReserved)
2521 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2522 debugstr_a(startup_info->lpReserved));
2524 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2525 inherit, flags, env, cur_dirW, &infoW, info );
2526 done:
2527 HeapFree( GetProcessHeap(), 0, app_nameW );
2528 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2529 HeapFree( GetProcessHeap(), 0, cur_dirW );
2530 RtlFreeUnicodeString( &desktopW );
2531 RtlFreeUnicodeString( &titleW );
2532 return ret;
2536 /**********************************************************************
2537 * CreateProcessW (KERNEL32.@)
2539 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2540 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2541 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2542 LPPROCESS_INFORMATION info )
2544 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2545 inherit, flags, env, cur_dir, startup_info, info);
2549 /**********************************************************************
2550 * exec_process
2552 static void exec_process( LPCWSTR name )
2554 HANDLE hFile;
2555 WCHAR *p;
2556 STARTUPINFOW startup_info;
2557 PROCESS_INFORMATION info;
2558 struct binary_info binary_info;
2560 hFile = open_exe_file( name, &binary_info );
2561 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2563 memset( &startup_info, 0, sizeof(startup_info) );
2564 startup_info.cb = sizeof(startup_info);
2566 /* Determine executable type */
2568 if (binary_info.flags & BINARY_FLAG_DLL)
2570 CloseHandle( hFile );
2571 return;
2574 switch (binary_info.type)
2576 case BINARY_PE:
2577 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x)\n",
2578 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2579 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2580 binary_info.arch );
2581 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2582 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2583 break;
2584 case BINARY_UNIX_LIB:
2585 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2586 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2587 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2588 break;
2589 case BINARY_UNKNOWN:
2590 /* check for .com or .pif extension */
2591 if (!(p = strrchrW( name, '.' ))) break;
2592 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2593 binary_info.type = BINARY_DOS;
2594 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2595 /* fall through */
2596 case BINARY_OS216:
2597 case BINARY_WIN16:
2598 case BINARY_DOS:
2599 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2600 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2601 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2602 break;
2603 default:
2604 break;
2606 CloseHandle( hFile );
2610 /***********************************************************************
2611 * wait_input_idle
2613 * Wrapper to call WaitForInputIdle USER function
2615 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2617 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2619 HMODULE mod = GetModuleHandleA( "user32.dll" );
2620 if (mod)
2622 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2623 if (ptr) return ptr( process, timeout );
2625 return 0;
2629 /***********************************************************************
2630 * WinExec (KERNEL32.@)
2632 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2634 PROCESS_INFORMATION info;
2635 STARTUPINFOA startup;
2636 char *cmdline;
2637 UINT ret;
2639 memset( &startup, 0, sizeof(startup) );
2640 startup.cb = sizeof(startup);
2641 startup.dwFlags = STARTF_USESHOWWINDOW;
2642 startup.wShowWindow = nCmdShow;
2644 /* cmdline needs to be writable for CreateProcess */
2645 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2646 strcpy( cmdline, lpCmdLine );
2648 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2649 0, NULL, NULL, &startup, &info ))
2651 /* Give 30 seconds to the app to come up */
2652 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2653 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2654 ret = 33;
2655 /* Close off the handles */
2656 CloseHandle( info.hThread );
2657 CloseHandle( info.hProcess );
2659 else if ((ret = GetLastError()) >= 32)
2661 FIXME("Strange error set by CreateProcess: %d\n", ret );
2662 ret = 11;
2664 HeapFree( GetProcessHeap(), 0, cmdline );
2665 return ret;
2669 /**********************************************************************
2670 * LoadModule (KERNEL32.@)
2672 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2674 LOADPARMS32 *params = paramBlock;
2675 PROCESS_INFORMATION info;
2676 STARTUPINFOA startup;
2677 DWORD ret;
2678 LPSTR cmdline, p;
2679 char filename[MAX_PATH];
2680 BYTE len;
2682 if (!name) return ERROR_FILE_NOT_FOUND;
2684 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2685 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2686 return GetLastError();
2688 len = (BYTE)params->lpCmdLine[0];
2689 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2690 return ERROR_NOT_ENOUGH_MEMORY;
2692 strcpy( cmdline, filename );
2693 p = cmdline + strlen(cmdline);
2694 *p++ = ' ';
2695 memcpy( p, params->lpCmdLine + 1, len );
2696 p[len] = 0;
2698 memset( &startup, 0, sizeof(startup) );
2699 startup.cb = sizeof(startup);
2700 if (params->lpCmdShow)
2702 startup.dwFlags = STARTF_USESHOWWINDOW;
2703 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2706 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2707 params->lpEnvAddress, NULL, &startup, &info ))
2709 /* Give 30 seconds to the app to come up */
2710 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2711 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2712 ret = 33;
2713 /* Close off the handles */
2714 CloseHandle( info.hThread );
2715 CloseHandle( info.hProcess );
2717 else if ((ret = GetLastError()) >= 32)
2719 FIXME("Strange error set by CreateProcess: %u\n", ret );
2720 ret = 11;
2723 HeapFree( GetProcessHeap(), 0, cmdline );
2724 return ret;
2728 /******************************************************************************
2729 * TerminateProcess (KERNEL32.@)
2731 * Terminates a process.
2733 * PARAMS
2734 * handle [I] Process to terminate.
2735 * exit_code [I] Exit code.
2737 * RETURNS
2738 * Success: TRUE.
2739 * Failure: FALSE, check GetLastError().
2741 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2743 NTSTATUS status;
2745 if (!handle)
2747 SetLastError( ERROR_INVALID_HANDLE );
2748 return FALSE;
2751 status = NtTerminateProcess( handle, exit_code );
2752 if (status) SetLastError( RtlNtStatusToDosError(status) );
2753 return !status;
2756 /***********************************************************************
2757 * ExitProcess (KERNEL32.@)
2759 * Exits the current process.
2761 * PARAMS
2762 * status [I] Status code to exit with.
2764 * RETURNS
2765 * Nothing.
2767 #ifdef __i386__
2768 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2769 "pushl %ebp\n\t"
2770 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2771 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2772 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2773 "pushl 8(%ebp)\n\t"
2774 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2775 "leave\n\t"
2776 "ret $4" )
2777 #else
2779 void WINAPI ExitProcess( DWORD status )
2781 RtlExitUserProcess( status );
2784 #endif
2786 /***********************************************************************
2787 * GetExitCodeProcess [KERNEL32.@]
2789 * Gets termination status of specified process.
2791 * PARAMS
2792 * hProcess [in] Handle to the process.
2793 * lpExitCode [out] Address to receive termination status.
2795 * RETURNS
2796 * Success: TRUE
2797 * Failure: FALSE
2799 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2801 NTSTATUS status;
2802 PROCESS_BASIC_INFORMATION pbi;
2804 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2805 sizeof(pbi), NULL);
2806 if (status == STATUS_SUCCESS)
2808 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2809 return TRUE;
2811 SetLastError( RtlNtStatusToDosError(status) );
2812 return FALSE;
2816 /***********************************************************************
2817 * SetErrorMode (KERNEL32.@)
2819 UINT WINAPI SetErrorMode( UINT mode )
2821 UINT old;
2823 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2824 &old, sizeof(old), NULL );
2825 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2826 &mode, sizeof(mode) );
2827 return old;
2830 /***********************************************************************
2831 * GetErrorMode (KERNEL32.@)
2833 UINT WINAPI GetErrorMode( void )
2835 UINT mode;
2837 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2838 &mode, sizeof(mode), NULL );
2839 return mode;
2842 /**********************************************************************
2843 * TlsAlloc [KERNEL32.@]
2845 * Allocates a thread local storage index.
2847 * RETURNS
2848 * Success: TLS index.
2849 * Failure: 0xFFFFFFFF
2851 DWORD WINAPI TlsAlloc( void )
2853 DWORD index;
2854 PEB * const peb = NtCurrentTeb()->Peb;
2856 RtlAcquirePebLock();
2857 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2858 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2859 else
2861 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2862 if (index != ~0U)
2864 if (!NtCurrentTeb()->TlsExpansionSlots &&
2865 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2866 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2868 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2869 index = ~0U;
2870 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2872 else
2874 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2875 index += TLS_MINIMUM_AVAILABLE;
2878 else SetLastError( ERROR_NO_MORE_ITEMS );
2880 RtlReleasePebLock();
2881 return index;
2885 /**********************************************************************
2886 * TlsFree [KERNEL32.@]
2888 * Releases a thread local storage index, making it available for reuse.
2890 * PARAMS
2891 * index [in] TLS index to free.
2893 * RETURNS
2894 * Success: TRUE
2895 * Failure: FALSE
2897 BOOL WINAPI TlsFree( DWORD index )
2899 BOOL ret;
2901 RtlAcquirePebLock();
2902 if (index >= TLS_MINIMUM_AVAILABLE)
2904 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2905 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2907 else
2909 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2910 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2912 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2913 else SetLastError( ERROR_INVALID_PARAMETER );
2914 RtlReleasePebLock();
2915 return ret;
2919 /**********************************************************************
2920 * TlsGetValue [KERNEL32.@]
2922 * Gets value in a thread's TLS slot.
2924 * PARAMS
2925 * index [in] TLS index to retrieve value for.
2927 * RETURNS
2928 * Success: Value stored in calling thread's TLS slot for index.
2929 * Failure: 0 and GetLastError() returns NO_ERROR.
2931 LPVOID WINAPI TlsGetValue( DWORD index )
2933 LPVOID ret;
2935 if (index < TLS_MINIMUM_AVAILABLE)
2937 ret = NtCurrentTeb()->TlsSlots[index];
2939 else
2941 index -= TLS_MINIMUM_AVAILABLE;
2942 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2944 SetLastError( ERROR_INVALID_PARAMETER );
2945 return NULL;
2947 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2948 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2950 SetLastError( ERROR_SUCCESS );
2951 return ret;
2955 /**********************************************************************
2956 * TlsSetValue [KERNEL32.@]
2958 * Stores a value in the thread's TLS slot.
2960 * PARAMS
2961 * index [in] TLS index to set value for.
2962 * value [in] Value to be stored.
2964 * RETURNS
2965 * Success: TRUE
2966 * Failure: FALSE
2968 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2970 if (index < TLS_MINIMUM_AVAILABLE)
2972 NtCurrentTeb()->TlsSlots[index] = value;
2974 else
2976 index -= TLS_MINIMUM_AVAILABLE;
2977 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2979 SetLastError( ERROR_INVALID_PARAMETER );
2980 return FALSE;
2982 if (!NtCurrentTeb()->TlsExpansionSlots &&
2983 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2984 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2986 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2987 return FALSE;
2989 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2991 return TRUE;
2995 /***********************************************************************
2996 * GetProcessFlags (KERNEL32.@)
2998 DWORD WINAPI GetProcessFlags( DWORD processid )
3000 IMAGE_NT_HEADERS *nt;
3001 DWORD flags = 0;
3003 if (processid && processid != GetCurrentProcessId()) return 0;
3005 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3007 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
3008 flags |= PDB32_CONSOLE_PROC;
3010 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
3011 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
3012 return flags;
3016 /*********************************************************************
3017 * OpenProcess (KERNEL32.@)
3019 * Opens a handle to a process.
3021 * PARAMS
3022 * access [I] Desired access rights assigned to the returned handle.
3023 * inherit [I] Determines whether or not child processes will inherit the handle.
3024 * id [I] Process identifier of the process to get a handle to.
3026 * RETURNS
3027 * Success: Valid handle to the specified process.
3028 * Failure: NULL, check GetLastError().
3030 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
3032 NTSTATUS status;
3033 HANDLE handle;
3034 OBJECT_ATTRIBUTES attr;
3035 CLIENT_ID cid;
3037 cid.UniqueProcess = ULongToHandle(id);
3038 cid.UniqueThread = 0; /* FIXME ? */
3040 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3041 attr.RootDirectory = NULL;
3042 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3043 attr.SecurityDescriptor = NULL;
3044 attr.SecurityQualityOfService = NULL;
3045 attr.ObjectName = NULL;
3047 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3049 status = NtOpenProcess(&handle, access, &attr, &cid);
3050 if (status != STATUS_SUCCESS)
3052 SetLastError( RtlNtStatusToDosError(status) );
3053 return NULL;
3055 return handle;
3059 /*********************************************************************
3060 * GetProcessId (KERNEL32.@)
3062 * Gets the a unique identifier of a process.
3064 * PARAMS
3065 * hProcess [I] Handle to the process.
3067 * RETURNS
3068 * Success: TRUE.
3069 * Failure: FALSE, check GetLastError().
3071 * NOTES
3073 * The identifier is unique only on the machine and only until the process
3074 * exits (including system shutdown).
3076 DWORD WINAPI GetProcessId( HANDLE hProcess )
3078 NTSTATUS status;
3079 PROCESS_BASIC_INFORMATION pbi;
3081 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3082 sizeof(pbi), NULL);
3083 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3084 SetLastError( RtlNtStatusToDosError(status) );
3085 return 0;
3089 /*********************************************************************
3090 * CloseHandle (KERNEL32.@)
3092 * Closes a handle.
3094 * PARAMS
3095 * handle [I] Handle to close.
3097 * RETURNS
3098 * Success: TRUE.
3099 * Failure: FALSE, check GetLastError().
3101 BOOL WINAPI CloseHandle( HANDLE handle )
3103 NTSTATUS status;
3105 /* stdio handles need special treatment */
3106 if (handle == (HANDLE)STD_INPUT_HANDLE)
3107 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3108 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3109 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3110 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3111 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3113 if (is_console_handle(handle))
3114 return CloseConsoleHandle(handle);
3116 status = NtClose( handle );
3117 if (status) SetLastError( RtlNtStatusToDosError(status) );
3118 return !status;
3122 /*********************************************************************
3123 * GetHandleInformation (KERNEL32.@)
3125 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3127 OBJECT_DATA_INFORMATION info;
3128 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3130 if (status) SetLastError( RtlNtStatusToDosError(status) );
3131 else if (flags)
3133 *flags = 0;
3134 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3135 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3137 return !status;
3141 /*********************************************************************
3142 * SetHandleInformation (KERNEL32.@)
3144 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3146 OBJECT_DATA_INFORMATION info;
3147 NTSTATUS status;
3149 /* if not setting both fields, retrieve current value first */
3150 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3151 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3153 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3155 SetLastError( RtlNtStatusToDosError(status) );
3156 return FALSE;
3159 if (mask & HANDLE_FLAG_INHERIT)
3160 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3161 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3162 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3164 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3165 if (status) SetLastError( RtlNtStatusToDosError(status) );
3166 return !status;
3170 /*********************************************************************
3171 * DuplicateHandle (KERNEL32.@)
3173 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3174 HANDLE dest_process, HANDLE *dest,
3175 DWORD access, BOOL inherit, DWORD options )
3177 NTSTATUS status;
3179 if (is_console_handle(source))
3181 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3182 if (source_process != dest_process ||
3183 source_process != GetCurrentProcess())
3185 SetLastError(ERROR_INVALID_PARAMETER);
3186 return FALSE;
3188 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3189 return (*dest != INVALID_HANDLE_VALUE);
3191 status = NtDuplicateObject( source_process, source, dest_process, dest,
3192 access, inherit ? OBJ_INHERIT : 0, options );
3193 if (status) SetLastError( RtlNtStatusToDosError(status) );
3194 return !status;
3198 /***********************************************************************
3199 * ConvertToGlobalHandle (KERNEL32.@)
3201 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3203 HANDLE ret = INVALID_HANDLE_VALUE;
3204 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3205 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3206 return ret;
3210 /***********************************************************************
3211 * SetHandleContext (KERNEL32.@)
3213 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3215 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3216 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3217 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3218 return FALSE;
3222 /***********************************************************************
3223 * GetHandleContext (KERNEL32.@)
3225 DWORD WINAPI GetHandleContext(HANDLE hnd)
3227 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3228 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3229 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3230 return 0;
3234 /***********************************************************************
3235 * CreateSocketHandle (KERNEL32.@)
3237 HANDLE WINAPI CreateSocketHandle(void)
3239 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3240 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3241 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3242 return INVALID_HANDLE_VALUE;
3246 /***********************************************************************
3247 * SetPriorityClass (KERNEL32.@)
3249 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3251 NTSTATUS status;
3252 PROCESS_PRIORITY_CLASS ppc;
3254 ppc.Foreground = FALSE;
3255 switch (priorityclass)
3257 case IDLE_PRIORITY_CLASS:
3258 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3259 case BELOW_NORMAL_PRIORITY_CLASS:
3260 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3261 case NORMAL_PRIORITY_CLASS:
3262 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3263 case ABOVE_NORMAL_PRIORITY_CLASS:
3264 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3265 case HIGH_PRIORITY_CLASS:
3266 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3267 case REALTIME_PRIORITY_CLASS:
3268 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3269 default:
3270 SetLastError(ERROR_INVALID_PARAMETER);
3271 return FALSE;
3274 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3275 &ppc, sizeof(ppc));
3277 if (status != STATUS_SUCCESS)
3279 SetLastError( RtlNtStatusToDosError(status) );
3280 return FALSE;
3282 return TRUE;
3286 /***********************************************************************
3287 * GetPriorityClass (KERNEL32.@)
3289 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3291 NTSTATUS status;
3292 PROCESS_BASIC_INFORMATION pbi;
3294 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3295 sizeof(pbi), NULL);
3296 if (status != STATUS_SUCCESS)
3298 SetLastError( RtlNtStatusToDosError(status) );
3299 return 0;
3301 switch (pbi.BasePriority)
3303 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3304 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3305 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3306 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3307 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3308 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3310 SetLastError( ERROR_INVALID_PARAMETER );
3311 return 0;
3315 /***********************************************************************
3316 * SetProcessAffinityMask (KERNEL32.@)
3318 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3320 NTSTATUS status;
3322 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3323 &affmask, sizeof(DWORD_PTR));
3324 if (status)
3326 SetLastError( RtlNtStatusToDosError(status) );
3327 return FALSE;
3329 return TRUE;
3333 /**********************************************************************
3334 * GetProcessAffinityMask (KERNEL32.@)
3336 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3338 NTSTATUS status = STATUS_SUCCESS;
3340 if (process_mask)
3342 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3343 process_mask, sizeof(*process_mask), NULL )))
3344 SetLastError( RtlNtStatusToDosError(status) );
3346 if (system_mask && status == STATUS_SUCCESS)
3348 SYSTEM_BASIC_INFORMATION info;
3350 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3351 SetLastError( RtlNtStatusToDosError(status) );
3352 else
3353 *system_mask = info.ActiveProcessorsAffinityMask;
3355 return !status;
3359 /***********************************************************************
3360 * GetProcessVersion (KERNEL32.@)
3362 DWORD WINAPI GetProcessVersion( DWORD pid )
3364 HANDLE process;
3365 NTSTATUS status;
3366 PROCESS_BASIC_INFORMATION pbi;
3367 SIZE_T count;
3368 PEB peb;
3369 IMAGE_DOS_HEADER dos;
3370 IMAGE_NT_HEADERS nt;
3371 DWORD ver = 0;
3373 if (!pid || pid == GetCurrentProcessId())
3375 IMAGE_NT_HEADERS *pnt;
3377 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3378 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3379 pnt->OptionalHeader.MinorSubsystemVersion);
3380 return 0;
3383 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3384 if (!process) return 0;
3386 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3387 if (status) goto err;
3389 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3390 if (status || count != sizeof(peb)) goto err;
3392 memset(&dos, 0, sizeof(dos));
3393 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3394 if (status || count != sizeof(dos)) goto err;
3395 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3397 memset(&nt, 0, sizeof(nt));
3398 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3399 if (status || count != sizeof(nt)) goto err;
3400 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3402 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3404 err:
3405 CloseHandle(process);
3407 if (status != STATUS_SUCCESS)
3408 SetLastError(RtlNtStatusToDosError(status));
3410 return ver;
3414 /***********************************************************************
3415 * SetProcessWorkingSetSize [KERNEL32.@]
3416 * Sets the min/max working set sizes for a specified process.
3418 * PARAMS
3419 * hProcess [I] Handle to the process of interest
3420 * minset [I] Specifies minimum working set size
3421 * maxset [I] Specifies maximum working set size
3423 * RETURNS
3424 * Success: TRUE
3425 * Failure: FALSE
3427 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3428 SIZE_T maxset)
3430 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3431 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3432 /* Trim the working set to zero */
3433 /* Swap the process out of physical RAM */
3435 return TRUE;
3438 /***********************************************************************
3439 * K32EmptyWorkingSet (KERNEL32.@)
3441 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3443 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3447 /***********************************************************************
3448 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3450 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3451 SIZE_T *maxset, DWORD *flags)
3453 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3454 /* 32 MB working set size */
3455 if (minset) *minset = 32*1024*1024;
3456 if (maxset) *maxset = 32*1024*1024;
3457 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3458 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3459 return TRUE;
3463 /***********************************************************************
3464 * GetProcessWorkingSetSize (KERNEL32.@)
3466 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3468 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3472 /***********************************************************************
3473 * SetProcessShutdownParameters (KERNEL32.@)
3475 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3477 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3478 shutdown_flags = flags;
3479 shutdown_priority = level;
3480 return TRUE;
3484 /***********************************************************************
3485 * GetProcessShutdownParameters (KERNEL32.@)
3488 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3490 *lpdwLevel = shutdown_priority;
3491 *lpdwFlags = shutdown_flags;
3492 return TRUE;
3496 /***********************************************************************
3497 * GetProcessPriorityBoost (KERNEL32.@)
3499 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3501 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3503 /* Report that no boost is present.. */
3504 *pDisablePriorityBoost = FALSE;
3506 return TRUE;
3509 /***********************************************************************
3510 * SetProcessPriorityBoost (KERNEL32.@)
3512 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3514 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3515 /* Say we can do it. I doubt the program will notice that we don't. */
3516 return TRUE;
3520 /***********************************************************************
3521 * ReadProcessMemory (KERNEL32.@)
3523 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3524 SIZE_T *bytes_read )
3526 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3527 if (status) SetLastError( RtlNtStatusToDosError(status) );
3528 return !status;
3532 /***********************************************************************
3533 * WriteProcessMemory (KERNEL32.@)
3535 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3536 SIZE_T *bytes_written )
3538 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3539 if (status) SetLastError( RtlNtStatusToDosError(status) );
3540 return !status;
3544 /****************************************************************************
3545 * FlushInstructionCache (KERNEL32.@)
3547 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3549 NTSTATUS status;
3550 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3551 if (status) SetLastError( RtlNtStatusToDosError(status) );
3552 return !status;
3556 /******************************************************************
3557 * GetProcessIoCounters (KERNEL32.@)
3559 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3561 NTSTATUS status;
3563 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3564 ioc, sizeof(*ioc), NULL);
3565 if (status) SetLastError( RtlNtStatusToDosError(status) );
3566 return !status;
3569 /******************************************************************
3570 * GetProcessHandleCount (KERNEL32.@)
3572 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3574 NTSTATUS status;
3576 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3577 cnt, sizeof(*cnt), NULL);
3578 if (status) SetLastError( RtlNtStatusToDosError(status) );
3579 return !status;
3582 /******************************************************************
3583 * QueryFullProcessImageNameA (KERNEL32.@)
3585 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3587 BOOL retval;
3588 DWORD pdwSizeW = *pdwSize;
3589 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3591 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3593 if(retval)
3594 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3595 lpExeName, *pdwSize, NULL, NULL));
3596 if(retval)
3597 *pdwSize = strlen(lpExeName);
3599 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3600 return retval;
3603 /******************************************************************
3604 * QueryFullProcessImageNameW (KERNEL32.@)
3606 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3608 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3609 UNICODE_STRING *dynamic_buffer = NULL;
3610 UNICODE_STRING *result = NULL;
3611 NTSTATUS status;
3612 DWORD needed;
3614 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3615 * is a DOS path and we depend on this. */
3616 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3617 sizeof(buffer) - sizeof(WCHAR), &needed);
3618 if (status == STATUS_INFO_LENGTH_MISMATCH)
3620 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3621 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3622 result = dynamic_buffer;
3624 else
3625 result = (PUNICODE_STRING)buffer;
3627 if (status) goto cleanup;
3629 if (dwFlags & PROCESS_NAME_NATIVE)
3631 WCHAR drive[3];
3632 WCHAR device[1024];
3633 DWORD ntlen, devlen;
3635 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3637 /* We cannot convert it to an NT device path so fail */
3638 status = STATUS_NO_SUCH_DEVICE;
3639 goto cleanup;
3642 /* Find this drive's NT device path */
3643 drive[0] = result->Buffer[0];
3644 drive[1] = ':';
3645 drive[2] = 0;
3646 if (!QueryDosDeviceW(drive, device, sizeof(device)/sizeof(*device)))
3648 status = STATUS_NO_SUCH_DEVICE;
3649 goto cleanup;
3652 devlen = lstrlenW(device);
3653 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3654 if (ntlen + 1 > *pdwSize)
3656 status = STATUS_BUFFER_TOO_SMALL;
3657 goto cleanup;
3659 *pdwSize = ntlen;
3661 memcpy(lpExeName, device, devlen * sizeof(*device));
3662 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3663 lpExeName[*pdwSize] = 0;
3664 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3666 else
3668 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3670 status = STATUS_BUFFER_TOO_SMALL;
3671 goto cleanup;
3674 *pdwSize = result->Length/sizeof(WCHAR);
3675 memcpy( lpExeName, result->Buffer, result->Length );
3676 lpExeName[*pdwSize] = 0;
3679 cleanup:
3680 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3681 if (status) SetLastError( RtlNtStatusToDosError(status) );
3682 return !status;
3685 /***********************************************************************
3686 * K32GetProcessImageFileNameA (KERNEL32.@)
3688 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3690 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3693 /***********************************************************************
3694 * K32GetProcessImageFileNameW (KERNEL32.@)
3696 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3698 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3701 /***********************************************************************
3702 * K32EnumProcesses (KERNEL32.@)
3704 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3706 SYSTEM_PROCESS_INFORMATION *spi;
3707 ULONG size = 0x4000;
3708 void *buf = NULL;
3709 NTSTATUS status;
3711 do {
3712 size *= 2;
3713 HeapFree(GetProcessHeap(), 0, buf);
3714 buf = HeapAlloc(GetProcessHeap(), 0, size);
3715 if (!buf)
3716 return FALSE;
3718 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3719 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3721 if (status != STATUS_SUCCESS)
3723 HeapFree(GetProcessHeap(), 0, buf);
3724 SetLastError(RtlNtStatusToDosError(status));
3725 return FALSE;
3728 spi = buf;
3730 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3732 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3733 *lpcbUsed += sizeof(DWORD);
3735 if (spi->NextEntryOffset == 0)
3736 break;
3738 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3741 HeapFree(GetProcessHeap(), 0, buf);
3742 return TRUE;
3745 /***********************************************************************
3746 * K32QueryWorkingSet (KERNEL32.@)
3748 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3750 NTSTATUS status;
3752 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3754 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3756 if (status)
3758 SetLastError( RtlNtStatusToDosError( status ) );
3759 return FALSE;
3761 return TRUE;
3764 /***********************************************************************
3765 * K32QueryWorkingSetEx (KERNEL32.@)
3767 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3769 NTSTATUS status;
3771 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3773 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3775 if (status)
3777 SetLastError( RtlNtStatusToDosError( status ) );
3778 return FALSE;
3780 return TRUE;
3783 /***********************************************************************
3784 * K32GetProcessMemoryInfo (KERNEL32.@)
3786 * Retrieve memory usage information for a given process
3789 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3790 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3792 NTSTATUS status;
3793 VM_COUNTERS vmc;
3795 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3797 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3798 return FALSE;
3801 status = NtQueryInformationProcess(process, ProcessVmCounters,
3802 &vmc, sizeof(vmc), NULL);
3804 if (status)
3806 SetLastError(RtlNtStatusToDosError(status));
3807 return FALSE;
3810 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3811 pmc->PageFaultCount = vmc.PageFaultCount;
3812 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3813 pmc->WorkingSetSize = vmc.WorkingSetSize;
3814 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3815 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3816 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3817 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3818 pmc->PagefileUsage = vmc.PagefileUsage;
3819 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3821 return TRUE;
3824 /***********************************************************************
3825 * ProcessIdToSessionId (KERNEL32.@)
3826 * This function is available on Terminal Server 4SP4 and Windows 2000
3828 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3830 if (procid != GetCurrentProcessId())
3831 FIXME("Unsupported for other processes.\n");
3833 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3834 return TRUE;
3838 /***********************************************************************
3839 * RegisterServiceProcess (KERNEL32.@)
3841 * A service process calls this function to ensure that it continues to run
3842 * even after a user logged off.
3844 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3846 /* I don't think that Wine needs to do anything in this function */
3847 return 1; /* success */
3851 /**********************************************************************
3852 * IsWow64Process (KERNEL32.@)
3854 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3856 ULONG_PTR pbi;
3857 NTSTATUS status;
3859 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3861 if (status != STATUS_SUCCESS)
3863 SetLastError( RtlNtStatusToDosError( status ) );
3864 return FALSE;
3866 *Wow64Process = (pbi != 0);
3867 return TRUE;
3871 /***********************************************************************
3872 * GetCurrentProcess (KERNEL32.@)
3874 * Get a handle to the current process.
3876 * PARAMS
3877 * None.
3879 * RETURNS
3880 * A handle representing the current process.
3882 #undef GetCurrentProcess
3883 HANDLE WINAPI GetCurrentProcess(void)
3885 return (HANDLE)~(ULONG_PTR)0;
3888 /***********************************************************************
3889 * GetLogicalProcessorInformation (KERNEL32.@)
3891 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3893 NTSTATUS status;
3895 TRACE("(%p,%p)\n", buffer, pBufLen);
3897 if(!pBufLen)
3899 SetLastError(ERROR_INVALID_PARAMETER);
3900 return FALSE;
3903 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3905 if (status == STATUS_INFO_LENGTH_MISMATCH)
3907 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3908 return FALSE;
3910 if (status != STATUS_SUCCESS)
3912 SetLastError( RtlNtStatusToDosError( status ) );
3913 return FALSE;
3915 return TRUE;
3918 /***********************************************************************
3919 * GetLogicalProcessorInformationEx (KERNEL32.@)
3921 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
3923 NTSTATUS status;
3925 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
3927 if (!len)
3929 SetLastError( ERROR_INVALID_PARAMETER );
3930 return FALSE;
3933 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
3934 buffer, *len, len );
3935 if (status == STATUS_INFO_LENGTH_MISMATCH)
3937 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3938 return FALSE;
3940 if (status != STATUS_SUCCESS)
3942 SetLastError( RtlNtStatusToDosError( status ) );
3943 return FALSE;
3945 return TRUE;
3948 /***********************************************************************
3949 * CmdBatNotification (KERNEL32.@)
3951 * Notifies the system that a batch file has started or finished.
3953 * PARAMS
3954 * bBatchRunning [I] TRUE if a batch file has started or
3955 * FALSE if a batch file has finished executing.
3957 * RETURNS
3958 * Unknown.
3960 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3962 FIXME("%d\n", bBatchRunning);
3963 return FALSE;
3967 /***********************************************************************
3968 * RegisterApplicationRestart (KERNEL32.@)
3970 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3972 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3974 return S_OK;
3977 /**********************************************************************
3978 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3980 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3982 static int once;
3983 if (!once++) FIXME("stub\n");
3984 /* Return current session id. */
3985 return NtCurrentTeb()->Peb->SessionId;
3988 /**********************************************************************
3989 * GetSystemDEPPolicy (KERNEL32.@)
3991 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
3993 FIXME("stub\n");
3994 return OptIn;
3997 /**********************************************************************
3998 * SetProcessDEPPolicy (KERNEL32.@)
4000 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
4002 FIXME("(%d): stub\n", newDEP);
4003 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4004 return FALSE;
4007 /**********************************************************************
4008 * ApplicationRecoveryFinished (KERNEL32.@)
4010 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
4012 FIXME(": stub\n");
4013 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4016 /**********************************************************************
4017 * ApplicationRecoveryInProgress (KERNEL32.@)
4019 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
4021 FIXME(":%p stub\n", canceled);
4022 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4023 return E_FAIL;
4026 /**********************************************************************
4027 * RegisterApplicationRecoveryCallback (KERNEL32.@)
4029 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
4031 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
4032 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4033 return E_FAIL;
4036 /**********************************************************************
4037 * GetNumaHighestNodeNumber (KERNEL32.@)
4039 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4041 *highestnode = 0;
4042 FIXME("(%p): semi-stub\n", highestnode);
4043 return TRUE;
4046 /**********************************************************************
4047 * GetNumaNodeProcessorMask (KERNEL32.@)
4049 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4051 FIXME("(%c %p): stub\n", node, mask);
4052 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4053 return FALSE;
4056 /**********************************************************************
4057 * GetNumaAvailableMemoryNode (KERNEL32.@)
4059 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4061 FIXME("(%c %p): stub\n", node, available_bytes);
4062 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4063 return FALSE;
4066 /***********************************************************************
4067 * GetNumaProcessorNode (KERNEL32.@)
4069 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4071 SYSTEM_INFO si;
4073 TRACE("(%d, %p)\n", processor, node);
4075 GetSystemInfo( &si );
4076 if (processor < si.dwNumberOfProcessors)
4078 *node = 0;
4079 return TRUE;
4082 *node = 0xFF;
4083 SetLastError(ERROR_INVALID_PARAMETER);
4084 return FALSE;
4087 /**********************************************************************
4088 * GetProcessDEPPolicy (KERNEL32.@)
4090 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4092 NTSTATUS status;
4093 ULONG dep_flags;
4095 TRACE("(%p %p %p)\n", process, flags, permanent);
4097 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4098 &dep_flags, sizeof(dep_flags), NULL );
4099 if (!status)
4102 if (flags)
4104 *flags = 0;
4105 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4106 *flags |= PROCESS_DEP_ENABLE;
4107 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4108 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4111 if (permanent)
4112 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4115 if (status) SetLastError( RtlNtStatusToDosError(status) );
4116 return !status;
4119 /**********************************************************************
4120 * FlushProcessWriteBuffers (KERNEL32.@)
4122 VOID WINAPI FlushProcessWriteBuffers(void)
4124 static int once = 0;
4126 if (!once++)
4127 FIXME(": stub\n");
4130 /***********************************************************************
4131 * UnregisterApplicationRestart (KERNEL32.@)
4133 HRESULT WINAPI UnregisterApplicationRestart(void)
4135 FIXME(": stub\n");
4136 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4137 return S_OK;
4140 /***********************************************************************
4141 * GetSystemFirmwareTable (KERNEL32.@)
4143 UINT WINAPI GetSystemFirmwareTable(DWORD provider, DWORD id, PVOID buffer, DWORD size)
4145 FIXME("(%d %d %p %d):stub\n", provider, id, buffer, size);
4146 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4147 return 0;
4150 struct proc_thread_attr
4152 DWORD_PTR attr;
4153 SIZE_T size;
4154 void *value;
4157 struct _PROC_THREAD_ATTRIBUTE_LIST
4159 DWORD mask; /* bitmask of items in list */
4160 DWORD size; /* max number of items in list */
4161 DWORD count; /* number of items in list */
4162 DWORD pad;
4163 DWORD_PTR unk;
4164 struct proc_thread_attr attrs[1];
4167 /***********************************************************************
4168 * InitializeProcThreadAttributeList (KERNEL32.@)
4170 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4171 DWORD count, DWORD flags, SIZE_T *size)
4173 SIZE_T needed;
4174 BOOL ret = FALSE;
4176 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4178 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4179 if (list && *size >= needed)
4181 list->mask = 0;
4182 list->size = count;
4183 list->count = 0;
4184 list->unk = 0;
4185 ret = TRUE;
4187 else
4188 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4190 *size = needed;
4191 return ret;
4194 /***********************************************************************
4195 * UpdateProcThreadAttribute (KERNEL32.@)
4197 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4198 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4199 void *prev_ret, SIZE_T *size_ret)
4201 DWORD mask;
4202 struct proc_thread_attr *entry;
4204 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4206 if (list->count >= list->size)
4208 SetLastError(ERROR_GEN_FAILURE);
4209 return FALSE;
4212 switch (attr)
4214 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4215 if (size != sizeof(HANDLE))
4217 SetLastError(ERROR_BAD_LENGTH);
4218 return FALSE;
4220 break;
4222 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4223 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4225 SetLastError(ERROR_BAD_LENGTH);
4226 return FALSE;
4228 break;
4230 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4231 if (size != sizeof(PROCESSOR_NUMBER))
4233 SetLastError(ERROR_BAD_LENGTH);
4234 return FALSE;
4236 break;
4238 default:
4239 SetLastError(ERROR_NOT_SUPPORTED);
4240 return FALSE;
4243 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4245 if (list->mask & mask)
4247 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4248 return FALSE;
4251 list->mask |= mask;
4253 entry = list->attrs + list->count;
4254 entry->attr = attr;
4255 entry->size = size;
4256 entry->value = value;
4257 list->count++;
4259 return TRUE;
4262 /***********************************************************************
4263 * DeleteProcThreadAttributeList (KERNEL32.@)
4265 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4267 return;
4270 /**********************************************************************
4271 * BaseFlushAppcompatCache (KERNEL32.@)
4273 BOOL WINAPI BaseFlushAppcompatCache(void)
4275 FIXME(": stub\n");
4276 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4277 return FALSE;