server: Create the initial thread as a separate request.
[wine.git] / dlls / kernel32 / process.c
blob0967f72775f16a0378ba8e63880bac152b9f62b4
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
42 #endif
43 #include <sys/types.h>
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #ifdef __APPLE__
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <pthread.h>
53 #endif
55 #include "ntstatus.h"
56 #define WIN32_NO_STATUS
57 #include "winternl.h"
58 #include "kernel_private.h"
59 #include "psapi.h"
60 #include "wine/exception.h"
61 #include "wine/library.h"
62 #include "wine/server.h"
63 #include "wine/unicode.h"
64 #include "wine/debug.h"
66 WINE_DEFAULT_DEBUG_CHANNEL(process);
67 WINE_DECLARE_DEBUG_CHANNEL(relay);
69 #ifdef __APPLE__
70 extern char **__wine_get_main_environment(void);
71 #else
72 extern char **__wine_main_environ;
73 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
74 #endif
76 typedef struct
78 LPSTR lpEnvAddress;
79 LPSTR lpCmdLine;
80 LPSTR lpCmdShow;
81 DWORD dwReserved;
82 } LOADPARMS32;
84 static DWORD shutdown_flags = 0;
85 static DWORD shutdown_priority = 0x280;
86 static BOOL is_wow64;
87 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
89 HMODULE kernel32_handle = 0;
90 SYSTEM_BASIC_INFORMATION system_info = { 0 };
92 const WCHAR DIR_Windows[] = {'C',':','\\','w','i','n','d','o','w','s',0};
93 const WCHAR DIR_System[] = {'C',':','\\','w','i','n','d','o','w','s',
94 '\\','s','y','s','t','e','m','3','2',0};
95 const WCHAR *DIR_SysWow64 = NULL;
97 /* Process flags */
98 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
99 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
100 #define PDB32_DOS_PROC 0x0010 /* Dos process */
101 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
102 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
103 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
105 static const WCHAR exeW[] = {'.','e','x','e',0};
106 static const WCHAR comW[] = {'.','c','o','m',0};
107 static const WCHAR batW[] = {'.','b','a','t',0};
108 static const WCHAR cmdW[] = {'.','c','m','d',0};
109 static const WCHAR pifW[] = {'.','p','i','f',0};
110 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
112 static void exec_process( LPCWSTR name );
114 extern void SHELL_LoadRegistry(void);
117 /***********************************************************************
118 * contains_path
120 static inline BOOL contains_path( LPCWSTR name )
122 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
126 /***********************************************************************
127 * is_special_env_var
129 * Check if an environment variable needs to be handled specially when
130 * passed through the Unix environment (i.e. prefixed with "WINE").
132 static inline BOOL is_special_env_var( const char *var )
134 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
135 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
136 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
137 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
138 !strncmp( var, "TMP=", sizeof("TMP=")-1 ) ||
139 !strncmp( var, "QT_", sizeof("QT_")-1 ) ||
140 !strncmp( var, "VK_", sizeof("VK_")-1 ));
144 /***********************************************************************
145 * is_path_prefix
147 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
149 unsigned int len = strlenW( prefix );
151 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
152 while (filename[len] == '\\') len++;
153 return len;
157 /***************************************************************************
158 * get_builtin_path
160 * Get the path of a builtin module when the native file does not exist.
162 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
163 UINT size, struct binary_info *binary_info )
165 WCHAR *file_part;
166 UINT len;
167 void *redir_disabled = 0;
168 unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
170 /* builtin names cannot be empty or contain spaces */
171 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
173 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
174 Wow64RevertWow64FsRedirection( redir_disabled );
176 if (contains_path( libname ))
178 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
179 filename, &file_part ) > size * sizeof(WCHAR))
180 return FALSE; /* too long */
182 if ((len = is_path_prefix( DIR_System, filename )))
184 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
186 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
188 flags = 0;
190 else return FALSE;
192 if (filename + len != file_part) return FALSE;
194 else
196 len = strlenW( DIR_System );
197 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
198 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
199 file_part = filename + len;
200 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
201 strcpyW( file_part, libname );
202 if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
204 if (ext && !strchrW( file_part, '.' ))
206 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
207 return FALSE; /* too long */
208 strcatW( file_part, ext );
210 binary_info->type = BINARY_UNIX_LIB;
211 binary_info->flags = flags;
212 binary_info->res_start = 0;
213 binary_info->res_end = 0;
214 /* assume current arch */
215 #if defined(__i386__) || defined(__x86_64__)
216 binary_info->arch = (flags & BINARY_FLAG_64BIT) ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
217 #elif defined(__powerpc__)
218 binary_info->arch = IMAGE_FILE_MACHINE_POWERPC;
219 #elif defined(__arm__) && !defined(__ARMEB__)
220 binary_info->arch = IMAGE_FILE_MACHINE_ARMNT;
221 #elif defined(__aarch64__)
222 binary_info->arch = IMAGE_FILE_MACHINE_ARM64;
223 #else
224 binary_info->arch = IMAGE_FILE_MACHINE_UNKNOWN;
225 #endif
226 return TRUE;
230 /***********************************************************************
231 * open_exe_file
233 * Open a specific exe file, taking load order into account.
234 * Returns the file handle or 0 for a builtin exe.
236 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
238 HANDLE handle;
240 TRACE("looking for %s\n", debugstr_w(name) );
242 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
243 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
245 WCHAR buffer[MAX_PATH];
246 /* file doesn't exist, check for builtin */
247 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
248 handle = 0;
250 else MODULE_get_binary_info( handle, binary_info );
252 return handle;
256 /***********************************************************************
257 * find_exe_file
259 * Open an exe file, and return the full name and file handle.
260 * Returns FALSE if file could not be found.
262 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
263 HANDLE *handle, struct binary_info *binary_info )
265 TRACE("looking for %s\n", debugstr_w(name) );
267 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
268 /* no builtin found, try native without extension in case it is a Unix app */
269 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
271 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
272 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
273 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
275 MODULE_get_binary_info( *handle, binary_info );
276 return TRUE;
278 return FALSE;
282 /***********************************************************************
283 * build_initial_environment
285 * Build the Win32 environment from the Unix environment
287 static BOOL build_initial_environment(void)
289 SIZE_T size = 1;
290 char **e;
291 WCHAR *p, *endptr;
292 void *ptr;
293 char **env = __wine_get_main_environment();
295 /* Compute the total size of the Unix environment */
296 for (e = env; *e; e++)
298 if (is_special_env_var( *e )) continue;
299 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
301 size *= sizeof(WCHAR);
303 /* Now allocate the environment */
304 ptr = NULL;
305 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
306 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
307 return FALSE;
309 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
310 endptr = p + size / sizeof(WCHAR);
312 /* And fill it with the Unix environment */
313 for (e = env; *e; e++)
315 char *str = *e;
317 /* skip Unix special variables and use the Wine variants instead */
318 if (!strncmp( str, "WINE", 4 ))
320 if (is_special_env_var( str + 4 )) str += 4;
321 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
323 else if (is_special_env_var( str )) continue; /* skip it */
325 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
326 p += strlenW(p) + 1;
328 *p = 0;
329 return TRUE;
333 /***********************************************************************
334 * set_registry_variables
336 * Set environment variables by enumerating the values of a key;
337 * helper for set_registry_environment().
338 * Note that Windows happily truncates the value if it's too big.
340 static void set_registry_variables( HANDLE hkey, ULONG type )
342 static const WCHAR pathW[] = {'P','A','T','H'};
343 static const WCHAR sep[] = {';',0};
344 UNICODE_STRING env_name, env_value;
345 NTSTATUS status;
346 DWORD size;
347 int index;
348 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
349 WCHAR tmpbuf[1024];
350 UNICODE_STRING tmp;
351 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
353 tmp.Buffer = tmpbuf;
354 tmp.MaximumLength = sizeof(tmpbuf);
356 for (index = 0; ; index++)
358 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
359 buffer, sizeof(buffer), &size );
360 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
361 break;
362 if (info->Type != type)
363 continue;
364 env_name.Buffer = info->Name;
365 env_name.Length = env_name.MaximumLength = info->NameLength;
366 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
367 env_value.Length = info->DataLength;
368 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
369 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
370 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
371 if (!env_value.Length) continue;
372 if (info->Type == REG_EXPAND_SZ)
374 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
375 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
376 RtlCopyUnicodeString( &env_value, &tmp );
378 /* PATH is magic */
379 if (env_name.Length == sizeof(pathW) &&
380 !memicmpW( env_name.Buffer, pathW, ARRAY_SIZE( pathW )) &&
381 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
383 RtlAppendUnicodeToString( &tmp, sep );
384 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
385 RtlCopyUnicodeString( &env_value, &tmp );
387 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
392 /***********************************************************************
393 * set_registry_environment
395 * Set the environment variables specified in the registry.
397 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
398 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
399 * on the order in which the variables are processed. But on Windows it
400 * does not really matter since they only use %SystemDrive% and
401 * %SystemRoot% which are predefined. But Wine defines these in the
402 * registry, so we need two passes.
404 static BOOL set_registry_environment( BOOL volatile_only )
406 static const WCHAR env_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
407 'M','a','c','h','i','n','e','\\',
408 'S','y','s','t','e','m','\\',
409 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
410 'C','o','n','t','r','o','l','\\',
411 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
412 'E','n','v','i','r','o','n','m','e','n','t',0};
413 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
414 static const WCHAR volatile_envW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
416 OBJECT_ATTRIBUTES attr;
417 UNICODE_STRING nameW;
418 HANDLE hkey;
419 BOOL ret = FALSE;
421 attr.Length = sizeof(attr);
422 attr.RootDirectory = 0;
423 attr.ObjectName = &nameW;
424 attr.Attributes = 0;
425 attr.SecurityDescriptor = NULL;
426 attr.SecurityQualityOfService = NULL;
428 /* first the system environment variables */
429 RtlInitUnicodeString( &nameW, env_keyW );
430 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
432 set_registry_variables( hkey, REG_SZ );
433 set_registry_variables( hkey, REG_EXPAND_SZ );
434 NtClose( hkey );
435 ret = TRUE;
438 /* then the ones for the current user */
439 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
440 RtlInitUnicodeString( &nameW, envW );
441 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
443 set_registry_variables( hkey, REG_SZ );
444 set_registry_variables( hkey, REG_EXPAND_SZ );
445 NtClose( hkey );
448 RtlInitUnicodeString( &nameW, volatile_envW );
449 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
451 set_registry_variables( hkey, REG_SZ );
452 set_registry_variables( hkey, REG_EXPAND_SZ );
453 NtClose( hkey );
456 NtClose( attr.RootDirectory );
457 return ret;
461 /***********************************************************************
462 * get_reg_value
464 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
466 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
467 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
468 DWORD len, size = sizeof(buffer);
469 WCHAR *ret = NULL;
470 UNICODE_STRING nameW;
472 RtlInitUnicodeString( &nameW, name );
473 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
474 return NULL;
476 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
477 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
479 if (info->Type == REG_EXPAND_SZ)
481 UNICODE_STRING value, expanded;
483 value.MaximumLength = len * sizeof(WCHAR);
484 value.Buffer = (WCHAR *)info->Data;
485 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
486 value.Length = len * sizeof(WCHAR);
487 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
488 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
489 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
490 else RtlFreeUnicodeString( &expanded );
492 else if (info->Type == REG_SZ)
494 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
496 memcpy( ret, info->Data, len * sizeof(WCHAR) );
497 ret[len] = 0;
500 return ret;
504 /***********************************************************************
505 * set_additional_environment
507 * Set some additional environment variables not specified in the registry.
509 static void set_additional_environment(void)
511 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
512 'M','a','c','h','i','n','e','\\',
513 'S','o','f','t','w','a','r','e','\\',
514 'M','i','c','r','o','s','o','f','t','\\',
515 'W','i','n','d','o','w','s',' ','N','T','\\',
516 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
517 'P','r','o','f','i','l','e','L','i','s','t',0};
518 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
519 static const WCHAR public_valueW[] = {'P','u','b','l','i','c',0};
520 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
521 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
522 static const WCHAR programdataW[] = {'P','r','o','g','r','a','m','D','a','t','a',0};
523 static const WCHAR publicW[] = {'P','U','B','L','I','C',0};
524 OBJECT_ATTRIBUTES attr;
525 UNICODE_STRING nameW;
526 WCHAR *profile_dir = NULL, *program_data_dir = NULL, *public_dir = NULL;
527 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
528 HANDLE hkey;
529 DWORD len;
531 /* ComputerName */
532 len = ARRAY_SIZE( buf );
533 if (GetComputerNameW( buf, &len ))
534 SetEnvironmentVariableW( computernameW, buf );
536 /* set the ALLUSERSPROFILE variables */
538 attr.Length = sizeof(attr);
539 attr.RootDirectory = 0;
540 attr.ObjectName = &nameW;
541 attr.Attributes = 0;
542 attr.SecurityDescriptor = NULL;
543 attr.SecurityQualityOfService = NULL;
544 RtlInitUnicodeString( &nameW, profile_keyW );
545 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
547 profile_dir = get_reg_value( hkey, profiles_valueW );
548 program_data_dir = get_reg_value( hkey, programdataW );
549 public_dir = get_reg_value( hkey, public_valueW );
550 NtClose( hkey );
553 if (program_data_dir)
555 SetEnvironmentVariableW( allusersW, program_data_dir );
556 SetEnvironmentVariableW( programdataW, program_data_dir );
559 if (public_dir)
561 SetEnvironmentVariableW( publicW, public_dir );
564 HeapFree( GetProcessHeap(), 0, profile_dir );
565 HeapFree( GetProcessHeap(), 0, program_data_dir );
566 HeapFree( GetProcessHeap(), 0, public_dir );
569 /***********************************************************************
570 * set_wow64_environment
572 * Set the environment variables that change across 32/64/Wow64.
574 static void set_wow64_environment(void)
576 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};
577 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};
578 static const WCHAR x86W[] = {'x','8','6',0};
579 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
580 'M','a','c','h','i','n','e','\\',
581 'S','o','f','t','w','a','r','e','\\',
582 'M','i','c','r','o','s','o','f','t','\\',
583 'W','i','n','d','o','w','s','\\',
584 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
585 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
586 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
587 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
588 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
589 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
590 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
591 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
592 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
594 OBJECT_ATTRIBUTES attr;
595 UNICODE_STRING nameW;
596 WCHAR arch[64];
597 WCHAR *value;
598 HANDLE hkey;
600 /* set the PROCESSOR_ARCHITECTURE variable */
602 if (GetEnvironmentVariableW( arch6432W, arch, ARRAY_SIZE( arch )))
604 if (is_win64)
606 SetEnvironmentVariableW( archW, arch );
607 SetEnvironmentVariableW( arch6432W, NULL );
610 else if (GetEnvironmentVariableW( archW, arch, ARRAY_SIZE( arch )))
612 if (is_wow64)
614 SetEnvironmentVariableW( arch6432W, arch );
615 SetEnvironmentVariableW( archW, x86W );
619 attr.Length = sizeof(attr);
620 attr.RootDirectory = 0;
621 attr.ObjectName = &nameW;
622 attr.Attributes = 0;
623 attr.SecurityDescriptor = NULL;
624 attr.SecurityQualityOfService = NULL;
625 RtlInitUnicodeString( &nameW, versionW );
626 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
628 /* set the ProgramFiles variables */
630 if ((value = get_reg_value( hkey, progdirW )))
632 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
633 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
634 HeapFree( GetProcessHeap(), 0, value );
636 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
638 SetEnvironmentVariableW( progfilesW, value );
639 HeapFree( GetProcessHeap(), 0, value );
642 /* set the CommonProgramFiles variables */
644 if ((value = get_reg_value( hkey, commondirW )))
646 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
647 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
648 HeapFree( GetProcessHeap(), 0, value );
650 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
652 SetEnvironmentVariableW( commonfilesW, value );
653 HeapFree( GetProcessHeap(), 0, value );
656 NtClose( hkey );
659 /***********************************************************************
660 * set_library_wargv
662 * Set the Wine library Unicode argv global variables.
664 static void set_library_wargv( char **argv )
666 int argc;
667 char *q;
668 WCHAR *p;
669 WCHAR **wargv;
670 DWORD total = 0;
672 for (argc = 0; argv[argc]; argc++)
673 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
675 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
676 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
677 p = (WCHAR *)(wargv + argc + 1);
678 for (argc = 0; argv[argc]; argc++)
680 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
681 wargv[argc] = p;
682 p += reslen;
683 total -= reslen;
685 wargv[argc] = NULL;
687 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
689 for (argc = 0; wargv[argc]; argc++)
690 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
692 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
693 q = (char *)(argv + argc + 1);
694 for (argc = 0; wargv[argc]; argc++)
696 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
697 argv[argc] = q;
698 q += reslen;
699 total -= reslen;
701 argv[argc] = NULL;
703 __wine_main_argc = argc;
704 __wine_main_argv = argv;
705 __wine_main_wargv = wargv;
709 /***********************************************************************
710 * update_library_argv0
712 * Update the argv[0] global variable with the binary we have found.
714 static void update_library_argv0( const WCHAR *argv0 )
716 DWORD len = strlenW( argv0 );
718 if (len > strlenW( __wine_main_wargv[0] ))
720 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
722 strcpyW( __wine_main_wargv[0], argv0 );
724 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
725 if (len > strlen( __wine_main_argv[0] ) + 1)
727 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
729 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
733 /***********************************************************************
734 * build_command_line
736 * Build the command line of a process from the argv array.
738 * Note that it does NOT necessarily include the file name.
739 * Sometimes we don't even have any command line options at all.
741 * We must quote and escape characters so that the argv array can be rebuilt
742 * from the command line:
743 * - spaces and tabs must be quoted
744 * 'a b' -> '"a b"'
745 * - quotes must be escaped
746 * '"' -> '\"'
747 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
748 * resulting in an odd number of '\' followed by a '"'
749 * '\"' -> '\\\"'
750 * '\\"' -> '\\\\\"'
751 * - '\'s are followed by the closing '"' must be doubled,
752 * resulting in an even number of '\' followed by a '"'
753 * ' \' -> '" \\"'
754 * ' \\' -> '" \\\\"'
755 * - '\'s that are not followed by a '"' can be left as is
756 * 'a\b' == 'a\b'
757 * 'a\\b' == 'a\\b'
759 static BOOL build_command_line( WCHAR **argv )
761 int len;
762 WCHAR **arg;
763 LPWSTR p;
764 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
766 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
768 len = 0;
769 for (arg = argv; *arg; arg++)
771 BOOL has_space;
772 int bcount;
773 WCHAR* a;
775 has_space=FALSE;
776 bcount=0;
777 a=*arg;
778 if( !*a ) has_space=TRUE;
779 while (*a!='\0') {
780 if (*a=='\\') {
781 bcount++;
782 } else {
783 if (*a==' ' || *a=='\t') {
784 has_space=TRUE;
785 } else if (*a=='"') {
786 /* doubling of '\' preceding a '"',
787 * plus escaping of said '"'
789 len+=2*bcount+1;
791 bcount=0;
793 a++;
795 len+=(a-*arg)+1 /* for the separating space */;
796 if (has_space)
797 len+=2+bcount; /* for the quotes and doubling of '\' preceding the closing quote */
800 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
801 return FALSE;
803 p = rupp->CommandLine.Buffer;
804 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
805 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
806 for (arg = argv; *arg; arg++)
808 BOOL has_space,has_quote;
809 WCHAR* a;
810 int bcount;
812 /* Check for quotes and spaces in this argument */
813 has_space=has_quote=FALSE;
814 a=*arg;
815 if( !*a ) has_space=TRUE;
816 while (*a!='\0') {
817 if (*a==' ' || *a=='\t') {
818 has_space=TRUE;
819 if (has_quote)
820 break;
821 } else if (*a=='"') {
822 has_quote=TRUE;
823 if (has_space)
824 break;
826 a++;
829 /* Now transfer it to the command line */
830 if (has_space)
831 *p++='"';
832 if (has_quote || has_space) {
833 bcount=0;
834 a=*arg;
835 while (*a!='\0') {
836 if (*a=='\\') {
837 *p++=*a;
838 bcount++;
839 } else {
840 if (*a=='"') {
841 int i;
843 /* Double all the '\\' preceding this '"', plus one */
844 for (i=0;i<=bcount;i++)
845 *p++='\\';
846 *p++='"';
847 } else {
848 *p++=*a;
850 bcount=0;
852 a++;
854 } else {
855 WCHAR* x = *arg;
856 while ((*p=*x++)) p++;
858 if (has_space) {
859 int i;
861 /* Double all the '\' preceding the closing quote */
862 for (i=0;i<bcount;i++)
863 *p++='\\';
864 *p++='"';
866 *p++=' ';
868 if (p > rupp->CommandLine.Buffer)
869 p--; /* remove last space */
870 *p = '\0';
872 return TRUE;
876 /***********************************************************************
877 * init_current_directory
879 * Initialize the current directory from the Unix cwd or the parent info.
881 static void init_current_directory( CURDIR *cur_dir )
883 UNICODE_STRING dir_str;
884 const char *pwd;
885 char *cwd;
886 int size;
888 /* if we received a cur dir from the parent, try this first */
890 if (cur_dir->DosPath.Length)
892 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
895 /* now try to get it from the Unix cwd */
897 for (size = 256; ; size *= 2)
899 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
900 if (getcwd( cwd, size )) break;
901 HeapFree( GetProcessHeap(), 0, cwd );
902 if (errno == ERANGE) continue;
903 cwd = NULL;
904 break;
907 /* try to use PWD if it is valid, so that we don't resolve symlinks */
909 pwd = getenv( "PWD" );
910 if (cwd)
912 struct stat st1, st2;
914 if (!pwd || stat( pwd, &st1 ) == -1 ||
915 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
916 pwd = cwd;
919 if (pwd)
921 ANSI_STRING unix_name;
922 UNICODE_STRING nt_name;
923 RtlInitAnsiString( &unix_name, pwd );
924 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
926 UNICODE_STRING dos_path;
927 /* skip the \??\ prefix, nt_name is 0 terminated */
928 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
929 RtlSetCurrentDirectory_U( &dos_path );
930 RtlFreeUnicodeString( &nt_name );
934 if (!cur_dir->DosPath.Length) /* still not initialized */
936 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
937 "starting in the Windows directory.\n", cwd ? cwd : "" );
938 RtlInitUnicodeString( &dir_str, DIR_Windows );
939 RtlSetCurrentDirectory_U( &dir_str );
941 HeapFree( GetProcessHeap(), 0, cwd );
943 done:
944 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
948 /***********************************************************************
949 * init_windows_dirs
951 * Create the windows and system directories if necessary.
953 static void init_windows_dirs(void)
955 static const WCHAR default_syswow64W[] = {'C',':','\\','w','i','n','d','o','w','s',
956 '\\','s','y','s','w','o','w','6','4',0};
958 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
959 ERR( "directory %s could not be created, error %u\n",
960 debugstr_w(DIR_Windows), GetLastError() );
961 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
962 ERR( "directory %s could not be created, error %u\n",
963 debugstr_w(DIR_System), GetLastError() );
965 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
967 DIR_SysWow64 = default_syswow64W;
968 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
969 ERR( "directory %s could not be created, error %u\n",
970 debugstr_w(DIR_SysWow64), GetLastError() );
975 /***********************************************************************
976 * start_wineboot
978 * Start the wineboot process if necessary. Return the handles to wait on.
980 static void start_wineboot( HANDLE handles[2] )
982 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
984 handles[1] = 0;
985 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
987 ERR( "failed to create wineboot event, expect trouble\n" );
988 return;
990 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
992 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
993 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
994 STARTUPINFOW si;
995 PROCESS_INFORMATION pi;
996 void *redir;
997 WCHAR app[MAX_PATH];
998 WCHAR cmdline[MAX_PATH + ARRAY_SIZE( wineboot ) + ARRAY_SIZE( args )];
1000 memset( &si, 0, sizeof(si) );
1001 si.cb = sizeof(si);
1002 si.dwFlags = STARTF_USESTDHANDLES;
1003 si.hStdInput = 0;
1004 si.hStdOutput = 0;
1005 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1007 GetSystemDirectoryW( app, MAX_PATH - ARRAY_SIZE( wineboot ));
1008 lstrcatW( app, wineboot );
1010 Wow64DisableWow64FsRedirection( &redir );
1011 strcpyW( cmdline, app );
1012 strcatW( cmdline, args );
1013 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1015 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1016 CloseHandle( pi.hThread );
1017 handles[1] = pi.hProcess;
1019 else
1021 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1022 CloseHandle( handles[0] );
1023 handles[0] = 0;
1025 Wow64RevertWow64FsRedirection( redir );
1030 #ifdef __i386__
1031 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1032 __ASM_GLOBAL_FUNC( call_process_entry,
1033 "pushl %ebp\n\t"
1034 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1035 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1036 "movl %esp,%ebp\n\t"
1037 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1038 "pushl 4(%ebp)\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1039 "pushl 4(%ebp)\n\t" /* Driller expects readable address at this offset */
1040 "pushl 4(%ebp)\n\t"
1041 "pushl 8(%ebp)\n\t"
1042 "call *12(%ebp)\n\t"
1043 "leave\n\t"
1044 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1045 __ASM_CFI(".cfi_same_value %ebp\n\t")
1046 "ret" )
1048 extern void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb ) DECLSPEC_HIDDEN;
1049 extern void WINAPI start_process_wrapper(void) DECLSPEC_HIDDEN;
1050 __ASM_GLOBAL_FUNC( start_process_wrapper,
1051 "pushl %ebp\n\t"
1052 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1053 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1054 "movl %esp,%ebp\n\t"
1055 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1056 "pushl %ebx\n\t" /* arg */
1057 "pushl %eax\n\t" /* entry */
1058 "call " __ASM_NAME("start_process") )
1059 #else
1060 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1062 return entry( peb );
1064 static void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb );
1065 #define start_process_wrapper start_process
1066 #endif
1068 /***********************************************************************
1069 * start_process
1071 * Startup routine of a new process. Runs on the new process stack.
1073 void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb )
1075 BOOL being_debugged;
1077 if (!entry)
1079 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1080 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1081 ExitThread( 1 );
1084 TRACE_(relay)( "\1Starting process %s (entryproc=%p)\n",
1085 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1087 __TRY
1089 if (!CheckRemoteDebuggerPresent( GetCurrentProcess(), &being_debugged ))
1090 being_debugged = FALSE;
1092 SetLastError( 0 ); /* clear error code */
1093 if (being_debugged) DbgBreakPoint();
1094 ExitThread( call_process_entry( peb, entry ));
1096 __EXCEPT(UnhandledExceptionFilter)
1098 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1100 __ENDTRY
1101 abort(); /* should not be reached */
1105 /***********************************************************************
1106 * set_process_name
1108 * Change the process name in the ps output.
1110 static void set_process_name( int argc, char *argv[] )
1112 BOOL shift_strings;
1113 char *p, *name;
1114 int i;
1116 #ifdef HAVE_SETPROCTITLE
1117 setproctitle("-%s", argv[1]);
1118 shift_strings = FALSE;
1119 #else
1120 p = argv[0];
1122 shift_strings = (argc >= 2);
1123 for (i = 1; i < argc; i++)
1125 p += strlen(p) + 1;
1126 if (p != argv[i])
1128 shift_strings = FALSE;
1129 break;
1132 #endif
1134 if (shift_strings)
1136 int offset = argv[1] - argv[0];
1137 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1138 memmove( argv[0], argv[1], end - argv[1] );
1139 memset( end - offset, 0, offset );
1140 for (i = 1; i < argc; i++)
1141 argv[i-1] = argv[i] - offset;
1142 argv[i-1] = NULL;
1144 else
1146 /* remove argv[0] */
1147 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1150 name = argv[0];
1151 if ((p = strrchr( name, '\\' ))) name = p + 1;
1152 if ((p = strrchr( name, '/' ))) name = p + 1;
1154 #if defined(HAVE_SETPROGNAME)
1155 setprogname( name );
1156 #endif
1158 #ifdef HAVE_PRCTL
1159 #ifndef PR_SET_NAME
1160 # define PR_SET_NAME 15
1161 #endif
1162 prctl( PR_SET_NAME, name );
1163 #endif /* HAVE_PRCTL */
1167 /***********************************************************************
1168 * __wine_kernel_init
1170 * Wine initialisation: load and start the main exe file.
1172 void CDECL __wine_kernel_init(void)
1174 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1175 static const WCHAR dotW[] = {'.',0};
1177 WCHAR *p, main_exe_name[MAX_PATH+1];
1178 PEB *peb = NtCurrentTeb()->Peb;
1179 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1180 HANDLE boot_events[2];
1181 BOOL got_environment = TRUE;
1183 /* Initialize everything */
1185 setbuf(stdout,NULL);
1186 setbuf(stderr,NULL);
1187 kernel32_handle = GetModuleHandleW(kernel32W);
1188 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1190 LOCALE_Init();
1192 if (!params->Environment)
1194 /* Copy the parent environment */
1195 if (!build_initial_environment()) exit(1);
1197 /* convert old configuration to new format */
1198 convert_old_config();
1200 got_environment = set_registry_environment( FALSE );
1201 set_additional_environment();
1204 init_windows_dirs();
1205 init_current_directory( &params->CurrentDirectory );
1207 set_process_name( __wine_main_argc, __wine_main_argv );
1208 set_library_wargv( __wine_main_argv );
1209 boot_events[0] = boot_events[1] = 0;
1211 if (peb->ProcessParameters->ImagePathName.Buffer)
1213 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1215 else
1217 struct binary_info binary_info;
1219 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1220 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1222 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1223 ExitProcess( GetLastError() );
1225 update_library_argv0( main_exe_name );
1226 if (!build_command_line( __wine_main_wargv )) goto error;
1227 start_wineboot( boot_events );
1230 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1231 p = strrchrW( main_exe_name, '.' );
1232 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1234 TRACE( "starting process name=%s argv[0]=%s\n",
1235 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1237 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1238 MODULE_get_dll_load_path( main_exe_name, -1 ));
1240 if (boot_events[0])
1242 DWORD timeout = 2 * 60 * 1000, count = 1;
1244 if (boot_events[1]) count++;
1245 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1246 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1247 ERR( "boot event wait timed out\n" );
1248 CloseHandle( boot_events[0] );
1249 if (boot_events[1]) CloseHandle( boot_events[1] );
1250 /* reload environment now that wineboot has run */
1251 set_registry_environment( got_environment );
1252 set_additional_environment();
1254 set_wow64_environment();
1256 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1258 DWORD_PTR args[1];
1259 WCHAR msgW[1024];
1260 char msg[1024];
1261 DWORD error = GetLastError();
1263 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1264 if (error == ERROR_BAD_EXE_FORMAT ||
1265 error == ERROR_INVALID_ADDRESS ||
1266 error == ERROR_NOT_ENOUGH_MEMORY)
1268 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1269 /* if we get back here, it failed */
1271 else if (error == ERROR_MOD_NOT_FOUND)
1273 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1274 else p = main_exe_name;
1275 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1277 /* args 1 and 2 are --app-name full_path */
1278 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1279 debugstr_w(__wine_main_wargv[3]) );
1280 ExitProcess( ERROR_BAD_EXE_FORMAT );
1282 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1283 ExitProcess( ERROR_FILE_NOT_FOUND );
1285 args[0] = (DWORD_PTR)main_exe_name;
1286 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1287 NULL, error, 0, msgW, ARRAY_SIZE( msgW ), (__ms_va_list *)args );
1288 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1289 MESSAGE( "wine: %s", msg );
1290 ExitProcess( error );
1293 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1295 LdrInitializeThunk( start_process_wrapper, 0, 0, 0 );
1297 error:
1298 ExitProcess( GetLastError() );
1302 /***********************************************************************
1303 * build_argv
1305 * Build an argv array from a command-line.
1306 * 'reserved' is the number of args to reserve before the first one.
1308 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1310 int argc;
1311 char** argv;
1312 char *arg,*s,*d,*cmdline;
1313 int in_quotes,bcount,len;
1315 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1316 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1317 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1319 argc=reserved+1;
1320 bcount=0;
1321 in_quotes=0;
1322 s=cmdline;
1323 while (1) {
1324 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1325 /* space */
1326 argc++;
1327 /* skip the remaining spaces */
1328 while (*s==' ' || *s=='\t') {
1329 s++;
1331 if (*s=='\0')
1332 break;
1333 bcount=0;
1334 continue;
1335 } else if (*s=='\\') {
1336 /* '\', count them */
1337 bcount++;
1338 } else if ((*s=='"') && ((bcount & 1)==0)) {
1339 /* unescaped '"' */
1340 in_quotes=!in_quotes;
1341 bcount=0;
1342 } else {
1343 /* a regular character */
1344 bcount=0;
1346 s++;
1348 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1350 HeapFree( GetProcessHeap(), 0, cmdline );
1351 return NULL;
1354 arg = d = s = (char *)(argv + argc);
1355 memcpy( d, cmdline, len );
1356 bcount=0;
1357 in_quotes=0;
1358 argc=reserved;
1359 while (*s) {
1360 if ((*s==' ' || *s=='\t') && !in_quotes) {
1361 /* Close the argument and copy it */
1362 *d=0;
1363 argv[argc++]=arg;
1365 /* skip the remaining spaces */
1366 do {
1367 s++;
1368 } while (*s==' ' || *s=='\t');
1370 /* Start with a new argument */
1371 arg=d=s;
1372 bcount=0;
1373 } else if (*s=='\\') {
1374 /* '\\' */
1375 *d++=*s++;
1376 bcount++;
1377 } else if (*s=='"') {
1378 /* '"' */
1379 if ((bcount & 1)==0) {
1380 /* Preceded by an even number of '\', this is half that
1381 * number of '\', plus a '"' which we discard.
1383 d-=bcount/2;
1384 s++;
1385 in_quotes=!in_quotes;
1386 } else {
1387 /* Preceded by an odd number of '\', this is half that
1388 * number of '\' followed by a '"'
1390 d=d-bcount/2-1;
1391 *d++='"';
1392 s++;
1394 bcount=0;
1395 } else {
1396 /* a regular character */
1397 *d++=*s++;
1398 bcount=0;
1401 if (*arg) {
1402 *d='\0';
1403 argv[argc++]=arg;
1405 argv[argc]=NULL;
1407 HeapFree( GetProcessHeap(), 0, cmdline );
1408 return argv;
1412 /***********************************************************************
1413 * build_envp
1415 * Build the environment of a new child process.
1417 static char **build_envp( const WCHAR *envW )
1419 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1421 const WCHAR *end;
1422 char **envp;
1423 char *env, *p;
1424 int count = 1, length;
1425 unsigned int i;
1427 for (end = envW; *end; count++) end += strlenW(end) + 1;
1428 end++;
1429 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1430 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1431 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1433 for (p = env; *p; p += strlen(p) + 1)
1434 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1436 for (i = 0; i < ARRAY_SIZE( unix_vars ); i++)
1438 if (!(p = getenv(unix_vars[i]))) continue;
1439 length += strlen(unix_vars[i]) + strlen(p) + 2;
1440 count++;
1443 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1445 char **envptr = envp;
1446 char *dst = (char *)(envp + count);
1448 /* some variables must not be modified, so we get them directly from the unix env */
1449 for (i = 0; i < ARRAY_SIZE( unix_vars ); i++)
1451 if (!(p = getenv(unix_vars[i]))) continue;
1452 *envptr++ = strcpy( dst, unix_vars[i] );
1453 strcat( dst, "=" );
1454 strcat( dst, p );
1455 dst += strlen(dst) + 1;
1458 /* now put the Windows environment strings */
1459 for (p = env; *p; p += strlen(p) + 1)
1461 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1462 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1463 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1464 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1465 if (is_special_env_var( p )) /* prefix it with "WINE" */
1467 *envptr++ = strcpy( dst, "WINE" );
1468 strcat( dst, p );
1470 else
1472 *envptr++ = strcpy( dst, p );
1474 dst += strlen(dst) + 1;
1476 *envptr = 0;
1478 HeapFree( GetProcessHeap(), 0, env );
1479 return envp;
1483 /***********************************************************************
1484 * fork_and_exec
1486 * Fork and exec a new Unix binary, checking for errors.
1488 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1489 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1491 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1492 int pid, err;
1493 char **argv, **envp;
1495 if (!env) env = GetEnvironmentStringsW();
1497 #ifdef HAVE_PIPE2
1498 if (pipe2( fd, O_CLOEXEC ) == -1)
1499 #endif
1501 if (pipe(fd) == -1)
1503 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1504 return -1;
1506 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1507 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1510 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1512 HANDLE hstdin, hstdout, hstderr;
1514 if (startup->dwFlags & STARTF_USESTDHANDLES)
1516 hstdin = startup->hStdInput;
1517 hstdout = startup->hStdOutput;
1518 hstderr = startup->hStdError;
1520 else
1522 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1523 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1524 hstderr = GetStdHandle(STD_ERROR_HANDLE);
1527 if (is_console_handle( hstdin ))
1528 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1529 if (is_console_handle( hstdout ))
1530 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1531 if (is_console_handle( hstderr ))
1532 hstderr = wine_server_ptr_handle( console_handle_unmap( hstderr ));
1533 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1534 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1535 wine_server_handle_to_fd( hstderr, FILE_WRITE_DATA, &stderr_fd, NULL );
1538 argv = build_argv( cmdline, 0 );
1539 envp = build_envp( env );
1541 if (!(pid = fork())) /* child */
1543 if (!(pid = fork())) /* grandchild */
1545 close( fd[0] );
1547 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1549 int nullfd = open( "/dev/null", O_RDWR );
1550 setsid();
1551 /* close stdin and stdout */
1552 if (nullfd != -1)
1554 dup2( nullfd, 0 );
1555 dup2( nullfd, 1 );
1556 close( nullfd );
1559 else
1561 if (stdin_fd != -1)
1563 dup2( stdin_fd, 0 );
1564 close( stdin_fd );
1566 if (stdout_fd != -1)
1568 dup2( stdout_fd, 1 );
1569 close( stdout_fd );
1571 if (stderr_fd != -1)
1573 dup2( stderr_fd, 2 );
1574 close( stderr_fd );
1578 /* Reset signals that we previously set to SIG_IGN */
1579 signal( SIGPIPE, SIG_DFL );
1581 if (newdir) chdir(newdir);
1583 if (argv && envp) execve( filename, argv, envp );
1586 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1588 err = errno;
1589 write( fd[1], &err, sizeof(err) );
1590 _exit(1);
1593 _exit(0); /* child if fork succeeded */
1595 HeapFree( GetProcessHeap(), 0, argv );
1596 HeapFree( GetProcessHeap(), 0, envp );
1597 if (stdin_fd != -1) close( stdin_fd );
1598 if (stdout_fd != -1) close( stdout_fd );
1599 if (stderr_fd != -1) close( stderr_fd );
1600 close( fd[1] );
1601 if (pid != -1)
1603 /* reap child */
1604 do {
1605 err = waitpid(pid, NULL, 0);
1606 } while (err < 0 && errno == EINTR);
1608 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1610 errno = err;
1611 pid = -1;
1614 if (pid == -1) FILE_SetDosError();
1615 close( fd[0] );
1616 return pid;
1620 static inline DWORD append_string( void **ptr, const WCHAR *str )
1622 DWORD len = strlenW( str );
1623 memcpy( *ptr, str, len * sizeof(WCHAR) );
1624 *ptr = (WCHAR *)*ptr + len;
1625 return len * sizeof(WCHAR);
1628 /***********************************************************************
1629 * create_startup_info
1631 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1632 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1633 const STARTUPINFOW *startup, DWORD *info_size )
1635 const RTL_USER_PROCESS_PARAMETERS *cur_params;
1636 const WCHAR *title;
1637 startup_info_t *info;
1638 DWORD size;
1639 void *ptr;
1640 UNICODE_STRING newdir;
1641 WCHAR imagepath[MAX_PATH];
1642 HANDLE hstdin, hstdout, hstderr;
1644 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1645 lstrcpynW( imagepath, filename, MAX_PATH );
1646 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1647 lstrcpynW( imagepath, filename, MAX_PATH );
1649 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1651 newdir.Buffer = NULL;
1652 if (cur_dir)
1654 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1655 cur_dir = newdir.Buffer + 4; /* skip \??\ prefix */
1656 else
1657 cur_dir = NULL;
1659 if (!cur_dir)
1661 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1662 cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1663 else
1664 cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1666 title = startup->lpTitle ? startup->lpTitle : imagepath;
1668 size = sizeof(*info);
1669 size += strlenW( cur_dir ) * sizeof(WCHAR);
1670 size += cur_params->DllPath.Length;
1671 size += strlenW( imagepath ) * sizeof(WCHAR);
1672 size += strlenW( cmdline ) * sizeof(WCHAR);
1673 size += strlenW( title ) * sizeof(WCHAR);
1674 if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1675 /* FIXME: shellinfo */
1676 if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1677 size = (size + 1) & ~1;
1678 *info_size = size;
1680 if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1682 info->console_flags = cur_params->ConsoleFlags;
1683 if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1684 if (flags & CREATE_NEW_CONSOLE) info->console = wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC);
1686 if (startup->dwFlags & STARTF_USESTDHANDLES)
1688 hstdin = startup->hStdInput;
1689 hstdout = startup->hStdOutput;
1690 hstderr = startup->hStdError;
1692 else if (flags & DETACHED_PROCESS)
1694 hstdin = INVALID_HANDLE_VALUE;
1695 hstdout = INVALID_HANDLE_VALUE;
1696 hstderr = INVALID_HANDLE_VALUE;
1698 else
1700 hstdin = GetStdHandle( STD_INPUT_HANDLE );
1701 hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1702 hstderr = GetStdHandle( STD_ERROR_HANDLE );
1704 info->hstdin = wine_server_obj_handle( hstdin );
1705 info->hstdout = wine_server_obj_handle( hstdout );
1706 info->hstderr = wine_server_obj_handle( hstderr );
1707 if ((flags & CREATE_NEW_CONSOLE) != 0)
1709 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1710 if (is_console_handle(hstdin)) info->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1711 if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1712 if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1714 else
1716 if (is_console_handle(hstdin)) info->hstdin = console_handle_unmap(hstdin);
1717 if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1718 if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1721 info->x = startup->dwX;
1722 info->y = startup->dwY;
1723 info->xsize = startup->dwXSize;
1724 info->ysize = startup->dwYSize;
1725 info->xchars = startup->dwXCountChars;
1726 info->ychars = startup->dwYCountChars;
1727 info->attribute = startup->dwFillAttribute;
1728 info->flags = startup->dwFlags;
1729 info->show = startup->wShowWindow;
1731 ptr = info + 1;
1732 info->curdir_len = append_string( &ptr, cur_dir );
1733 info->dllpath_len = cur_params->DllPath.Length;
1734 memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1735 ptr = (char *)ptr + cur_params->DllPath.Length;
1736 info->imagepath_len = append_string( &ptr, imagepath );
1737 info->cmdline_len = append_string( &ptr, cmdline );
1738 info->title_len = append_string( &ptr, title );
1739 if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1740 if (startup->lpReserved2 && startup->cbReserved2)
1742 info->runtime_len = startup->cbReserved2;
1743 memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1746 done:
1747 RtlFreeUnicodeString( &newdir );
1748 return info;
1751 /***********************************************************************
1752 * get_alternate_loader
1754 * Get the name of the alternate (32 or 64 bit) Wine loader.
1756 static const char *get_alternate_loader( char **ret_env )
1758 char *env;
1759 const char *loader = NULL;
1760 const char *loader_env = getenv( "WINELOADER" );
1762 *ret_env = NULL;
1764 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1766 if (loader_env)
1768 int len = strlen( loader_env );
1769 if (!is_win64)
1771 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1772 strcpy( env, "WINELOADER=" );
1773 strcat( env, loader_env );
1774 strcat( env, "64" );
1776 else
1778 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1779 strcpy( env, "WINELOADER=" );
1780 strcat( env, loader_env );
1781 len += sizeof("WINELOADER=") - 1;
1782 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1784 if (!loader)
1786 if ((loader = strrchr( env, '/' ))) loader++;
1787 else loader = env;
1789 *ret_env = env;
1791 if (!loader) loader = is_win64 ? "wine" : "wine64";
1792 return loader;
1795 #ifdef __APPLE__
1796 /***********************************************************************
1797 * terminate_main_thread
1799 * On some versions of Mac OS X, the execve system call fails with
1800 * ENOTSUP if the process has multiple threads. Wine is always multi-
1801 * threaded on Mac OS X because it specifically reserves the main thread
1802 * for use by the system frameworks (see apple_main_thread() in
1803 * libs/wine/loader.c). So, when we need to exec without first forking,
1804 * we need to terminate the main thread first. We do this by installing
1805 * a custom run loop source onto the main run loop and signaling it.
1806 * The source's "perform" callback is pthread_exit and it will be
1807 * executed on the main thread, terminating it.
1809 * Returns TRUE if there's still hope the main thread has terminated or
1810 * will soon. Return FALSE if we've given up.
1812 static BOOL terminate_main_thread(void)
1814 static int delayms;
1816 if (!delayms)
1818 CFRunLoopSourceContext source_context = { 0 };
1819 CFRunLoopSourceRef source;
1821 source_context.perform = pthread_exit;
1822 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
1823 return FALSE;
1825 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
1826 CFRunLoopSourceSignal( source );
1827 CFRunLoopWakeUp( CFRunLoopGetMain() );
1828 CFRelease( source );
1830 delayms = 20;
1833 if (delayms > 1000)
1834 return FALSE;
1836 usleep(delayms * 1000);
1837 delayms *= 2;
1839 return TRUE;
1841 #endif
1843 /***********************************************************************
1844 * get_process_cpu
1846 static int get_process_cpu( const WCHAR *filename, const struct binary_info *binary_info )
1848 switch (binary_info->arch)
1850 case IMAGE_FILE_MACHINE_I386: return CPU_x86;
1851 case IMAGE_FILE_MACHINE_AMD64: return CPU_x86_64;
1852 case IMAGE_FILE_MACHINE_POWERPC: return CPU_POWERPC;
1853 case IMAGE_FILE_MACHINE_ARM:
1854 case IMAGE_FILE_MACHINE_THUMB:
1855 case IMAGE_FILE_MACHINE_ARMNT: return CPU_ARM;
1856 case IMAGE_FILE_MACHINE_ARM64: return CPU_ARM64;
1858 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename), binary_info->arch );
1859 return -1;
1862 /***********************************************************************
1863 * exec_loader
1865 static pid_t exec_loader( LPCWSTR cmd_line, unsigned int flags, int socketfd,
1866 int stdin_fd, int stdout_fd, const char *unixdir, char *winedebug,
1867 const struct binary_info *binary_info, int exec_only )
1869 pid_t pid;
1870 char *wineloader = NULL;
1871 const char *loader = NULL;
1872 char **argv;
1874 argv = build_argv( cmd_line, 1 );
1876 if (!is_win64 ^ !(binary_info->flags & BINARY_FLAG_64BIT))
1877 loader = get_alternate_loader( &wineloader );
1879 if (exec_only || !(pid = fork())) /* child */
1881 if (exec_only || !(pid = fork())) /* grandchild */
1883 char preloader_reserve[64], socket_env[64];
1885 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1887 int fd = open( "/dev/null", O_RDWR );
1888 setsid();
1889 /* close stdin and stdout */
1890 if (fd != -1)
1892 dup2( fd, 0 );
1893 dup2( fd, 1 );
1894 close( fd );
1897 else
1899 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1900 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1903 if (stdin_fd != -1) close( stdin_fd );
1904 if (stdout_fd != -1) close( stdout_fd );
1906 /* Reset signals that we previously set to SIG_IGN */
1907 signal( SIGPIPE, SIG_DFL );
1909 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
1910 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
1911 (ULONG)(binary_info->res_start >> 32), (ULONG)binary_info->res_start,
1912 (ULONG)(binary_info->res_end >> 32), (ULONG)binary_info->res_end );
1914 putenv( preloader_reserve );
1915 putenv( socket_env );
1916 if (winedebug) putenv( winedebug );
1917 if (wineloader) putenv( wineloader );
1918 if (unixdir) chdir(unixdir);
1920 if (argv)
1924 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
1926 #ifdef __APPLE__
1927 while (errno == ENOTSUP && exec_only && terminate_main_thread());
1928 #else
1929 while (0);
1930 #endif
1932 _exit(1);
1935 _exit(pid == -1);
1938 if (pid != -1)
1940 /* reap child */
1941 pid_t wret;
1942 do {
1943 wret = waitpid(pid, NULL, 0);
1944 } while (wret < 0 && errno == EINTR);
1947 HeapFree( GetProcessHeap(), 0, wineloader );
1948 HeapFree( GetProcessHeap(), 0, argv );
1949 return pid;
1952 /* creates a struct security_descriptor and contained information in one contiguous piece of memory */
1953 static NTSTATUS alloc_object_attributes( const SECURITY_ATTRIBUTES *attr, struct object_attributes **ret,
1954 data_size_t *ret_len )
1956 unsigned int len = sizeof(**ret);
1957 PSID owner = NULL, group = NULL;
1958 ACL *dacl, *sacl;
1959 BOOLEAN dacl_present, sacl_present, defaulted;
1960 PSECURITY_DESCRIPTOR sd = NULL;
1961 NTSTATUS status;
1963 *ret = NULL;
1964 *ret_len = 0;
1966 if (attr) sd = attr->lpSecurityDescriptor;
1968 if (sd)
1970 len += sizeof(struct security_descriptor);
1972 if ((status = RtlGetOwnerSecurityDescriptor( sd, &owner, &defaulted ))) return status;
1973 if ((status = RtlGetGroupSecurityDescriptor( sd, &group, &defaulted ))) return status;
1974 if ((status = RtlGetSaclSecurityDescriptor( sd, &sacl_present, &sacl, &defaulted ))) return status;
1975 if ((status = RtlGetDaclSecurityDescriptor( sd, &dacl_present, &dacl, &defaulted ))) return status;
1976 if (owner) len += RtlLengthSid( owner );
1977 if (group) len += RtlLengthSid( group );
1978 if (sacl_present && sacl) len += sacl->AclSize;
1979 if (dacl_present && dacl) len += dacl->AclSize;
1982 len = (len + 3) & ~3; /* DWORD-align the entire structure */
1984 *ret = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, len );
1985 if (!*ret) return STATUS_NO_MEMORY;
1987 (*ret)->attributes = (attr && attr->bInheritHandle) ? OBJ_INHERIT : 0;
1989 if (sd)
1991 struct security_descriptor *descr = (struct security_descriptor *)(*ret + 1);
1992 unsigned char *ptr = (unsigned char *)(descr + 1);
1994 descr->control = ((SECURITY_DESCRIPTOR *)sd)->Control & ~SE_SELF_RELATIVE;
1995 if (owner) descr->owner_len = RtlLengthSid( owner );
1996 if (group) descr->group_len = RtlLengthSid( group );
1997 if (sacl_present && sacl) descr->sacl_len = sacl->AclSize;
1998 if (dacl_present && dacl) descr->dacl_len = dacl->AclSize;
2000 memcpy( ptr, owner, descr->owner_len );
2001 ptr += descr->owner_len;
2002 memcpy( ptr, group, descr->group_len );
2003 ptr += descr->group_len;
2004 memcpy( ptr, sacl, descr->sacl_len );
2005 ptr += descr->sacl_len;
2006 memcpy( ptr, dacl, descr->dacl_len );
2007 (*ret)->sd_len = (sizeof(*descr) + descr->owner_len + descr->group_len + descr->sacl_len +
2008 descr->dacl_len + sizeof(WCHAR) - 1) & ~(sizeof(WCHAR) - 1);
2010 *ret_len = len;
2011 return STATUS_SUCCESS;
2014 /***********************************************************************
2015 * create_process
2017 * Create a new process. If hFile is a valid handle we have an exe
2018 * file, otherwise it is a Winelib app.
2020 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
2021 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2022 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2023 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2024 const struct binary_info *binary_info, int exec_only )
2026 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
2027 NTSTATUS status;
2028 BOOL success = FALSE;
2029 HANDLE process_info, process_handle = 0;
2030 struct object_attributes *objattr;
2031 data_size_t attr_len;
2032 WCHAR *env_end;
2033 char *winedebug = NULL;
2034 startup_info_t *startup_info;
2035 DWORD startup_info_size;
2036 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
2037 pid_t pid;
2038 int err, cpu;
2040 if ((cpu = get_process_cpu( filename, binary_info )) == -1)
2042 SetLastError( ERROR_BAD_EXE_FORMAT );
2043 return FALSE;
2046 /* create the socket for the new process */
2048 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2050 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2051 return FALSE;
2053 #ifdef SO_PASSCRED
2054 else
2056 int enable = 1;
2057 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2059 #endif
2061 if (exec_only) /* things are much simpler in this case */
2063 wine_server_send_fd( socketfd[1] );
2064 close( socketfd[1] );
2065 SERVER_START_REQ( new_process )
2067 req->create_flags = flags;
2068 req->socket_fd = socketfd[1];
2069 req->exe_file = wine_server_obj_handle( hFile );
2070 req->cpu = cpu;
2071 status = wine_server_call( req );
2073 SERVER_END_REQ;
2075 switch (status)
2077 case STATUS_INVALID_IMAGE_WIN_64:
2078 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2079 break;
2080 case STATUS_INVALID_IMAGE_FORMAT:
2081 ERR( "%s not supported on this installation (%s binary)\n",
2082 debugstr_w(filename), cpu_names[cpu] );
2083 break;
2084 case STATUS_SUCCESS:
2085 exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2086 winedebug, binary_info, TRUE );
2088 close( socketfd[0] );
2089 SetLastError( RtlNtStatusToDosError( status ));
2090 return FALSE;
2093 RtlAcquirePebLock();
2095 if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
2096 &startup_info_size )))
2098 RtlReleasePebLock();
2099 close( socketfd[0] );
2100 close( socketfd[1] );
2101 return FALSE;
2103 if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
2104 env_end = env;
2105 while (*env_end)
2107 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2108 if (!winedebug && !strncmpW( env_end, WINEDEBUG, ARRAY_SIZE( WINEDEBUG ) - 1 ))
2110 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2111 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2112 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2114 env_end += strlenW(env_end) + 1;
2116 env_end++;
2118 wine_server_send_fd( socketfd[1] );
2119 close( socketfd[1] );
2121 /* create the process on the server side */
2123 SERVER_START_REQ( new_process )
2125 req->inherit_all = inherit;
2126 req->create_flags = flags;
2127 req->socket_fd = socketfd[1];
2128 req->exe_file = wine_server_obj_handle( hFile );
2129 req->access = PROCESS_ALL_ACCESS;
2130 req->attributes = (psa && psa->nLength >= sizeof(*psa) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
2131 req->cpu = cpu;
2132 req->info_size = startup_info_size;
2134 wine_server_add_data( req, startup_info, startup_info_size );
2135 wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
2136 if (!(status = wine_server_call( req )))
2138 info->dwProcessId = (DWORD)reply->pid;
2139 process_handle = wine_server_ptr_handle( reply->handle );
2141 process_info = wine_server_ptr_handle( reply->info );
2143 SERVER_END_REQ;
2145 if (!status)
2147 alloc_object_attributes( tsa, &objattr, &attr_len );
2148 SERVER_START_REQ( new_thread )
2150 req->process = wine_server_obj_handle( process_handle );
2151 req->access = THREAD_ALL_ACCESS;
2152 req->suspend = !!(flags & CREATE_SUSPENDED);
2153 req->request_fd = -1;
2154 wine_server_add_data( req, objattr, attr_len );
2155 if (!(status = wine_server_call( req )))
2157 info->hProcess = process_handle;
2158 info->hThread = wine_server_ptr_handle( reply->handle );
2159 info->dwThreadId = reply->tid;
2162 SERVER_END_REQ;
2163 HeapFree( GetProcessHeap(), 0, objattr );
2166 RtlReleasePebLock();
2167 if (status)
2169 switch (status)
2171 case STATUS_INVALID_IMAGE_WIN_64:
2172 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2173 break;
2174 case STATUS_INVALID_IMAGE_FORMAT:
2175 ERR( "%s not supported on this installation (%s binary)\n",
2176 debugstr_w(filename), cpu_names[cpu] );
2177 break;
2179 close( socketfd[0] );
2180 CloseHandle( process_handle );
2181 HeapFree( GetProcessHeap(), 0, startup_info );
2182 HeapFree( GetProcessHeap(), 0, winedebug );
2183 SetLastError( RtlNtStatusToDosError( status ));
2184 return FALSE;
2187 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2189 if (startup_info->hstdin)
2190 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2191 FILE_READ_DATA, &stdin_fd, NULL );
2192 if (startup_info->hstdout)
2193 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2194 FILE_WRITE_DATA, &stdout_fd, NULL );
2196 HeapFree( GetProcessHeap(), 0, startup_info );
2198 /* create the child process */
2200 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2201 winedebug, binary_info, FALSE );
2203 if (stdin_fd != -1) close( stdin_fd );
2204 if (stdout_fd != -1) close( stdout_fd );
2205 close( socketfd[0] );
2206 HeapFree( GetProcessHeap(), 0, winedebug );
2207 if (pid == -1)
2209 FILE_SetDosError();
2210 goto error;
2213 /* wait for the new process info to be ready */
2215 WaitForSingleObject( process_info, INFINITE );
2216 SERVER_START_REQ( get_new_process_info )
2218 req->info = wine_server_obj_handle( process_info );
2219 wine_server_call( req );
2220 success = reply->success;
2221 err = reply->exit_code;
2223 SERVER_END_REQ;
2225 if (!success)
2227 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2228 goto error;
2230 CloseHandle( process_info );
2231 return success;
2233 error:
2234 CloseHandle( process_info );
2235 CloseHandle( info->hProcess );
2236 CloseHandle( info->hThread );
2237 info->hProcess = info->hThread = 0;
2238 info->dwProcessId = info->dwThreadId = 0;
2239 return FALSE;
2243 /***********************************************************************
2244 * create_vdm_process
2246 * Create a new VDM process for a 16-bit or DOS application.
2248 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2249 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2250 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2251 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2252 const struct binary_info *binary_info, int exec_only )
2254 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2256 BOOL ret;
2257 WCHAR buffer[MAX_PATH];
2258 LPWSTR new_cmd_line;
2260 if (!(ret = GetFullPathNameW(filename, MAX_PATH, buffer, NULL)))
2261 return FALSE;
2263 new_cmd_line = HeapAlloc(GetProcessHeap(), 0,
2264 (strlenW(buffer) + strlenW(cmd_line) + 30) * sizeof(WCHAR));
2266 if (!new_cmd_line)
2268 SetLastError( ERROR_OUTOFMEMORY );
2269 return FALSE;
2271 sprintfW(new_cmd_line, argsW, winevdmW, buffer, cmd_line);
2272 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2273 flags, startup, info, unixdir, binary_info, exec_only );
2274 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2275 return ret;
2279 /***********************************************************************
2280 * create_cmd_process
2282 * Create a new cmd shell process for a .BAT file.
2284 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2285 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2286 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2287 LPPROCESS_INFORMATION info )
2290 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2291 static const WCHAR cmdW[] = {'\\','c','m','d','.','e','x','e',0};
2292 static const WCHAR slashscW[] = {' ','/','s','/','c',' ',0};
2293 static const WCHAR quotW[] = {'"',0};
2294 WCHAR comspec[MAX_PATH];
2295 WCHAR *newcmdline;
2296 BOOL ret;
2298 if (!GetEnvironmentVariableW( comspecW, comspec, ARRAY_SIZE( comspec )))
2300 GetSystemDirectoryW( comspec, (sizeof(comspec) - sizeof(cmdW))/sizeof(WCHAR) );
2301 strcatW( comspec, cmdW );
2303 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2304 (strlenW(comspec) + 7 + strlenW(cmd_line) + 2) * sizeof(WCHAR))))
2305 return FALSE;
2307 strcpyW( newcmdline, comspec );
2308 strcatW( newcmdline, slashscW );
2309 strcatW( newcmdline, quotW );
2310 strcatW( newcmdline, cmd_line );
2311 strcatW( newcmdline, quotW );
2312 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2313 flags, env, cur_dir, startup, info );
2314 HeapFree( GetProcessHeap(), 0, newcmdline );
2315 return ret;
2319 /*************************************************************************
2320 * get_file_name
2322 * Helper for CreateProcess: retrieve the file name to load from the
2323 * app name and command line. Store the file name in buffer, and
2324 * return a possibly modified command line.
2325 * Also returns a handle to the opened file if it's a Windows binary.
2327 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2328 int buflen, HANDLE *handle, struct binary_info *binary_info )
2330 static const WCHAR quotesW[] = {'"','%','s','"',0};
2332 WCHAR *name, *pos, *first_space, *ret = NULL;
2333 const WCHAR *p;
2335 /* if we have an app name, everything is easy */
2337 if (appname)
2339 /* use the unmodified app name as file name */
2340 lstrcpynW( buffer, appname, buflen );
2341 *handle = open_exe_file( buffer, binary_info );
2342 if (!(ret = cmdline) || !cmdline[0])
2344 /* no command-line, create one */
2345 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2346 sprintfW( ret, quotesW, appname );
2348 return ret;
2351 /* first check for a quoted file name */
2353 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2355 int len = p - cmdline - 1;
2356 /* extract the quoted portion as file name */
2357 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2358 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2359 name[len] = 0;
2361 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2362 ret = cmdline; /* no change necessary */
2363 goto done;
2366 /* now try the command-line word by word */
2368 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2369 return NULL;
2370 pos = name;
2371 p = cmdline;
2372 first_space = NULL;
2374 for (;;)
2376 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2377 *pos = 0;
2378 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2380 ret = cmdline;
2381 break;
2383 if (!first_space) first_space = pos;
2384 if (!(*pos++ = *p++)) break;
2387 if (!ret)
2389 SetLastError( ERROR_FILE_NOT_FOUND );
2391 else if (first_space) /* build a new command-line with quotes */
2393 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2394 goto done;
2395 sprintfW( ret, quotesW, name );
2396 strcatW( ret, p );
2399 done:
2400 HeapFree( GetProcessHeap(), 0, name );
2401 return ret;
2405 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2406 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2407 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2408 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2409 LPPROCESS_INFORMATION info )
2411 BOOL retv = FALSE;
2412 HANDLE hFile = 0;
2413 char *unixdir = NULL;
2414 WCHAR name[MAX_PATH];
2415 WCHAR *tidy_cmdline, *p, *envW = env;
2416 struct binary_info binary_info;
2418 /* Process the AppName and/or CmdLine to get module name and path */
2420 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2422 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, ARRAY_SIZE( name ),
2423 &hFile, &binary_info )))
2424 return FALSE;
2425 if (hFile == INVALID_HANDLE_VALUE) goto done;
2427 /* Warn if unsupported features are used */
2429 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2430 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2431 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2432 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2433 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2435 if (cur_dir)
2437 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2439 SetLastError(ERROR_DIRECTORY);
2440 goto done;
2443 else
2445 WCHAR buf[MAX_PATH];
2446 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2449 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2451 char *e = env;
2452 DWORD lenW;
2454 while (*e) e += strlen(e) + 1;
2455 e++; /* final null */
2456 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2457 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2458 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2459 flags |= CREATE_UNICODE_ENVIRONMENT;
2462 info->hThread = info->hProcess = 0;
2463 info->dwProcessId = info->dwThreadId = 0;
2465 if (binary_info.flags & BINARY_FLAG_DLL)
2467 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2468 SetLastError( ERROR_BAD_EXE_FORMAT );
2470 else switch (binary_info.type)
2472 case BINARY_PE:
2473 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x%s)\n",
2474 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2475 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2476 binary_info.arch, (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2477 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2478 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2479 break;
2480 case BINARY_OS216:
2481 case BINARY_WIN16:
2482 case BINARY_DOS:
2483 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2484 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2485 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2486 break;
2487 case BINARY_UNIX_LIB:
2488 TRACE( "starting %s as %d-bit Winelib app\n",
2489 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2490 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2491 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2492 break;
2493 case BINARY_UNKNOWN:
2494 /* check for .com or .bat extension */
2495 if ((p = strrchrW( name, '.' )))
2497 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2499 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2500 binary_info.type = BINARY_DOS;
2501 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2502 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2503 inherit, flags, startup_info, info, unixdir,
2504 &binary_info, FALSE );
2505 break;
2507 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2509 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2510 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2511 inherit, flags, startup_info, info );
2512 break;
2515 /* fall through */
2516 case BINARY_UNIX_EXE:
2518 /* unknown file, try as unix executable */
2519 char *unix_name;
2521 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2523 if ((unix_name = wine_get_unix_file_name( name )))
2525 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2526 HeapFree( GetProcessHeap(), 0, unix_name );
2529 break;
2531 if (hFile) CloseHandle( hFile );
2533 done:
2534 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2535 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2536 HeapFree( GetProcessHeap(), 0, unixdir );
2537 if (retv)
2538 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2539 return retv;
2543 /**********************************************************************
2544 * CreateProcessA (KERNEL32.@)
2546 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2547 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2548 DWORD flags, LPVOID env, LPCSTR cur_dir,
2549 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2551 BOOL ret = FALSE;
2552 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2553 UNICODE_STRING desktopW, titleW;
2554 STARTUPINFOW infoW;
2556 desktopW.Buffer = NULL;
2557 titleW.Buffer = NULL;
2558 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2559 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2560 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2562 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2563 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2565 memcpy( &infoW, startup_info, sizeof(infoW) );
2566 infoW.lpDesktop = desktopW.Buffer;
2567 infoW.lpTitle = titleW.Buffer;
2569 if (startup_info->lpReserved)
2570 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2571 debugstr_a(startup_info->lpReserved));
2573 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2574 inherit, flags, env, cur_dirW, &infoW, info );
2575 done:
2576 HeapFree( GetProcessHeap(), 0, app_nameW );
2577 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2578 HeapFree( GetProcessHeap(), 0, cur_dirW );
2579 RtlFreeUnicodeString( &desktopW );
2580 RtlFreeUnicodeString( &titleW );
2581 return ret;
2585 /**********************************************************************
2586 * CreateProcessW (KERNEL32.@)
2588 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2589 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2590 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2591 LPPROCESS_INFORMATION info )
2593 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2594 inherit, flags, env, cur_dir, startup_info, info);
2598 /**********************************************************************
2599 * exec_process
2601 static void exec_process( LPCWSTR name )
2603 HANDLE hFile;
2604 WCHAR *p;
2605 STARTUPINFOW startup_info;
2606 PROCESS_INFORMATION info;
2607 struct binary_info binary_info;
2609 hFile = open_exe_file( name, &binary_info );
2610 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2612 memset( &startup_info, 0, sizeof(startup_info) );
2613 startup_info.cb = sizeof(startup_info);
2615 /* Determine executable type */
2617 if (binary_info.flags & BINARY_FLAG_DLL)
2619 CloseHandle( hFile );
2620 return;
2623 switch (binary_info.type)
2625 case BINARY_PE:
2626 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x)\n",
2627 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2628 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2629 binary_info.arch );
2630 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2631 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2632 break;
2633 case BINARY_UNIX_LIB:
2634 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2635 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2636 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2637 break;
2638 case BINARY_UNKNOWN:
2639 /* check for .com or .pif extension */
2640 if (!(p = strrchrW( name, '.' ))) break;
2641 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2642 binary_info.type = BINARY_DOS;
2643 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2644 /* fall through */
2645 case BINARY_OS216:
2646 case BINARY_WIN16:
2647 case BINARY_DOS:
2648 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2649 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2650 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2651 break;
2652 default:
2653 break;
2655 CloseHandle( hFile );
2659 /***********************************************************************
2660 * wait_input_idle
2662 * Wrapper to call WaitForInputIdle USER function
2664 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2666 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2668 HMODULE mod = GetModuleHandleA( "user32.dll" );
2669 if (mod)
2671 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2672 if (ptr) return ptr( process, timeout );
2674 return 0;
2678 /***********************************************************************
2679 * WinExec (KERNEL32.@)
2681 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2683 PROCESS_INFORMATION info;
2684 STARTUPINFOA startup;
2685 char *cmdline;
2686 UINT ret;
2688 memset( &startup, 0, sizeof(startup) );
2689 startup.cb = sizeof(startup);
2690 startup.dwFlags = STARTF_USESHOWWINDOW;
2691 startup.wShowWindow = nCmdShow;
2693 /* cmdline needs to be writable for CreateProcess */
2694 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2695 strcpy( cmdline, lpCmdLine );
2697 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2698 0, NULL, NULL, &startup, &info ))
2700 /* Give 30 seconds to the app to come up */
2701 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2702 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2703 ret = 33;
2704 /* Close off the handles */
2705 CloseHandle( info.hThread );
2706 CloseHandle( info.hProcess );
2708 else if ((ret = GetLastError()) >= 32)
2710 FIXME("Strange error set by CreateProcess: %d\n", ret );
2711 ret = 11;
2713 HeapFree( GetProcessHeap(), 0, cmdline );
2714 return ret;
2718 /**********************************************************************
2719 * LoadModule (KERNEL32.@)
2721 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2723 LOADPARMS32 *params = paramBlock;
2724 PROCESS_INFORMATION info;
2725 STARTUPINFOA startup;
2726 DWORD ret;
2727 LPSTR cmdline, p;
2728 char filename[MAX_PATH];
2729 BYTE len;
2731 if (!name) return ERROR_FILE_NOT_FOUND;
2733 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2734 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2735 return GetLastError();
2737 len = (BYTE)params->lpCmdLine[0];
2738 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2739 return ERROR_NOT_ENOUGH_MEMORY;
2741 strcpy( cmdline, filename );
2742 p = cmdline + strlen(cmdline);
2743 *p++ = ' ';
2744 memcpy( p, params->lpCmdLine + 1, len );
2745 p[len] = 0;
2747 memset( &startup, 0, sizeof(startup) );
2748 startup.cb = sizeof(startup);
2749 if (params->lpCmdShow)
2751 startup.dwFlags = STARTF_USESHOWWINDOW;
2752 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2755 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2756 params->lpEnvAddress, NULL, &startup, &info ))
2758 /* Give 30 seconds to the app to come up */
2759 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2760 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2761 ret = 33;
2762 /* Close off the handles */
2763 CloseHandle( info.hThread );
2764 CloseHandle( info.hProcess );
2766 else if ((ret = GetLastError()) >= 32)
2768 FIXME("Strange error set by CreateProcess: %u\n", ret );
2769 ret = 11;
2772 HeapFree( GetProcessHeap(), 0, cmdline );
2773 return ret;
2777 /******************************************************************************
2778 * TerminateProcess (KERNEL32.@)
2780 * Terminates a process.
2782 * PARAMS
2783 * handle [I] Process to terminate.
2784 * exit_code [I] Exit code.
2786 * RETURNS
2787 * Success: TRUE.
2788 * Failure: FALSE, check GetLastError().
2790 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2792 NTSTATUS status;
2794 if (!handle)
2796 SetLastError( ERROR_INVALID_HANDLE );
2797 return FALSE;
2800 status = NtTerminateProcess( handle, exit_code );
2801 if (status) SetLastError( RtlNtStatusToDosError(status) );
2802 return !status;
2805 /***********************************************************************
2806 * ExitProcess (KERNEL32.@)
2808 * Exits the current process.
2810 * PARAMS
2811 * status [I] Status code to exit with.
2813 * RETURNS
2814 * Nothing.
2816 #ifdef __i386__
2817 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2818 "pushl %ebp\n\t"
2819 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2820 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2821 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2822 "pushl 8(%ebp)\n\t"
2823 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2824 "leave\n\t"
2825 "ret $4" )
2826 #else
2828 void WINAPI ExitProcess( DWORD status )
2830 RtlExitUserProcess( status );
2833 #endif
2835 /***********************************************************************
2836 * GetExitCodeProcess [KERNEL32.@]
2838 * Gets termination status of specified process.
2840 * PARAMS
2841 * hProcess [in] Handle to the process.
2842 * lpExitCode [out] Address to receive termination status.
2844 * RETURNS
2845 * Success: TRUE
2846 * Failure: FALSE
2848 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2850 NTSTATUS status;
2851 PROCESS_BASIC_INFORMATION pbi;
2853 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2854 sizeof(pbi), NULL);
2855 if (status == STATUS_SUCCESS)
2857 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2858 return TRUE;
2860 SetLastError( RtlNtStatusToDosError(status) );
2861 return FALSE;
2865 /***********************************************************************
2866 * SetErrorMode (KERNEL32.@)
2868 UINT WINAPI SetErrorMode( UINT mode )
2870 UINT old;
2872 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2873 &old, sizeof(old), NULL );
2874 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2875 &mode, sizeof(mode) );
2876 return old;
2879 /***********************************************************************
2880 * GetErrorMode (KERNEL32.@)
2882 UINT WINAPI GetErrorMode( void )
2884 UINT mode;
2886 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2887 &mode, sizeof(mode), NULL );
2888 return mode;
2891 /**********************************************************************
2892 * TlsAlloc [KERNEL32.@]
2894 * Allocates a thread local storage index.
2896 * RETURNS
2897 * Success: TLS index.
2898 * Failure: 0xFFFFFFFF
2900 DWORD WINAPI TlsAlloc( void )
2902 DWORD index;
2903 PEB * const peb = NtCurrentTeb()->Peb;
2905 RtlAcquirePebLock();
2906 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2907 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2908 else
2910 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2911 if (index != ~0U)
2913 if (!NtCurrentTeb()->TlsExpansionSlots &&
2914 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2915 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2917 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2918 index = ~0U;
2919 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2921 else
2923 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2924 index += TLS_MINIMUM_AVAILABLE;
2927 else SetLastError( ERROR_NO_MORE_ITEMS );
2929 RtlReleasePebLock();
2930 return index;
2934 /**********************************************************************
2935 * TlsFree [KERNEL32.@]
2937 * Releases a thread local storage index, making it available for reuse.
2939 * PARAMS
2940 * index [in] TLS index to free.
2942 * RETURNS
2943 * Success: TRUE
2944 * Failure: FALSE
2946 BOOL WINAPI TlsFree( DWORD index )
2948 BOOL ret;
2950 RtlAcquirePebLock();
2951 if (index >= TLS_MINIMUM_AVAILABLE)
2953 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2954 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2956 else
2958 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2959 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2961 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2962 else SetLastError( ERROR_INVALID_PARAMETER );
2963 RtlReleasePebLock();
2964 return ret;
2968 /**********************************************************************
2969 * TlsGetValue [KERNEL32.@]
2971 * Gets value in a thread's TLS slot.
2973 * PARAMS
2974 * index [in] TLS index to retrieve value for.
2976 * RETURNS
2977 * Success: Value stored in calling thread's TLS slot for index.
2978 * Failure: 0 and GetLastError() returns NO_ERROR.
2980 LPVOID WINAPI TlsGetValue( DWORD index )
2982 LPVOID ret;
2984 if (index < TLS_MINIMUM_AVAILABLE)
2986 ret = NtCurrentTeb()->TlsSlots[index];
2988 else
2990 index -= TLS_MINIMUM_AVAILABLE;
2991 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2993 SetLastError( ERROR_INVALID_PARAMETER );
2994 return NULL;
2996 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2997 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2999 SetLastError( ERROR_SUCCESS );
3000 return ret;
3004 /**********************************************************************
3005 * TlsSetValue [KERNEL32.@]
3007 * Stores a value in the thread's TLS slot.
3009 * PARAMS
3010 * index [in] TLS index to set value for.
3011 * value [in] Value to be stored.
3013 * RETURNS
3014 * Success: TRUE
3015 * Failure: FALSE
3017 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
3019 if (index < TLS_MINIMUM_AVAILABLE)
3021 NtCurrentTeb()->TlsSlots[index] = value;
3023 else
3025 index -= TLS_MINIMUM_AVAILABLE;
3026 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
3028 SetLastError( ERROR_INVALID_PARAMETER );
3029 return FALSE;
3031 if (!NtCurrentTeb()->TlsExpansionSlots &&
3032 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
3033 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
3035 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3036 return FALSE;
3038 NtCurrentTeb()->TlsExpansionSlots[index] = value;
3040 return TRUE;
3044 /***********************************************************************
3045 * GetProcessFlags (KERNEL32.@)
3047 DWORD WINAPI GetProcessFlags( DWORD processid )
3049 IMAGE_NT_HEADERS *nt;
3050 DWORD flags = 0;
3052 if (processid && processid != GetCurrentProcessId()) return 0;
3054 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3056 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
3057 flags |= PDB32_CONSOLE_PROC;
3059 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
3060 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
3061 return flags;
3065 /*********************************************************************
3066 * OpenProcess (KERNEL32.@)
3068 * Opens a handle to a process.
3070 * PARAMS
3071 * access [I] Desired access rights assigned to the returned handle.
3072 * inherit [I] Determines whether or not child processes will inherit the handle.
3073 * id [I] Process identifier of the process to get a handle to.
3075 * RETURNS
3076 * Success: Valid handle to the specified process.
3077 * Failure: NULL, check GetLastError().
3079 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
3081 NTSTATUS status;
3082 HANDLE handle;
3083 OBJECT_ATTRIBUTES attr;
3084 CLIENT_ID cid;
3086 cid.UniqueProcess = ULongToHandle(id);
3087 cid.UniqueThread = 0; /* FIXME ? */
3089 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3090 attr.RootDirectory = NULL;
3091 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3092 attr.SecurityDescriptor = NULL;
3093 attr.SecurityQualityOfService = NULL;
3094 attr.ObjectName = NULL;
3096 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3098 status = NtOpenProcess(&handle, access, &attr, &cid);
3099 if (status != STATUS_SUCCESS)
3101 SetLastError( RtlNtStatusToDosError(status) );
3102 return NULL;
3104 return handle;
3108 /*********************************************************************
3109 * GetProcessId (KERNEL32.@)
3111 * Gets the a unique identifier of a process.
3113 * PARAMS
3114 * hProcess [I] Handle to the process.
3116 * RETURNS
3117 * Success: TRUE.
3118 * Failure: FALSE, check GetLastError().
3120 * NOTES
3122 * The identifier is unique only on the machine and only until the process
3123 * exits (including system shutdown).
3125 DWORD WINAPI GetProcessId( HANDLE hProcess )
3127 NTSTATUS status;
3128 PROCESS_BASIC_INFORMATION pbi;
3130 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3131 sizeof(pbi), NULL);
3132 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3133 SetLastError( RtlNtStatusToDosError(status) );
3134 return 0;
3138 /*********************************************************************
3139 * CloseHandle (KERNEL32.@)
3141 * Closes a handle.
3143 * PARAMS
3144 * handle [I] Handle to close.
3146 * RETURNS
3147 * Success: TRUE.
3148 * Failure: FALSE, check GetLastError().
3150 BOOL WINAPI CloseHandle( HANDLE handle )
3152 NTSTATUS status;
3154 /* stdio handles need special treatment */
3155 if (handle == (HANDLE)STD_INPUT_HANDLE)
3156 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3157 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3158 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3159 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3160 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3162 if (is_console_handle(handle))
3163 return CloseConsoleHandle(handle);
3165 status = NtClose( handle );
3166 if (status) SetLastError( RtlNtStatusToDosError(status) );
3167 return !status;
3171 /*********************************************************************
3172 * GetHandleInformation (KERNEL32.@)
3174 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3176 OBJECT_DATA_INFORMATION info;
3177 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3179 if (status) SetLastError( RtlNtStatusToDosError(status) );
3180 else if (flags)
3182 *flags = 0;
3183 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3184 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3186 return !status;
3190 /*********************************************************************
3191 * SetHandleInformation (KERNEL32.@)
3193 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3195 OBJECT_DATA_INFORMATION info;
3196 NTSTATUS status;
3198 /* if not setting both fields, retrieve current value first */
3199 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3200 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3202 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3204 SetLastError( RtlNtStatusToDosError(status) );
3205 return FALSE;
3208 if (mask & HANDLE_FLAG_INHERIT)
3209 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3210 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3211 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3213 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3214 if (status) SetLastError( RtlNtStatusToDosError(status) );
3215 return !status;
3219 /*********************************************************************
3220 * DuplicateHandle (KERNEL32.@)
3222 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3223 HANDLE dest_process, HANDLE *dest,
3224 DWORD access, BOOL inherit, DWORD options )
3226 NTSTATUS status;
3228 if (is_console_handle(source))
3230 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3231 if (source_process != dest_process ||
3232 source_process != GetCurrentProcess())
3234 SetLastError(ERROR_INVALID_PARAMETER);
3235 return FALSE;
3237 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3238 return (*dest != INVALID_HANDLE_VALUE);
3240 status = NtDuplicateObject( source_process, source, dest_process, dest,
3241 access, inherit ? OBJ_INHERIT : 0, options );
3242 if (status) SetLastError( RtlNtStatusToDosError(status) );
3243 return !status;
3247 /***********************************************************************
3248 * ConvertToGlobalHandle (KERNEL32.@)
3250 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3252 HANDLE ret = INVALID_HANDLE_VALUE;
3253 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3254 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3255 return ret;
3259 /***********************************************************************
3260 * SetHandleContext (KERNEL32.@)
3262 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3264 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3265 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3266 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3267 return FALSE;
3271 /***********************************************************************
3272 * GetHandleContext (KERNEL32.@)
3274 DWORD WINAPI GetHandleContext(HANDLE hnd)
3276 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3277 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3278 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3279 return 0;
3283 /***********************************************************************
3284 * CreateSocketHandle (KERNEL32.@)
3286 HANDLE WINAPI CreateSocketHandle(void)
3288 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3289 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3290 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3291 return INVALID_HANDLE_VALUE;
3295 /***********************************************************************
3296 * SetPriorityClass (KERNEL32.@)
3298 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3300 NTSTATUS status;
3301 PROCESS_PRIORITY_CLASS ppc;
3303 ppc.Foreground = FALSE;
3304 switch (priorityclass)
3306 case IDLE_PRIORITY_CLASS:
3307 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3308 case BELOW_NORMAL_PRIORITY_CLASS:
3309 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3310 case NORMAL_PRIORITY_CLASS:
3311 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3312 case ABOVE_NORMAL_PRIORITY_CLASS:
3313 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3314 case HIGH_PRIORITY_CLASS:
3315 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3316 case REALTIME_PRIORITY_CLASS:
3317 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3318 default:
3319 SetLastError(ERROR_INVALID_PARAMETER);
3320 return FALSE;
3323 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3324 &ppc, sizeof(ppc));
3326 if (status != STATUS_SUCCESS)
3328 SetLastError( RtlNtStatusToDosError(status) );
3329 return FALSE;
3331 return TRUE;
3335 /***********************************************************************
3336 * GetPriorityClass (KERNEL32.@)
3338 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3340 NTSTATUS status;
3341 PROCESS_BASIC_INFORMATION pbi;
3343 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3344 sizeof(pbi), NULL);
3345 if (status != STATUS_SUCCESS)
3347 SetLastError( RtlNtStatusToDosError(status) );
3348 return 0;
3350 switch (pbi.BasePriority)
3352 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3353 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3354 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3355 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3356 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3357 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3359 SetLastError( ERROR_INVALID_PARAMETER );
3360 return 0;
3364 /***********************************************************************
3365 * SetProcessAffinityMask (KERNEL32.@)
3367 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3369 NTSTATUS status;
3371 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3372 &affmask, sizeof(DWORD_PTR));
3373 if (status)
3375 SetLastError( RtlNtStatusToDosError(status) );
3376 return FALSE;
3378 return TRUE;
3382 /**********************************************************************
3383 * GetProcessAffinityMask (KERNEL32.@)
3385 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3387 NTSTATUS status = STATUS_SUCCESS;
3389 if (process_mask)
3391 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3392 process_mask, sizeof(*process_mask), NULL )))
3393 SetLastError( RtlNtStatusToDosError(status) );
3395 if (system_mask && status == STATUS_SUCCESS)
3397 SYSTEM_BASIC_INFORMATION info;
3399 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3400 SetLastError( RtlNtStatusToDosError(status) );
3401 else
3402 *system_mask = info.ActiveProcessorsAffinityMask;
3404 return !status;
3408 /***********************************************************************
3409 * SetProcessAffinityUpdateMode (KERNEL32.@)
3411 BOOL WINAPI SetProcessAffinityUpdateMode( HANDLE process, DWORD flags )
3413 FIXME("(%p,0x%08x): stub\n", process, flags);
3414 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3415 return FALSE;
3419 /***********************************************************************
3420 * GetProcessVersion (KERNEL32.@)
3422 DWORD WINAPI GetProcessVersion( DWORD pid )
3424 HANDLE process;
3425 NTSTATUS status;
3426 PROCESS_BASIC_INFORMATION pbi;
3427 SIZE_T count;
3428 PEB peb;
3429 IMAGE_DOS_HEADER dos;
3430 IMAGE_NT_HEADERS nt;
3431 DWORD ver = 0;
3433 if (!pid || pid == GetCurrentProcessId())
3435 IMAGE_NT_HEADERS *pnt;
3437 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3438 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3439 pnt->OptionalHeader.MinorSubsystemVersion);
3440 return 0;
3443 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3444 if (!process) return 0;
3446 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3447 if (status) goto err;
3449 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3450 if (status || count != sizeof(peb)) goto err;
3452 memset(&dos, 0, sizeof(dos));
3453 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3454 if (status || count != sizeof(dos)) goto err;
3455 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3457 memset(&nt, 0, sizeof(nt));
3458 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3459 if (status || count != sizeof(nt)) goto err;
3460 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3462 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3464 err:
3465 CloseHandle(process);
3467 if (status != STATUS_SUCCESS)
3468 SetLastError(RtlNtStatusToDosError(status));
3470 return ver;
3474 /***********************************************************************
3475 * SetProcessWorkingSetSizeEx [KERNEL32.@]
3476 * Sets the min/max working set sizes for a specified process.
3478 * PARAMS
3479 * process [I] Handle to the process of interest
3480 * minset [I] Specifies minimum working set size
3481 * maxset [I] Specifies maximum working set size
3482 * flags [I] Flags to enforce working set sizes
3484 * RETURNS
3485 * Success: TRUE
3486 * Failure: FALSE
3488 BOOL WINAPI SetProcessWorkingSetSizeEx(HANDLE process, SIZE_T minset, SIZE_T maxset, DWORD flags)
3490 WARN("(%p,%ld,%ld,%x): stub - harmless\n", process, minset, maxset, flags);
3491 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3492 /* Trim the working set to zero */
3493 /* Swap the process out of physical RAM */
3495 return TRUE;
3498 /***********************************************************************
3499 * SetProcessWorkingSetSize [KERNEL32.@]
3500 * Sets the min/max working set sizes for a specified process.
3502 * PARAMS
3503 * process [I] Handle to the process of interest
3504 * minset [I] Specifies minimum working set size
3505 * maxset [I] Specifies maximum working set size
3507 * RETURNS
3508 * Success: TRUE
3509 * Failure: FALSE
3511 BOOL WINAPI SetProcessWorkingSetSize(HANDLE process, SIZE_T minset, SIZE_T maxset)
3513 return SetProcessWorkingSetSizeEx(process, minset, maxset, 0);
3516 /***********************************************************************
3517 * K32EmptyWorkingSet (KERNEL32.@)
3519 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3521 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3525 /***********************************************************************
3526 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3528 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3529 SIZE_T *maxset, DWORD *flags)
3531 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3532 /* 32 MB working set size */
3533 if (minset) *minset = 32*1024*1024;
3534 if (maxset) *maxset = 32*1024*1024;
3535 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3536 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3537 return TRUE;
3541 /***********************************************************************
3542 * GetProcessWorkingSetSize (KERNEL32.@)
3544 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3546 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3550 /***********************************************************************
3551 * SetProcessShutdownParameters (KERNEL32.@)
3553 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3555 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3556 shutdown_flags = flags;
3557 shutdown_priority = level;
3558 return TRUE;
3562 /***********************************************************************
3563 * GetProcessShutdownParameters (KERNEL32.@)
3566 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3568 *lpdwLevel = shutdown_priority;
3569 *lpdwFlags = shutdown_flags;
3570 return TRUE;
3574 /***********************************************************************
3575 * GetProcessPriorityBoost (KERNEL32.@)
3577 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3579 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3581 /* Report that no boost is present.. */
3582 *pDisablePriorityBoost = FALSE;
3584 return TRUE;
3587 /***********************************************************************
3588 * SetProcessPriorityBoost (KERNEL32.@)
3590 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3592 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3593 /* Say we can do it. I doubt the program will notice that we don't. */
3594 return TRUE;
3598 /***********************************************************************
3599 * ReadProcessMemory (KERNEL32.@)
3601 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3602 SIZE_T *bytes_read )
3604 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3605 if (status) SetLastError( RtlNtStatusToDosError(status) );
3606 return !status;
3610 /***********************************************************************
3611 * WriteProcessMemory (KERNEL32.@)
3613 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3614 SIZE_T *bytes_written )
3616 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3617 if (status) SetLastError( RtlNtStatusToDosError(status) );
3618 return !status;
3622 /****************************************************************************
3623 * FlushInstructionCache (KERNEL32.@)
3625 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3627 NTSTATUS status;
3628 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3629 if (status) SetLastError( RtlNtStatusToDosError(status) );
3630 return !status;
3634 /******************************************************************
3635 * GetProcessIoCounters (KERNEL32.@)
3637 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3639 NTSTATUS status;
3641 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3642 ioc, sizeof(*ioc), NULL);
3643 if (status) SetLastError( RtlNtStatusToDosError(status) );
3644 return !status;
3647 /******************************************************************
3648 * GetProcessHandleCount (KERNEL32.@)
3650 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3652 NTSTATUS status;
3654 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3655 cnt, sizeof(*cnt), NULL);
3656 if (status) SetLastError( RtlNtStatusToDosError(status) );
3657 return !status;
3660 /******************************************************************
3661 * QueryFullProcessImageNameA (KERNEL32.@)
3663 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3665 BOOL retval;
3666 DWORD pdwSizeW = *pdwSize;
3667 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3669 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3671 if(retval)
3672 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3673 lpExeName, *pdwSize, NULL, NULL));
3674 if(retval)
3675 *pdwSize = strlen(lpExeName);
3677 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3678 return retval;
3681 /******************************************************************
3682 * QueryFullProcessImageNameW (KERNEL32.@)
3684 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3686 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3687 UNICODE_STRING *dynamic_buffer = NULL;
3688 UNICODE_STRING *result = NULL;
3689 NTSTATUS status;
3690 DWORD needed;
3692 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3693 * is a DOS path and we depend on this. */
3694 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3695 sizeof(buffer) - sizeof(WCHAR), &needed);
3696 if (status == STATUS_INFO_LENGTH_MISMATCH)
3698 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3699 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3700 result = dynamic_buffer;
3702 else
3703 result = (PUNICODE_STRING)buffer;
3705 if (status) goto cleanup;
3707 if (dwFlags & PROCESS_NAME_NATIVE)
3709 WCHAR drive[3];
3710 WCHAR device[1024];
3711 DWORD ntlen, devlen;
3713 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3715 /* We cannot convert it to an NT device path so fail */
3716 status = STATUS_NO_SUCH_DEVICE;
3717 goto cleanup;
3720 /* Find this drive's NT device path */
3721 drive[0] = result->Buffer[0];
3722 drive[1] = ':';
3723 drive[2] = 0;
3724 if (!QueryDosDeviceW(drive, device, ARRAY_SIZE(device)))
3726 status = STATUS_NO_SUCH_DEVICE;
3727 goto cleanup;
3730 devlen = lstrlenW(device);
3731 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3732 if (ntlen + 1 > *pdwSize)
3734 status = STATUS_BUFFER_TOO_SMALL;
3735 goto cleanup;
3737 *pdwSize = ntlen;
3739 memcpy(lpExeName, device, devlen * sizeof(*device));
3740 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3741 lpExeName[*pdwSize] = 0;
3742 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3744 else
3746 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3748 status = STATUS_BUFFER_TOO_SMALL;
3749 goto cleanup;
3752 *pdwSize = result->Length/sizeof(WCHAR);
3753 memcpy( lpExeName, result->Buffer, result->Length );
3754 lpExeName[*pdwSize] = 0;
3757 cleanup:
3758 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3759 if (status) SetLastError( RtlNtStatusToDosError(status) );
3760 return !status;
3763 /***********************************************************************
3764 * K32GetProcessImageFileNameA (KERNEL32.@)
3766 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3768 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3771 /***********************************************************************
3772 * K32GetProcessImageFileNameW (KERNEL32.@)
3774 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3776 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3779 /***********************************************************************
3780 * K32EnumProcesses (KERNEL32.@)
3782 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3784 SYSTEM_PROCESS_INFORMATION *spi;
3785 ULONG size = 0x4000;
3786 void *buf = NULL;
3787 NTSTATUS status;
3789 do {
3790 size *= 2;
3791 HeapFree(GetProcessHeap(), 0, buf);
3792 buf = HeapAlloc(GetProcessHeap(), 0, size);
3793 if (!buf)
3794 return FALSE;
3796 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3797 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3799 if (status != STATUS_SUCCESS)
3801 HeapFree(GetProcessHeap(), 0, buf);
3802 SetLastError(RtlNtStatusToDosError(status));
3803 return FALSE;
3806 spi = buf;
3808 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3810 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3811 *lpcbUsed += sizeof(DWORD);
3813 if (spi->NextEntryOffset == 0)
3814 break;
3816 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3819 HeapFree(GetProcessHeap(), 0, buf);
3820 return TRUE;
3823 /***********************************************************************
3824 * K32QueryWorkingSet (KERNEL32.@)
3826 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3828 NTSTATUS status;
3830 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3832 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3834 if (status)
3836 SetLastError( RtlNtStatusToDosError( status ) );
3837 return FALSE;
3839 return TRUE;
3842 /***********************************************************************
3843 * K32QueryWorkingSetEx (KERNEL32.@)
3845 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3847 NTSTATUS status;
3849 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3851 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3853 if (status)
3855 SetLastError( RtlNtStatusToDosError( status ) );
3856 return FALSE;
3858 return TRUE;
3861 /***********************************************************************
3862 * K32GetProcessMemoryInfo (KERNEL32.@)
3864 * Retrieve memory usage information for a given process
3867 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3868 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3870 NTSTATUS status;
3871 VM_COUNTERS vmc;
3873 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3875 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3876 return FALSE;
3879 status = NtQueryInformationProcess(process, ProcessVmCounters,
3880 &vmc, sizeof(vmc), NULL);
3882 if (status)
3884 SetLastError(RtlNtStatusToDosError(status));
3885 return FALSE;
3888 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3889 pmc->PageFaultCount = vmc.PageFaultCount;
3890 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3891 pmc->WorkingSetSize = vmc.WorkingSetSize;
3892 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3893 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3894 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3895 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3896 pmc->PagefileUsage = vmc.PagefileUsage;
3897 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3899 return TRUE;
3902 /***********************************************************************
3903 * ProcessIdToSessionId (KERNEL32.@)
3904 * This function is available on Terminal Server 4SP4 and Windows 2000
3906 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3908 if (procid != GetCurrentProcessId())
3909 FIXME("Unsupported for other processes.\n");
3911 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3912 return TRUE;
3916 /***********************************************************************
3917 * RegisterServiceProcess (KERNEL32.@)
3919 * A service process calls this function to ensure that it continues to run
3920 * even after a user logged off.
3922 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3924 /* I don't think that Wine needs to do anything in this function */
3925 return 1; /* success */
3929 /**********************************************************************
3930 * IsWow64Process (KERNEL32.@)
3932 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3934 ULONG_PTR pbi;
3935 NTSTATUS status;
3937 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3939 if (status != STATUS_SUCCESS)
3941 SetLastError( RtlNtStatusToDosError( status ) );
3942 return FALSE;
3944 *Wow64Process = (pbi != 0);
3945 return TRUE;
3949 /***********************************************************************
3950 * GetCurrentProcess (KERNEL32.@)
3952 * Get a handle to the current process.
3954 * PARAMS
3955 * None.
3957 * RETURNS
3958 * A handle representing the current process.
3960 #undef GetCurrentProcess
3961 HANDLE WINAPI GetCurrentProcess(void)
3963 return (HANDLE)~(ULONG_PTR)0;
3966 /***********************************************************************
3967 * GetLogicalProcessorInformation (KERNEL32.@)
3969 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3971 NTSTATUS status;
3973 TRACE("(%p,%p)\n", buffer, pBufLen);
3975 if(!pBufLen)
3977 SetLastError(ERROR_INVALID_PARAMETER);
3978 return FALSE;
3981 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3983 if (status == STATUS_INFO_LENGTH_MISMATCH)
3985 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3986 return FALSE;
3988 if (status != STATUS_SUCCESS)
3990 SetLastError( RtlNtStatusToDosError( status ) );
3991 return FALSE;
3993 return TRUE;
3996 /***********************************************************************
3997 * GetLogicalProcessorInformationEx (KERNEL32.@)
3999 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
4001 NTSTATUS status;
4003 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
4005 if (!len)
4007 SetLastError( ERROR_INVALID_PARAMETER );
4008 return FALSE;
4011 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
4012 buffer, *len, len );
4013 if (status == STATUS_INFO_LENGTH_MISMATCH)
4015 SetLastError( ERROR_INSUFFICIENT_BUFFER );
4016 return FALSE;
4018 if (status != STATUS_SUCCESS)
4020 SetLastError( RtlNtStatusToDosError( status ) );
4021 return FALSE;
4023 return TRUE;
4026 /***********************************************************************
4027 * CmdBatNotification (KERNEL32.@)
4029 * Notifies the system that a batch file has started or finished.
4031 * PARAMS
4032 * bBatchRunning [I] TRUE if a batch file has started or
4033 * FALSE if a batch file has finished executing.
4035 * RETURNS
4036 * Unknown.
4038 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
4040 FIXME("%d\n", bBatchRunning);
4041 return FALSE;
4044 /***********************************************************************
4045 * RegisterApplicationRestart (KERNEL32.@)
4047 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
4049 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
4051 return S_OK;
4054 /**********************************************************************
4055 * WTSGetActiveConsoleSessionId (KERNEL32.@)
4057 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
4059 static int once;
4060 if (!once++) FIXME("stub\n");
4061 /* Return current session id. */
4062 return NtCurrentTeb()->Peb->SessionId;
4065 /**********************************************************************
4066 * GetSystemDEPPolicy (KERNEL32.@)
4068 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
4070 FIXME("stub\n");
4071 return OptIn;
4074 /**********************************************************************
4075 * SetProcessDEPPolicy (KERNEL32.@)
4077 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
4079 FIXME("(%d): stub\n", newDEP);
4080 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4081 return FALSE;
4084 /**********************************************************************
4085 * ApplicationRecoveryFinished (KERNEL32.@)
4087 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
4089 FIXME(": stub\n");
4090 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4093 /**********************************************************************
4094 * ApplicationRecoveryInProgress (KERNEL32.@)
4096 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
4098 FIXME(":%p stub\n", canceled);
4099 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4100 return E_FAIL;
4103 /**********************************************************************
4104 * RegisterApplicationRecoveryCallback (KERNEL32.@)
4106 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
4108 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
4109 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4110 return E_FAIL;
4113 /***********************************************************************
4114 * GetApplicationRestartSettings (KERNEL32.@)
4116 HRESULT WINAPI GetApplicationRestartSettings(HANDLE process, WCHAR *cmdline, DWORD *size, DWORD *flags)
4118 FIXME("%p, %p, %p, %p)\n", process, cmdline, size, flags);
4119 return E_NOTIMPL;
4122 /**********************************************************************
4123 * GetNumaHighestNodeNumber (KERNEL32.@)
4125 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4127 *highestnode = 0;
4128 FIXME("(%p): semi-stub\n", highestnode);
4129 return TRUE;
4132 /**********************************************************************
4133 * GetNumaNodeProcessorMask (KERNEL32.@)
4135 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4137 FIXME("(%c %p): stub\n", node, mask);
4138 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4139 return FALSE;
4142 /**********************************************************************
4143 * GetNumaNodeProcessorMaskEx (KERNEL32.@)
4145 BOOL WINAPI GetNumaNodeProcessorMaskEx(USHORT node, PGROUP_AFFINITY mask)
4147 FIXME("(%hu %p): stub\n", node, mask);
4148 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4149 return FALSE;
4152 /**********************************************************************
4153 * GetNumaAvailableMemoryNode (KERNEL32.@)
4155 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4157 FIXME("(%c %p): stub\n", node, available_bytes);
4158 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4159 return FALSE;
4162 /***********************************************************************
4163 * GetNumaProcessorNode (KERNEL32.@)
4165 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4167 SYSTEM_INFO si;
4169 TRACE("(%d, %p)\n", processor, node);
4171 GetSystemInfo( &si );
4172 if (processor < si.dwNumberOfProcessors)
4174 *node = 0;
4175 return TRUE;
4178 *node = 0xFF;
4179 SetLastError(ERROR_INVALID_PARAMETER);
4180 return FALSE;
4183 /**********************************************************************
4184 * GetProcessDEPPolicy (KERNEL32.@)
4186 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4188 NTSTATUS status;
4189 ULONG dep_flags;
4191 TRACE("(%p %p %p)\n", process, flags, permanent);
4193 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4194 &dep_flags, sizeof(dep_flags), NULL );
4195 if (!status)
4198 if (flags)
4200 *flags = 0;
4201 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4202 *flags |= PROCESS_DEP_ENABLE;
4203 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4204 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4207 if (permanent)
4208 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4211 if (status) SetLastError( RtlNtStatusToDosError(status) );
4212 return !status;
4215 /**********************************************************************
4216 * FlushProcessWriteBuffers (KERNEL32.@)
4218 VOID WINAPI FlushProcessWriteBuffers(void)
4220 static int once = 0;
4222 if (!once++)
4223 FIXME(": stub\n");
4226 /***********************************************************************
4227 * UnregisterApplicationRestart (KERNEL32.@)
4229 HRESULT WINAPI UnregisterApplicationRestart(void)
4231 FIXME(": stub\n");
4232 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4233 return S_OK;
4236 struct proc_thread_attr
4238 DWORD_PTR attr;
4239 SIZE_T size;
4240 void *value;
4243 struct _PROC_THREAD_ATTRIBUTE_LIST
4245 DWORD mask; /* bitmask of items in list */
4246 DWORD size; /* max number of items in list */
4247 DWORD count; /* number of items in list */
4248 DWORD pad;
4249 DWORD_PTR unk;
4250 struct proc_thread_attr attrs[1];
4253 /***********************************************************************
4254 * InitializeProcThreadAttributeList (KERNEL32.@)
4256 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4257 DWORD count, DWORD flags, SIZE_T *size)
4259 SIZE_T needed;
4260 BOOL ret = FALSE;
4262 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4264 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4265 if (list && *size >= needed)
4267 list->mask = 0;
4268 list->size = count;
4269 list->count = 0;
4270 list->unk = 0;
4271 ret = TRUE;
4273 else
4274 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4276 *size = needed;
4277 return ret;
4280 /***********************************************************************
4281 * UpdateProcThreadAttribute (KERNEL32.@)
4283 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4284 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4285 void *prev_ret, SIZE_T *size_ret)
4287 DWORD mask;
4288 struct proc_thread_attr *entry;
4290 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4292 if (list->count >= list->size)
4294 SetLastError(ERROR_GEN_FAILURE);
4295 return FALSE;
4298 switch (attr)
4300 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4301 if (size != sizeof(HANDLE))
4303 SetLastError(ERROR_BAD_LENGTH);
4304 return FALSE;
4306 break;
4308 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4309 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4311 SetLastError(ERROR_BAD_LENGTH);
4312 return FALSE;
4314 break;
4316 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4317 if (size != sizeof(PROCESSOR_NUMBER))
4319 SetLastError(ERROR_BAD_LENGTH);
4320 return FALSE;
4322 break;
4324 case PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY:
4325 if (size != sizeof(DWORD) && size != sizeof(DWORD64))
4327 SetLastError(ERROR_BAD_LENGTH);
4328 return FALSE;
4330 break;
4332 case PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY:
4333 if (size != sizeof(DWORD) && size != sizeof(DWORD64) && size != sizeof(DWORD64) * 2)
4335 SetLastError(ERROR_BAD_LENGTH);
4336 return FALSE;
4338 break;
4340 default:
4341 SetLastError(ERROR_NOT_SUPPORTED);
4342 FIXME("Unhandled attribute number %lu\n", attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4343 return FALSE;
4346 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4348 if (list->mask & mask)
4350 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4351 return FALSE;
4354 list->mask |= mask;
4356 entry = list->attrs + list->count;
4357 entry->attr = attr;
4358 entry->size = size;
4359 entry->value = value;
4360 list->count++;
4362 return TRUE;
4365 /***********************************************************************
4366 * CreateUmsCompletionList (KERNEL32.@)
4368 BOOL WINAPI CreateUmsCompletionList(PUMS_COMPLETION_LIST *list)
4370 FIXME( "%p: stub\n", list );
4371 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4372 return FALSE;
4375 /***********************************************************************
4376 * CreateUmsThreadContext (KERNEL32.@)
4378 BOOL WINAPI CreateUmsThreadContext(PUMS_CONTEXT *ctx)
4380 FIXME( "%p: stub\n", ctx );
4381 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4382 return FALSE;
4385 /***********************************************************************
4386 * DeleteProcThreadAttributeList (KERNEL32.@)
4388 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4390 return;
4393 /***********************************************************************
4394 * DeleteUmsCompletionList (KERNEL32.@)
4396 BOOL WINAPI DeleteUmsCompletionList(PUMS_COMPLETION_LIST list)
4398 FIXME( "%p: stub\n", list );
4399 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4400 return FALSE;
4403 /***********************************************************************
4404 * DeleteUmsThreadContext (KERNEL32.@)
4406 BOOL WINAPI DeleteUmsThreadContext(PUMS_CONTEXT ctx)
4408 FIXME( "%p: stub\n", ctx );
4409 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4410 return FALSE;
4413 /***********************************************************************
4414 * DequeueUmsCompletionListItems (KERNEL32.@)
4416 BOOL WINAPI DequeueUmsCompletionListItems(void *list, DWORD timeout, PUMS_CONTEXT *ctx)
4418 FIXME( "%p,%08x,%p: stub\n", list, timeout, ctx );
4419 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4420 return FALSE;
4423 /***********************************************************************
4424 * EnterUmsSchedulingMode (KERNEL32.@)
4426 BOOL WINAPI EnterUmsSchedulingMode(UMS_SCHEDULER_STARTUP_INFO *info)
4428 FIXME( "%p: stub\n", info );
4429 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4430 return FALSE;
4433 /***********************************************************************
4434 * ExecuteUmsThread (KERNEL32.@)
4436 BOOL WINAPI ExecuteUmsThread(PUMS_CONTEXT ctx)
4438 FIXME( "%p: stub\n", ctx );
4439 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4440 return FALSE;
4443 /***********************************************************************
4444 * GetCurrentUmsThread (KERNEL32.@)
4446 PUMS_CONTEXT WINAPI GetCurrentUmsThread(void)
4448 FIXME( "stub\n" );
4449 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4450 return FALSE;
4453 /***********************************************************************
4454 * GetNextUmsListItem (KERNEL32.@)
4456 PUMS_CONTEXT WINAPI GetNextUmsListItem(PUMS_CONTEXT ctx)
4458 FIXME( "%p: stub\n", ctx );
4459 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4460 return NULL;
4463 /***********************************************************************
4464 * GetUmsCompletionListEvent (KERNEL32.@)
4466 BOOL WINAPI GetUmsCompletionListEvent(PUMS_COMPLETION_LIST list, HANDLE *event)
4468 FIXME( "%p,%p: stub\n", list, event );
4469 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4470 return FALSE;
4473 /***********************************************************************
4474 * QueryUmsThreadInformation (KERNEL32.@)
4476 BOOL WINAPI QueryUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4477 void *buf, ULONG length, ULONG *ret_length)
4479 FIXME( "%p,%08x,%p,%08x,%p: stub\n", ctx, class, buf, length, ret_length );
4480 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4481 return FALSE;
4484 /***********************************************************************
4485 * SetUmsThreadInformation (KERNEL32.@)
4487 BOOL WINAPI SetUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4488 void *buf, ULONG length)
4490 FIXME( "%p,%08x,%p,%08x: stub\n", ctx, class, buf, length );
4491 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4492 return FALSE;
4495 /***********************************************************************
4496 * UmsThreadYield (KERNEL32.@)
4498 BOOL WINAPI UmsThreadYield(void *param)
4500 FIXME( "%p: stub\n", param );
4501 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4502 return FALSE;
4505 /**********************************************************************
4506 * BaseFlushAppcompatCache (KERNEL32.@)
4508 BOOL WINAPI BaseFlushAppcompatCache(void)
4510 FIXME(": stub\n");
4511 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4512 return FALSE;
4515 /**********************************************************************
4516 * SetProcessMitigationPolicy (KERNEL32.@)
4518 BOOL WINAPI SetProcessMitigationPolicy(PROCESS_MITIGATION_POLICY policy, void *buffer, SIZE_T length)
4520 FIXME("(%d, %p, %lu): stub\n", policy, buffer, length);
4522 return TRUE;