kernel32: Remove the DOS/Win16/OS2 binary distinction.
[wine.git] / dlls / kernel32 / process.c
blobe1590474e46fe4a5bd8e2a830caae08152e25cdb
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 alloc_object_attributes( psa, &objattr, &attr_len );
2124 SERVER_START_REQ( new_process )
2126 req->inherit_all = inherit;
2127 req->create_flags = flags;
2128 req->socket_fd = socketfd[1];
2129 req->exe_file = wine_server_obj_handle( hFile );
2130 req->access = PROCESS_ALL_ACCESS;
2131 req->cpu = cpu;
2132 req->info_size = startup_info_size;
2133 wine_server_add_data( req, objattr, attr_len );
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;
2144 HeapFree( GetProcessHeap(), 0, objattr );
2146 if (!status)
2148 alloc_object_attributes( tsa, &objattr, &attr_len );
2149 SERVER_START_REQ( new_thread )
2151 req->process = wine_server_obj_handle( process_handle );
2152 req->access = THREAD_ALL_ACCESS;
2153 req->suspend = !!(flags & CREATE_SUSPENDED);
2154 req->request_fd = -1;
2155 wine_server_add_data( req, objattr, attr_len );
2156 if (!(status = wine_server_call( req )))
2158 info->hProcess = process_handle;
2159 info->hThread = wine_server_ptr_handle( reply->handle );
2160 info->dwThreadId = reply->tid;
2163 SERVER_END_REQ;
2164 HeapFree( GetProcessHeap(), 0, objattr );
2167 RtlReleasePebLock();
2168 if (status)
2170 switch (status)
2172 case STATUS_INVALID_IMAGE_WIN_64:
2173 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename) );
2174 break;
2175 case STATUS_INVALID_IMAGE_FORMAT:
2176 ERR( "%s not supported on this installation (%s binary)\n",
2177 debugstr_w(filename), cpu_names[cpu] );
2178 break;
2180 close( socketfd[0] );
2181 CloseHandle( process_handle );
2182 HeapFree( GetProcessHeap(), 0, startup_info );
2183 HeapFree( GetProcessHeap(), 0, winedebug );
2184 SetLastError( RtlNtStatusToDosError( status ));
2185 return FALSE;
2188 if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
2190 if (startup_info->hstdin)
2191 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
2192 FILE_READ_DATA, &stdin_fd, NULL );
2193 if (startup_info->hstdout)
2194 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
2195 FILE_WRITE_DATA, &stdout_fd, NULL );
2197 HeapFree( GetProcessHeap(), 0, startup_info );
2199 /* create the child process */
2201 pid = exec_loader( cmd_line, flags, socketfd[0], stdin_fd, stdout_fd, unixdir,
2202 winedebug, binary_info, FALSE );
2204 if (stdin_fd != -1) close( stdin_fd );
2205 if (stdout_fd != -1) close( stdout_fd );
2206 close( socketfd[0] );
2207 HeapFree( GetProcessHeap(), 0, winedebug );
2208 if (pid == -1)
2210 FILE_SetDosError();
2211 goto error;
2214 /* wait for the new process info to be ready */
2216 WaitForSingleObject( process_info, INFINITE );
2217 SERVER_START_REQ( get_new_process_info )
2219 req->info = wine_server_obj_handle( process_info );
2220 wine_server_call( req );
2221 success = reply->success;
2222 err = reply->exit_code;
2224 SERVER_END_REQ;
2226 if (!success)
2228 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2229 goto error;
2231 CloseHandle( process_info );
2232 return success;
2234 error:
2235 CloseHandle( process_info );
2236 CloseHandle( info->hProcess );
2237 CloseHandle( info->hThread );
2238 info->hProcess = info->hThread = 0;
2239 info->dwProcessId = info->dwThreadId = 0;
2240 return FALSE;
2244 /***********************************************************************
2245 * create_vdm_process
2247 * Create a new VDM process for a 16-bit or DOS application.
2249 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
2250 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2251 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2252 LPPROCESS_INFORMATION info, LPCSTR unixdir,
2253 const struct binary_info *binary_info, int exec_only )
2255 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2257 BOOL ret;
2258 WCHAR buffer[MAX_PATH];
2259 LPWSTR new_cmd_line;
2261 if (!(ret = GetFullPathNameW(filename, MAX_PATH, buffer, NULL)))
2262 return FALSE;
2264 new_cmd_line = HeapAlloc(GetProcessHeap(), 0,
2265 (strlenW(buffer) + strlenW(cmd_line) + 30) * sizeof(WCHAR));
2267 if (!new_cmd_line)
2269 SetLastError( ERROR_OUTOFMEMORY );
2270 return FALSE;
2272 sprintfW(new_cmd_line, argsW, winevdmW, buffer, cmd_line);
2273 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
2274 flags, startup, info, unixdir, binary_info, exec_only );
2275 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2276 return ret;
2280 /***********************************************************************
2281 * create_cmd_process
2283 * Create a new cmd shell process for a .BAT file.
2285 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
2286 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2287 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2288 LPPROCESS_INFORMATION info )
2291 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2292 static const WCHAR cmdW[] = {'\\','c','m','d','.','e','x','e',0};
2293 static const WCHAR slashscW[] = {' ','/','s','/','c',' ',0};
2294 static const WCHAR quotW[] = {'"',0};
2295 WCHAR comspec[MAX_PATH];
2296 WCHAR *newcmdline;
2297 BOOL ret;
2299 if (!GetEnvironmentVariableW( comspecW, comspec, ARRAY_SIZE( comspec )))
2301 GetSystemDirectoryW( comspec, (sizeof(comspec) - sizeof(cmdW))/sizeof(WCHAR) );
2302 strcatW( comspec, cmdW );
2304 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2305 (strlenW(comspec) + 7 + strlenW(cmd_line) + 2) * sizeof(WCHAR))))
2306 return FALSE;
2308 strcpyW( newcmdline, comspec );
2309 strcatW( newcmdline, slashscW );
2310 strcatW( newcmdline, quotW );
2311 strcatW( newcmdline, cmd_line );
2312 strcatW( newcmdline, quotW );
2313 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2314 flags, env, cur_dir, startup, info );
2315 HeapFree( GetProcessHeap(), 0, newcmdline );
2316 return ret;
2320 /*************************************************************************
2321 * get_file_name
2323 * Helper for CreateProcess: retrieve the file name to load from the
2324 * app name and command line. Store the file name in buffer, and
2325 * return a possibly modified command line.
2326 * Also returns a handle to the opened file if it's a Windows binary.
2328 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2329 int buflen, HANDLE *handle, struct binary_info *binary_info )
2331 static const WCHAR quotesW[] = {'"','%','s','"',0};
2333 WCHAR *name, *pos, *first_space, *ret = NULL;
2334 const WCHAR *p;
2336 /* if we have an app name, everything is easy */
2338 if (appname)
2340 /* use the unmodified app name as file name */
2341 lstrcpynW( buffer, appname, buflen );
2342 *handle = open_exe_file( buffer, binary_info );
2343 if (!(ret = cmdline) || !cmdline[0])
2345 /* no command-line, create one */
2346 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2347 sprintfW( ret, quotesW, appname );
2349 return ret;
2352 /* first check for a quoted file name */
2354 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2356 int len = p - cmdline - 1;
2357 /* extract the quoted portion as file name */
2358 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2359 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2360 name[len] = 0;
2362 if (!find_exe_file( name, buffer, buflen, handle, binary_info )) goto done;
2363 ret = cmdline; /* no change necessary */
2364 goto done;
2367 /* now try the command-line word by word */
2369 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2370 return NULL;
2371 pos = name;
2372 p = cmdline;
2373 first_space = NULL;
2375 for (;;)
2377 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2378 *pos = 0;
2379 if (find_exe_file( name, buffer, buflen, handle, binary_info ))
2381 ret = cmdline;
2382 break;
2384 if (!first_space) first_space = pos;
2385 if (!(*pos++ = *p++)) break;
2388 if (!ret)
2390 SetLastError( ERROR_FILE_NOT_FOUND );
2392 else if (first_space) /* build a new command-line with quotes */
2394 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2395 goto done;
2396 sprintfW( ret, quotesW, name );
2397 strcatW( ret, p );
2400 done:
2401 HeapFree( GetProcessHeap(), 0, name );
2402 return ret;
2406 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2407 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2408 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2409 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2410 LPPROCESS_INFORMATION info )
2412 BOOL retv = FALSE;
2413 HANDLE hFile = 0;
2414 char *unixdir = NULL;
2415 WCHAR name[MAX_PATH];
2416 WCHAR *tidy_cmdline, *p, *envW = env;
2417 struct binary_info binary_info;
2419 /* Process the AppName and/or CmdLine to get module name and path */
2421 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2423 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, ARRAY_SIZE( name ),
2424 &hFile, &binary_info )))
2425 return FALSE;
2426 if (hFile == INVALID_HANDLE_VALUE) goto done;
2428 /* Warn if unsupported features are used */
2430 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2431 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2432 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2433 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2434 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2436 if (cur_dir)
2438 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2440 SetLastError(ERROR_DIRECTORY);
2441 goto done;
2444 else
2446 WCHAR buf[MAX_PATH];
2447 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2450 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
2452 char *e = env;
2453 DWORD lenW;
2455 while (*e) e += strlen(e) + 1;
2456 e++; /* final null */
2457 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, NULL, 0 );
2458 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2459 MultiByteToWideChar( CP_ACP, 0, env, e - (char*)env, envW, lenW );
2460 flags |= CREATE_UNICODE_ENVIRONMENT;
2463 info->hThread = info->hProcess = 0;
2464 info->dwProcessId = info->dwThreadId = 0;
2466 if (binary_info.flags & BINARY_FLAG_DLL)
2468 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2469 SetLastError( ERROR_BAD_EXE_FORMAT );
2471 else switch (binary_info.type)
2473 case BINARY_PE:
2474 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x%s)\n",
2475 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2476 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2477 binary_info.arch, (binary_info.flags & BINARY_FLAG_FAKEDLL) ? ", fakedll" : "" );
2478 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2479 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2480 break;
2481 case BINARY_WIN16:
2482 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2483 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2484 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2485 break;
2486 case BINARY_UNIX_LIB:
2487 TRACE( "starting %s as %d-bit Winelib app\n",
2488 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32 );
2489 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2490 inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2491 break;
2492 case BINARY_UNKNOWN:
2493 /* check for .com or .bat extension */
2494 if ((p = strrchrW( name, '.' )))
2496 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2498 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2499 binary_info.type = BINARY_WIN16;
2500 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2501 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2502 inherit, flags, startup_info, info, unixdir,
2503 &binary_info, FALSE );
2504 break;
2506 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2508 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2509 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2510 inherit, flags, startup_info, info );
2511 break;
2514 /* fall through */
2515 case BINARY_UNIX_EXE:
2517 /* unknown file, try as unix executable */
2518 char *unix_name;
2520 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2522 if ((unix_name = wine_get_unix_file_name( name )))
2524 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2525 HeapFree( GetProcessHeap(), 0, unix_name );
2528 break;
2530 if (hFile) CloseHandle( hFile );
2532 done:
2533 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2534 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2535 HeapFree( GetProcessHeap(), 0, unixdir );
2536 if (retv)
2537 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2538 return retv;
2542 /**********************************************************************
2543 * CreateProcessA (KERNEL32.@)
2545 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2546 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2547 DWORD flags, LPVOID env, LPCSTR cur_dir,
2548 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2550 BOOL ret = FALSE;
2551 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2552 UNICODE_STRING desktopW, titleW;
2553 STARTUPINFOW infoW;
2555 desktopW.Buffer = NULL;
2556 titleW.Buffer = NULL;
2557 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2558 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2559 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2561 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2562 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2564 memcpy( &infoW, startup_info, sizeof(infoW) );
2565 infoW.lpDesktop = desktopW.Buffer;
2566 infoW.lpTitle = titleW.Buffer;
2568 if (startup_info->lpReserved)
2569 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2570 debugstr_a(startup_info->lpReserved));
2572 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2573 inherit, flags, env, cur_dirW, &infoW, info );
2574 done:
2575 HeapFree( GetProcessHeap(), 0, app_nameW );
2576 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2577 HeapFree( GetProcessHeap(), 0, cur_dirW );
2578 RtlFreeUnicodeString( &desktopW );
2579 RtlFreeUnicodeString( &titleW );
2580 return ret;
2584 /**********************************************************************
2585 * CreateProcessW (KERNEL32.@)
2587 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2588 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2589 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2590 LPPROCESS_INFORMATION info )
2592 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2593 inherit, flags, env, cur_dir, startup_info, info);
2597 /**********************************************************************
2598 * exec_process
2600 static void exec_process( LPCWSTR name )
2602 HANDLE hFile;
2603 WCHAR *p;
2604 STARTUPINFOW startup_info;
2605 PROCESS_INFORMATION info;
2606 struct binary_info binary_info;
2608 hFile = open_exe_file( name, &binary_info );
2609 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2611 memset( &startup_info, 0, sizeof(startup_info) );
2612 startup_info.cb = sizeof(startup_info);
2614 /* Determine executable type */
2616 if (binary_info.flags & BINARY_FLAG_DLL)
2618 CloseHandle( hFile );
2619 return;
2622 switch (binary_info.type)
2624 case BINARY_PE:
2625 TRACE( "starting %s as Win%d binary (%s-%s, arch %04x)\n",
2626 debugstr_w(name), (binary_info.flags & BINARY_FLAG_64BIT) ? 64 : 32,
2627 wine_dbgstr_longlong(binary_info.res_start), wine_dbgstr_longlong(binary_info.res_end),
2628 binary_info.arch );
2629 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2630 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2631 break;
2632 case BINARY_UNIX_LIB:
2633 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2634 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2635 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2636 break;
2637 case BINARY_UNKNOWN:
2638 /* check for .com or .pif extension */
2639 if (!(p = strrchrW( name, '.' ))) break;
2640 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2641 binary_info.type = BINARY_WIN16;
2642 binary_info.arch = IMAGE_FILE_MACHINE_I386;
2643 /* fall through */
2644 case BINARY_WIN16:
2645 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2646 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2647 FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2648 break;
2649 default:
2650 break;
2652 CloseHandle( hFile );
2656 /***********************************************************************
2657 * wait_input_idle
2659 * Wrapper to call WaitForInputIdle USER function
2661 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2663 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2665 HMODULE mod = GetModuleHandleA( "user32.dll" );
2666 if (mod)
2668 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2669 if (ptr) return ptr( process, timeout );
2671 return 0;
2675 /***********************************************************************
2676 * WinExec (KERNEL32.@)
2678 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2680 PROCESS_INFORMATION info;
2681 STARTUPINFOA startup;
2682 char *cmdline;
2683 UINT ret;
2685 memset( &startup, 0, sizeof(startup) );
2686 startup.cb = sizeof(startup);
2687 startup.dwFlags = STARTF_USESHOWWINDOW;
2688 startup.wShowWindow = nCmdShow;
2690 /* cmdline needs to be writable for CreateProcess */
2691 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2692 strcpy( cmdline, lpCmdLine );
2694 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2695 0, NULL, NULL, &startup, &info ))
2697 /* Give 30 seconds to the app to come up */
2698 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2699 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2700 ret = 33;
2701 /* Close off the handles */
2702 CloseHandle( info.hThread );
2703 CloseHandle( info.hProcess );
2705 else if ((ret = GetLastError()) >= 32)
2707 FIXME("Strange error set by CreateProcess: %d\n", ret );
2708 ret = 11;
2710 HeapFree( GetProcessHeap(), 0, cmdline );
2711 return ret;
2715 /**********************************************************************
2716 * LoadModule (KERNEL32.@)
2718 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2720 LOADPARMS32 *params = paramBlock;
2721 PROCESS_INFORMATION info;
2722 STARTUPINFOA startup;
2723 DWORD ret;
2724 LPSTR cmdline, p;
2725 char filename[MAX_PATH];
2726 BYTE len;
2728 if (!name) return ERROR_FILE_NOT_FOUND;
2730 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2731 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2732 return GetLastError();
2734 len = (BYTE)params->lpCmdLine[0];
2735 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2736 return ERROR_NOT_ENOUGH_MEMORY;
2738 strcpy( cmdline, filename );
2739 p = cmdline + strlen(cmdline);
2740 *p++ = ' ';
2741 memcpy( p, params->lpCmdLine + 1, len );
2742 p[len] = 0;
2744 memset( &startup, 0, sizeof(startup) );
2745 startup.cb = sizeof(startup);
2746 if (params->lpCmdShow)
2748 startup.dwFlags = STARTF_USESHOWWINDOW;
2749 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2752 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2753 params->lpEnvAddress, NULL, &startup, &info ))
2755 /* Give 30 seconds to the app to come up */
2756 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2757 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2758 ret = 33;
2759 /* Close off the handles */
2760 CloseHandle( info.hThread );
2761 CloseHandle( info.hProcess );
2763 else if ((ret = GetLastError()) >= 32)
2765 FIXME("Strange error set by CreateProcess: %u\n", ret );
2766 ret = 11;
2769 HeapFree( GetProcessHeap(), 0, cmdline );
2770 return ret;
2774 /******************************************************************************
2775 * TerminateProcess (KERNEL32.@)
2777 * Terminates a process.
2779 * PARAMS
2780 * handle [I] Process to terminate.
2781 * exit_code [I] Exit code.
2783 * RETURNS
2784 * Success: TRUE.
2785 * Failure: FALSE, check GetLastError().
2787 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2789 NTSTATUS status;
2791 if (!handle)
2793 SetLastError( ERROR_INVALID_HANDLE );
2794 return FALSE;
2797 status = NtTerminateProcess( handle, exit_code );
2798 if (status) SetLastError( RtlNtStatusToDosError(status) );
2799 return !status;
2802 /***********************************************************************
2803 * ExitProcess (KERNEL32.@)
2805 * Exits the current process.
2807 * PARAMS
2808 * status [I] Status code to exit with.
2810 * RETURNS
2811 * Nothing.
2813 #ifdef __i386__
2814 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2815 "pushl %ebp\n\t"
2816 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2817 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2818 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2819 "pushl 8(%ebp)\n\t"
2820 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2821 "leave\n\t"
2822 "ret $4" )
2823 #else
2825 void WINAPI ExitProcess( DWORD status )
2827 RtlExitUserProcess( status );
2830 #endif
2832 /***********************************************************************
2833 * GetExitCodeProcess [KERNEL32.@]
2835 * Gets termination status of specified process.
2837 * PARAMS
2838 * hProcess [in] Handle to the process.
2839 * lpExitCode [out] Address to receive termination status.
2841 * RETURNS
2842 * Success: TRUE
2843 * Failure: FALSE
2845 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2847 NTSTATUS status;
2848 PROCESS_BASIC_INFORMATION pbi;
2850 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2851 sizeof(pbi), NULL);
2852 if (status == STATUS_SUCCESS)
2854 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2855 return TRUE;
2857 SetLastError( RtlNtStatusToDosError(status) );
2858 return FALSE;
2862 /***********************************************************************
2863 * SetErrorMode (KERNEL32.@)
2865 UINT WINAPI SetErrorMode( UINT mode )
2867 UINT old;
2869 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2870 &old, sizeof(old), NULL );
2871 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2872 &mode, sizeof(mode) );
2873 return old;
2876 /***********************************************************************
2877 * GetErrorMode (KERNEL32.@)
2879 UINT WINAPI GetErrorMode( void )
2881 UINT mode;
2883 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
2884 &mode, sizeof(mode), NULL );
2885 return mode;
2888 /**********************************************************************
2889 * TlsAlloc [KERNEL32.@]
2891 * Allocates a thread local storage index.
2893 * RETURNS
2894 * Success: TLS index.
2895 * Failure: 0xFFFFFFFF
2897 DWORD WINAPI TlsAlloc( void )
2899 DWORD index;
2900 PEB * const peb = NtCurrentTeb()->Peb;
2902 RtlAcquirePebLock();
2903 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
2904 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2905 else
2907 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2908 if (index != ~0U)
2910 if (!NtCurrentTeb()->TlsExpansionSlots &&
2911 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2912 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2914 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2915 index = ~0U;
2916 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2918 else
2920 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2921 index += TLS_MINIMUM_AVAILABLE;
2924 else SetLastError( ERROR_NO_MORE_ITEMS );
2926 RtlReleasePebLock();
2927 return index;
2931 /**********************************************************************
2932 * TlsFree [KERNEL32.@]
2934 * Releases a thread local storage index, making it available for reuse.
2936 * PARAMS
2937 * index [in] TLS index to free.
2939 * RETURNS
2940 * Success: TRUE
2941 * Failure: FALSE
2943 BOOL WINAPI TlsFree( DWORD index )
2945 BOOL ret;
2947 RtlAcquirePebLock();
2948 if (index >= TLS_MINIMUM_AVAILABLE)
2950 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2951 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2953 else
2955 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2956 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2958 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2959 else SetLastError( ERROR_INVALID_PARAMETER );
2960 RtlReleasePebLock();
2961 return ret;
2965 /**********************************************************************
2966 * TlsGetValue [KERNEL32.@]
2968 * Gets value in a thread's TLS slot.
2970 * PARAMS
2971 * index [in] TLS index to retrieve value for.
2973 * RETURNS
2974 * Success: Value stored in calling thread's TLS slot for index.
2975 * Failure: 0 and GetLastError() returns NO_ERROR.
2977 LPVOID WINAPI TlsGetValue( DWORD index )
2979 LPVOID ret;
2981 if (index < TLS_MINIMUM_AVAILABLE)
2983 ret = NtCurrentTeb()->TlsSlots[index];
2985 else
2987 index -= TLS_MINIMUM_AVAILABLE;
2988 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2990 SetLastError( ERROR_INVALID_PARAMETER );
2991 return NULL;
2993 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2994 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2996 SetLastError( ERROR_SUCCESS );
2997 return ret;
3001 /**********************************************************************
3002 * TlsSetValue [KERNEL32.@]
3004 * Stores a value in the thread's TLS slot.
3006 * PARAMS
3007 * index [in] TLS index to set value for.
3008 * value [in] Value to be stored.
3010 * RETURNS
3011 * Success: TRUE
3012 * Failure: FALSE
3014 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
3016 if (index < TLS_MINIMUM_AVAILABLE)
3018 NtCurrentTeb()->TlsSlots[index] = value;
3020 else
3022 index -= TLS_MINIMUM_AVAILABLE;
3023 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
3025 SetLastError( ERROR_INVALID_PARAMETER );
3026 return FALSE;
3028 if (!NtCurrentTeb()->TlsExpansionSlots &&
3029 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
3030 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
3032 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3033 return FALSE;
3035 NtCurrentTeb()->TlsExpansionSlots[index] = value;
3037 return TRUE;
3041 /***********************************************************************
3042 * GetProcessFlags (KERNEL32.@)
3044 DWORD WINAPI GetProcessFlags( DWORD processid )
3046 IMAGE_NT_HEADERS *nt;
3047 DWORD flags = 0;
3049 if (processid && processid != GetCurrentProcessId()) return 0;
3051 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3053 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
3054 flags |= PDB32_CONSOLE_PROC;
3056 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
3057 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
3058 return flags;
3062 /*********************************************************************
3063 * OpenProcess (KERNEL32.@)
3065 * Opens a handle to a process.
3067 * PARAMS
3068 * access [I] Desired access rights assigned to the returned handle.
3069 * inherit [I] Determines whether or not child processes will inherit the handle.
3070 * id [I] Process identifier of the process to get a handle to.
3072 * RETURNS
3073 * Success: Valid handle to the specified process.
3074 * Failure: NULL, check GetLastError().
3076 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
3078 NTSTATUS status;
3079 HANDLE handle;
3080 OBJECT_ATTRIBUTES attr;
3081 CLIENT_ID cid;
3083 cid.UniqueProcess = ULongToHandle(id);
3084 cid.UniqueThread = 0; /* FIXME ? */
3086 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3087 attr.RootDirectory = NULL;
3088 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3089 attr.SecurityDescriptor = NULL;
3090 attr.SecurityQualityOfService = NULL;
3091 attr.ObjectName = NULL;
3093 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3095 status = NtOpenProcess(&handle, access, &attr, &cid);
3096 if (status != STATUS_SUCCESS)
3098 SetLastError( RtlNtStatusToDosError(status) );
3099 return NULL;
3101 return handle;
3105 /*********************************************************************
3106 * GetProcessId (KERNEL32.@)
3108 * Gets the a unique identifier of a process.
3110 * PARAMS
3111 * hProcess [I] Handle to the process.
3113 * RETURNS
3114 * Success: TRUE.
3115 * Failure: FALSE, check GetLastError().
3117 * NOTES
3119 * The identifier is unique only on the machine and only until the process
3120 * exits (including system shutdown).
3122 DWORD WINAPI GetProcessId( HANDLE hProcess )
3124 NTSTATUS status;
3125 PROCESS_BASIC_INFORMATION pbi;
3127 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3128 sizeof(pbi), NULL);
3129 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3130 SetLastError( RtlNtStatusToDosError(status) );
3131 return 0;
3135 /*********************************************************************
3136 * CloseHandle (KERNEL32.@)
3138 * Closes a handle.
3140 * PARAMS
3141 * handle [I] Handle to close.
3143 * RETURNS
3144 * Success: TRUE.
3145 * Failure: FALSE, check GetLastError().
3147 BOOL WINAPI CloseHandle( HANDLE handle )
3149 NTSTATUS status;
3151 /* stdio handles need special treatment */
3152 if (handle == (HANDLE)STD_INPUT_HANDLE)
3153 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3154 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3155 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3156 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3157 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3159 if (is_console_handle(handle))
3160 return CloseConsoleHandle(handle);
3162 status = NtClose( handle );
3163 if (status) SetLastError( RtlNtStatusToDosError(status) );
3164 return !status;
3168 /*********************************************************************
3169 * GetHandleInformation (KERNEL32.@)
3171 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3173 OBJECT_DATA_INFORMATION info;
3174 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3176 if (status) SetLastError( RtlNtStatusToDosError(status) );
3177 else if (flags)
3179 *flags = 0;
3180 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3181 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3183 return !status;
3187 /*********************************************************************
3188 * SetHandleInformation (KERNEL32.@)
3190 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3192 OBJECT_DATA_INFORMATION info;
3193 NTSTATUS status;
3195 /* if not setting both fields, retrieve current value first */
3196 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3197 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3199 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3201 SetLastError( RtlNtStatusToDosError(status) );
3202 return FALSE;
3205 if (mask & HANDLE_FLAG_INHERIT)
3206 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3207 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3208 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3210 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3211 if (status) SetLastError( RtlNtStatusToDosError(status) );
3212 return !status;
3216 /*********************************************************************
3217 * DuplicateHandle (KERNEL32.@)
3219 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3220 HANDLE dest_process, HANDLE *dest,
3221 DWORD access, BOOL inherit, DWORD options )
3223 NTSTATUS status;
3225 if (is_console_handle(source))
3227 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3228 if (source_process != dest_process ||
3229 source_process != GetCurrentProcess())
3231 SetLastError(ERROR_INVALID_PARAMETER);
3232 return FALSE;
3234 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3235 return (*dest != INVALID_HANDLE_VALUE);
3237 status = NtDuplicateObject( source_process, source, dest_process, dest,
3238 access, inherit ? OBJ_INHERIT : 0, options );
3239 if (status) SetLastError( RtlNtStatusToDosError(status) );
3240 return !status;
3244 /***********************************************************************
3245 * ConvertToGlobalHandle (KERNEL32.@)
3247 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3249 HANDLE ret = INVALID_HANDLE_VALUE;
3250 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3251 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3252 return ret;
3256 /***********************************************************************
3257 * SetHandleContext (KERNEL32.@)
3259 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3261 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3262 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3263 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3264 return FALSE;
3268 /***********************************************************************
3269 * GetHandleContext (KERNEL32.@)
3271 DWORD WINAPI GetHandleContext(HANDLE hnd)
3273 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3274 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3275 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3276 return 0;
3280 /***********************************************************************
3281 * CreateSocketHandle (KERNEL32.@)
3283 HANDLE WINAPI CreateSocketHandle(void)
3285 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3286 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3287 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3288 return INVALID_HANDLE_VALUE;
3292 /***********************************************************************
3293 * SetPriorityClass (KERNEL32.@)
3295 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3297 NTSTATUS status;
3298 PROCESS_PRIORITY_CLASS ppc;
3300 ppc.Foreground = FALSE;
3301 switch (priorityclass)
3303 case IDLE_PRIORITY_CLASS:
3304 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3305 case BELOW_NORMAL_PRIORITY_CLASS:
3306 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3307 case NORMAL_PRIORITY_CLASS:
3308 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3309 case ABOVE_NORMAL_PRIORITY_CLASS:
3310 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3311 case HIGH_PRIORITY_CLASS:
3312 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3313 case REALTIME_PRIORITY_CLASS:
3314 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3315 default:
3316 SetLastError(ERROR_INVALID_PARAMETER);
3317 return FALSE;
3320 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3321 &ppc, sizeof(ppc));
3323 if (status != STATUS_SUCCESS)
3325 SetLastError( RtlNtStatusToDosError(status) );
3326 return FALSE;
3328 return TRUE;
3332 /***********************************************************************
3333 * GetPriorityClass (KERNEL32.@)
3335 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3337 NTSTATUS status;
3338 PROCESS_BASIC_INFORMATION pbi;
3340 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3341 sizeof(pbi), NULL);
3342 if (status != STATUS_SUCCESS)
3344 SetLastError( RtlNtStatusToDosError(status) );
3345 return 0;
3347 switch (pbi.BasePriority)
3349 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3350 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3351 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3352 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3353 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3354 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3356 SetLastError( ERROR_INVALID_PARAMETER );
3357 return 0;
3361 /***********************************************************************
3362 * SetProcessAffinityMask (KERNEL32.@)
3364 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3366 NTSTATUS status;
3368 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3369 &affmask, sizeof(DWORD_PTR));
3370 if (status)
3372 SetLastError( RtlNtStatusToDosError(status) );
3373 return FALSE;
3375 return TRUE;
3379 /**********************************************************************
3380 * GetProcessAffinityMask (KERNEL32.@)
3382 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3384 NTSTATUS status = STATUS_SUCCESS;
3386 if (process_mask)
3388 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3389 process_mask, sizeof(*process_mask), NULL )))
3390 SetLastError( RtlNtStatusToDosError(status) );
3392 if (system_mask && status == STATUS_SUCCESS)
3394 SYSTEM_BASIC_INFORMATION info;
3396 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3397 SetLastError( RtlNtStatusToDosError(status) );
3398 else
3399 *system_mask = info.ActiveProcessorsAffinityMask;
3401 return !status;
3405 /***********************************************************************
3406 * SetProcessAffinityUpdateMode (KERNEL32.@)
3408 BOOL WINAPI SetProcessAffinityUpdateMode( HANDLE process, DWORD flags )
3410 FIXME("(%p,0x%08x): stub\n", process, flags);
3411 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3412 return FALSE;
3416 /***********************************************************************
3417 * GetProcessVersion (KERNEL32.@)
3419 DWORD WINAPI GetProcessVersion( DWORD pid )
3421 HANDLE process;
3422 NTSTATUS status;
3423 PROCESS_BASIC_INFORMATION pbi;
3424 SIZE_T count;
3425 PEB peb;
3426 IMAGE_DOS_HEADER dos;
3427 IMAGE_NT_HEADERS nt;
3428 DWORD ver = 0;
3430 if (!pid || pid == GetCurrentProcessId())
3432 IMAGE_NT_HEADERS *pnt;
3434 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3435 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3436 pnt->OptionalHeader.MinorSubsystemVersion);
3437 return 0;
3440 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3441 if (!process) return 0;
3443 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3444 if (status) goto err;
3446 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3447 if (status || count != sizeof(peb)) goto err;
3449 memset(&dos, 0, sizeof(dos));
3450 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3451 if (status || count != sizeof(dos)) goto err;
3452 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3454 memset(&nt, 0, sizeof(nt));
3455 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3456 if (status || count != sizeof(nt)) goto err;
3457 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3459 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3461 err:
3462 CloseHandle(process);
3464 if (status != STATUS_SUCCESS)
3465 SetLastError(RtlNtStatusToDosError(status));
3467 return ver;
3471 /***********************************************************************
3472 * SetProcessWorkingSetSizeEx [KERNEL32.@]
3473 * Sets the min/max working set sizes for a specified process.
3475 * PARAMS
3476 * process [I] Handle to the process of interest
3477 * minset [I] Specifies minimum working set size
3478 * maxset [I] Specifies maximum working set size
3479 * flags [I] Flags to enforce working set sizes
3481 * RETURNS
3482 * Success: TRUE
3483 * Failure: FALSE
3485 BOOL WINAPI SetProcessWorkingSetSizeEx(HANDLE process, SIZE_T minset, SIZE_T maxset, DWORD flags)
3487 WARN("(%p,%ld,%ld,%x): stub - harmless\n", process, minset, maxset, flags);
3488 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3489 /* Trim the working set to zero */
3490 /* Swap the process out of physical RAM */
3492 return TRUE;
3495 /***********************************************************************
3496 * SetProcessWorkingSetSize [KERNEL32.@]
3497 * Sets the min/max working set sizes for a specified process.
3499 * PARAMS
3500 * process [I] Handle to the process of interest
3501 * minset [I] Specifies minimum working set size
3502 * maxset [I] Specifies maximum working set size
3504 * RETURNS
3505 * Success: TRUE
3506 * Failure: FALSE
3508 BOOL WINAPI SetProcessWorkingSetSize(HANDLE process, SIZE_T minset, SIZE_T maxset)
3510 return SetProcessWorkingSetSizeEx(process, minset, maxset, 0);
3513 /***********************************************************************
3514 * K32EmptyWorkingSet (KERNEL32.@)
3516 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3518 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3522 /***********************************************************************
3523 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3525 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3526 SIZE_T *maxset, DWORD *flags)
3528 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3529 /* 32 MB working set size */
3530 if (minset) *minset = 32*1024*1024;
3531 if (maxset) *maxset = 32*1024*1024;
3532 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3533 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3534 return TRUE;
3538 /***********************************************************************
3539 * GetProcessWorkingSetSize (KERNEL32.@)
3541 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3543 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3547 /***********************************************************************
3548 * SetProcessShutdownParameters (KERNEL32.@)
3550 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3552 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3553 shutdown_flags = flags;
3554 shutdown_priority = level;
3555 return TRUE;
3559 /***********************************************************************
3560 * GetProcessShutdownParameters (KERNEL32.@)
3563 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3565 *lpdwLevel = shutdown_priority;
3566 *lpdwFlags = shutdown_flags;
3567 return TRUE;
3571 /***********************************************************************
3572 * GetProcessPriorityBoost (KERNEL32.@)
3574 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3576 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3578 /* Report that no boost is present.. */
3579 *pDisablePriorityBoost = FALSE;
3581 return TRUE;
3584 /***********************************************************************
3585 * SetProcessPriorityBoost (KERNEL32.@)
3587 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3589 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3590 /* Say we can do it. I doubt the program will notice that we don't. */
3591 return TRUE;
3595 /***********************************************************************
3596 * ReadProcessMemory (KERNEL32.@)
3598 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3599 SIZE_T *bytes_read )
3601 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3602 if (status) SetLastError( RtlNtStatusToDosError(status) );
3603 return !status;
3607 /***********************************************************************
3608 * WriteProcessMemory (KERNEL32.@)
3610 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3611 SIZE_T *bytes_written )
3613 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3614 if (status) SetLastError( RtlNtStatusToDosError(status) );
3615 return !status;
3619 /****************************************************************************
3620 * FlushInstructionCache (KERNEL32.@)
3622 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3624 NTSTATUS status;
3625 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3626 if (status) SetLastError( RtlNtStatusToDosError(status) );
3627 return !status;
3631 /******************************************************************
3632 * GetProcessIoCounters (KERNEL32.@)
3634 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3636 NTSTATUS status;
3638 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3639 ioc, sizeof(*ioc), NULL);
3640 if (status) SetLastError( RtlNtStatusToDosError(status) );
3641 return !status;
3644 /******************************************************************
3645 * GetProcessHandleCount (KERNEL32.@)
3647 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3649 NTSTATUS status;
3651 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3652 cnt, sizeof(*cnt), NULL);
3653 if (status) SetLastError( RtlNtStatusToDosError(status) );
3654 return !status;
3657 /******************************************************************
3658 * QueryFullProcessImageNameA (KERNEL32.@)
3660 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3662 BOOL retval;
3663 DWORD pdwSizeW = *pdwSize;
3664 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3666 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3668 if(retval)
3669 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3670 lpExeName, *pdwSize, NULL, NULL));
3671 if(retval)
3672 *pdwSize = strlen(lpExeName);
3674 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3675 return retval;
3678 /******************************************************************
3679 * QueryFullProcessImageNameW (KERNEL32.@)
3681 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3683 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3684 UNICODE_STRING *dynamic_buffer = NULL;
3685 UNICODE_STRING *result = NULL;
3686 NTSTATUS status;
3687 DWORD needed;
3689 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3690 * is a DOS path and we depend on this. */
3691 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3692 sizeof(buffer) - sizeof(WCHAR), &needed);
3693 if (status == STATUS_INFO_LENGTH_MISMATCH)
3695 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3696 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3697 result = dynamic_buffer;
3699 else
3700 result = (PUNICODE_STRING)buffer;
3702 if (status) goto cleanup;
3704 if (dwFlags & PROCESS_NAME_NATIVE)
3706 WCHAR drive[3];
3707 WCHAR device[1024];
3708 DWORD ntlen, devlen;
3710 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3712 /* We cannot convert it to an NT device path so fail */
3713 status = STATUS_NO_SUCH_DEVICE;
3714 goto cleanup;
3717 /* Find this drive's NT device path */
3718 drive[0] = result->Buffer[0];
3719 drive[1] = ':';
3720 drive[2] = 0;
3721 if (!QueryDosDeviceW(drive, device, ARRAY_SIZE(device)))
3723 status = STATUS_NO_SUCH_DEVICE;
3724 goto cleanup;
3727 devlen = lstrlenW(device);
3728 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3729 if (ntlen + 1 > *pdwSize)
3731 status = STATUS_BUFFER_TOO_SMALL;
3732 goto cleanup;
3734 *pdwSize = ntlen;
3736 memcpy(lpExeName, device, devlen * sizeof(*device));
3737 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3738 lpExeName[*pdwSize] = 0;
3739 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3741 else
3743 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3745 status = STATUS_BUFFER_TOO_SMALL;
3746 goto cleanup;
3749 *pdwSize = result->Length/sizeof(WCHAR);
3750 memcpy( lpExeName, result->Buffer, result->Length );
3751 lpExeName[*pdwSize] = 0;
3754 cleanup:
3755 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3756 if (status) SetLastError( RtlNtStatusToDosError(status) );
3757 return !status;
3760 /***********************************************************************
3761 * K32GetProcessImageFileNameA (KERNEL32.@)
3763 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
3765 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3768 /***********************************************************************
3769 * K32GetProcessImageFileNameW (KERNEL32.@)
3771 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
3773 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
3776 /***********************************************************************
3777 * K32EnumProcesses (KERNEL32.@)
3779 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
3781 SYSTEM_PROCESS_INFORMATION *spi;
3782 ULONG size = 0x4000;
3783 void *buf = NULL;
3784 NTSTATUS status;
3786 do {
3787 size *= 2;
3788 HeapFree(GetProcessHeap(), 0, buf);
3789 buf = HeapAlloc(GetProcessHeap(), 0, size);
3790 if (!buf)
3791 return FALSE;
3793 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
3794 } while(status == STATUS_INFO_LENGTH_MISMATCH);
3796 if (status != STATUS_SUCCESS)
3798 HeapFree(GetProcessHeap(), 0, buf);
3799 SetLastError(RtlNtStatusToDosError(status));
3800 return FALSE;
3803 spi = buf;
3805 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
3807 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
3808 *lpcbUsed += sizeof(DWORD);
3810 if (spi->NextEntryOffset == 0)
3811 break;
3813 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
3816 HeapFree(GetProcessHeap(), 0, buf);
3817 return TRUE;
3820 /***********************************************************************
3821 * K32QueryWorkingSet (KERNEL32.@)
3823 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
3825 NTSTATUS status;
3827 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3829 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3831 if (status)
3833 SetLastError( RtlNtStatusToDosError( status ) );
3834 return FALSE;
3836 return TRUE;
3839 /***********************************************************************
3840 * K32QueryWorkingSetEx (KERNEL32.@)
3842 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
3844 NTSTATUS status;
3846 TRACE( "(%p, %p, %d)\n", process, buffer, size );
3848 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
3850 if (status)
3852 SetLastError( RtlNtStatusToDosError( status ) );
3853 return FALSE;
3855 return TRUE;
3858 /***********************************************************************
3859 * K32GetProcessMemoryInfo (KERNEL32.@)
3861 * Retrieve memory usage information for a given process
3864 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
3865 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
3867 NTSTATUS status;
3868 VM_COUNTERS vmc;
3870 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
3872 SetLastError(ERROR_INSUFFICIENT_BUFFER);
3873 return FALSE;
3876 status = NtQueryInformationProcess(process, ProcessVmCounters,
3877 &vmc, sizeof(vmc), NULL);
3879 if (status)
3881 SetLastError(RtlNtStatusToDosError(status));
3882 return FALSE;
3885 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
3886 pmc->PageFaultCount = vmc.PageFaultCount;
3887 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
3888 pmc->WorkingSetSize = vmc.WorkingSetSize;
3889 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
3890 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
3891 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
3892 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
3893 pmc->PagefileUsage = vmc.PagefileUsage;
3894 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
3896 return TRUE;
3899 /***********************************************************************
3900 * ProcessIdToSessionId (KERNEL32.@)
3901 * This function is available on Terminal Server 4SP4 and Windows 2000
3903 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3905 if (procid != GetCurrentProcessId())
3906 FIXME("Unsupported for other processes.\n");
3908 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
3909 return TRUE;
3913 /***********************************************************************
3914 * RegisterServiceProcess (KERNEL32.@)
3916 * A service process calls this function to ensure that it continues to run
3917 * even after a user logged off.
3919 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3921 /* I don't think that Wine needs to do anything in this function */
3922 return 1; /* success */
3926 /**********************************************************************
3927 * IsWow64Process (KERNEL32.@)
3929 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3931 ULONG_PTR pbi;
3932 NTSTATUS status;
3934 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3936 if (status != STATUS_SUCCESS)
3938 SetLastError( RtlNtStatusToDosError( status ) );
3939 return FALSE;
3941 *Wow64Process = (pbi != 0);
3942 return TRUE;
3946 /***********************************************************************
3947 * GetCurrentProcess (KERNEL32.@)
3949 * Get a handle to the current process.
3951 * PARAMS
3952 * None.
3954 * RETURNS
3955 * A handle representing the current process.
3957 #undef GetCurrentProcess
3958 HANDLE WINAPI GetCurrentProcess(void)
3960 return (HANDLE)~(ULONG_PTR)0;
3963 /***********************************************************************
3964 * GetLogicalProcessorInformation (KERNEL32.@)
3966 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
3968 NTSTATUS status;
3970 TRACE("(%p,%p)\n", buffer, pBufLen);
3972 if(!pBufLen)
3974 SetLastError(ERROR_INVALID_PARAMETER);
3975 return FALSE;
3978 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
3980 if (status == STATUS_INFO_LENGTH_MISMATCH)
3982 SetLastError( ERROR_INSUFFICIENT_BUFFER );
3983 return FALSE;
3985 if (status != STATUS_SUCCESS)
3987 SetLastError( RtlNtStatusToDosError( status ) );
3988 return FALSE;
3990 return TRUE;
3993 /***********************************************************************
3994 * GetLogicalProcessorInformationEx (KERNEL32.@)
3996 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
3998 NTSTATUS status;
4000 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
4002 if (!len)
4004 SetLastError( ERROR_INVALID_PARAMETER );
4005 return FALSE;
4008 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
4009 buffer, *len, len );
4010 if (status == STATUS_INFO_LENGTH_MISMATCH)
4012 SetLastError( ERROR_INSUFFICIENT_BUFFER );
4013 return FALSE;
4015 if (status != STATUS_SUCCESS)
4017 SetLastError( RtlNtStatusToDosError( status ) );
4018 return FALSE;
4020 return TRUE;
4023 /***********************************************************************
4024 * CmdBatNotification (KERNEL32.@)
4026 * Notifies the system that a batch file has started or finished.
4028 * PARAMS
4029 * bBatchRunning [I] TRUE if a batch file has started or
4030 * FALSE if a batch file has finished executing.
4032 * RETURNS
4033 * Unknown.
4035 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
4037 FIXME("%d\n", bBatchRunning);
4038 return FALSE;
4041 /***********************************************************************
4042 * RegisterApplicationRestart (KERNEL32.@)
4044 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
4046 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
4048 return S_OK;
4051 /**********************************************************************
4052 * WTSGetActiveConsoleSessionId (KERNEL32.@)
4054 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
4056 static int once;
4057 if (!once++) FIXME("stub\n");
4058 /* Return current session id. */
4059 return NtCurrentTeb()->Peb->SessionId;
4062 /**********************************************************************
4063 * GetSystemDEPPolicy (KERNEL32.@)
4065 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
4067 FIXME("stub\n");
4068 return OptIn;
4071 /**********************************************************************
4072 * SetProcessDEPPolicy (KERNEL32.@)
4074 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
4076 FIXME("(%d): stub\n", newDEP);
4077 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4078 return FALSE;
4081 /**********************************************************************
4082 * ApplicationRecoveryFinished (KERNEL32.@)
4084 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
4086 FIXME(": stub\n");
4087 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4090 /**********************************************************************
4091 * ApplicationRecoveryInProgress (KERNEL32.@)
4093 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
4095 FIXME(":%p stub\n", canceled);
4096 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4097 return E_FAIL;
4100 /**********************************************************************
4101 * RegisterApplicationRecoveryCallback (KERNEL32.@)
4103 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
4105 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
4106 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4107 return E_FAIL;
4110 /***********************************************************************
4111 * GetApplicationRestartSettings (KERNEL32.@)
4113 HRESULT WINAPI GetApplicationRestartSettings(HANDLE process, WCHAR *cmdline, DWORD *size, DWORD *flags)
4115 FIXME("%p, %p, %p, %p)\n", process, cmdline, size, flags);
4116 return E_NOTIMPL;
4119 /**********************************************************************
4120 * GetNumaHighestNodeNumber (KERNEL32.@)
4122 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4124 *highestnode = 0;
4125 FIXME("(%p): semi-stub\n", highestnode);
4126 return TRUE;
4129 /**********************************************************************
4130 * GetNumaNodeProcessorMask (KERNEL32.@)
4132 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4134 FIXME("(%c %p): stub\n", node, mask);
4135 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4136 return FALSE;
4139 /**********************************************************************
4140 * GetNumaNodeProcessorMaskEx (KERNEL32.@)
4142 BOOL WINAPI GetNumaNodeProcessorMaskEx(USHORT node, PGROUP_AFFINITY mask)
4144 FIXME("(%hu %p): stub\n", node, mask);
4145 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4146 return FALSE;
4149 /**********************************************************************
4150 * GetNumaAvailableMemoryNode (KERNEL32.@)
4152 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4154 FIXME("(%c %p): stub\n", node, available_bytes);
4155 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4156 return FALSE;
4159 /***********************************************************************
4160 * GetNumaProcessorNode (KERNEL32.@)
4162 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4164 SYSTEM_INFO si;
4166 TRACE("(%d, %p)\n", processor, node);
4168 GetSystemInfo( &si );
4169 if (processor < si.dwNumberOfProcessors)
4171 *node = 0;
4172 return TRUE;
4175 *node = 0xFF;
4176 SetLastError(ERROR_INVALID_PARAMETER);
4177 return FALSE;
4180 /**********************************************************************
4181 * GetProcessDEPPolicy (KERNEL32.@)
4183 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4185 NTSTATUS status;
4186 ULONG dep_flags;
4188 TRACE("(%p %p %p)\n", process, flags, permanent);
4190 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4191 &dep_flags, sizeof(dep_flags), NULL );
4192 if (!status)
4195 if (flags)
4197 *flags = 0;
4198 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4199 *flags |= PROCESS_DEP_ENABLE;
4200 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4201 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4204 if (permanent)
4205 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4208 if (status) SetLastError( RtlNtStatusToDosError(status) );
4209 return !status;
4212 /**********************************************************************
4213 * FlushProcessWriteBuffers (KERNEL32.@)
4215 VOID WINAPI FlushProcessWriteBuffers(void)
4217 static int once = 0;
4219 if (!once++)
4220 FIXME(": stub\n");
4223 /***********************************************************************
4224 * UnregisterApplicationRestart (KERNEL32.@)
4226 HRESULT WINAPI UnregisterApplicationRestart(void)
4228 FIXME(": stub\n");
4229 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4230 return S_OK;
4233 struct proc_thread_attr
4235 DWORD_PTR attr;
4236 SIZE_T size;
4237 void *value;
4240 struct _PROC_THREAD_ATTRIBUTE_LIST
4242 DWORD mask; /* bitmask of items in list */
4243 DWORD size; /* max number of items in list */
4244 DWORD count; /* number of items in list */
4245 DWORD pad;
4246 DWORD_PTR unk;
4247 struct proc_thread_attr attrs[1];
4250 /***********************************************************************
4251 * InitializeProcThreadAttributeList (KERNEL32.@)
4253 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4254 DWORD count, DWORD flags, SIZE_T *size)
4256 SIZE_T needed;
4257 BOOL ret = FALSE;
4259 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4261 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4262 if (list && *size >= needed)
4264 list->mask = 0;
4265 list->size = count;
4266 list->count = 0;
4267 list->unk = 0;
4268 ret = TRUE;
4270 else
4271 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4273 *size = needed;
4274 return ret;
4277 /***********************************************************************
4278 * UpdateProcThreadAttribute (KERNEL32.@)
4280 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4281 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4282 void *prev_ret, SIZE_T *size_ret)
4284 DWORD mask;
4285 struct proc_thread_attr *entry;
4287 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4289 if (list->count >= list->size)
4291 SetLastError(ERROR_GEN_FAILURE);
4292 return FALSE;
4295 switch (attr)
4297 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4298 if (size != sizeof(HANDLE))
4300 SetLastError(ERROR_BAD_LENGTH);
4301 return FALSE;
4303 break;
4305 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4306 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4308 SetLastError(ERROR_BAD_LENGTH);
4309 return FALSE;
4311 break;
4313 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4314 if (size != sizeof(PROCESSOR_NUMBER))
4316 SetLastError(ERROR_BAD_LENGTH);
4317 return FALSE;
4319 break;
4321 case PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY:
4322 if (size != sizeof(DWORD) && size != sizeof(DWORD64))
4324 SetLastError(ERROR_BAD_LENGTH);
4325 return FALSE;
4327 break;
4329 case PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY:
4330 if (size != sizeof(DWORD) && size != sizeof(DWORD64) && size != sizeof(DWORD64) * 2)
4332 SetLastError(ERROR_BAD_LENGTH);
4333 return FALSE;
4335 break;
4337 default:
4338 SetLastError(ERROR_NOT_SUPPORTED);
4339 FIXME("Unhandled attribute number %lu\n", attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4340 return FALSE;
4343 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4345 if (list->mask & mask)
4347 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4348 return FALSE;
4351 list->mask |= mask;
4353 entry = list->attrs + list->count;
4354 entry->attr = attr;
4355 entry->size = size;
4356 entry->value = value;
4357 list->count++;
4359 return TRUE;
4362 /***********************************************************************
4363 * CreateUmsCompletionList (KERNEL32.@)
4365 BOOL WINAPI CreateUmsCompletionList(PUMS_COMPLETION_LIST *list)
4367 FIXME( "%p: stub\n", list );
4368 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4369 return FALSE;
4372 /***********************************************************************
4373 * CreateUmsThreadContext (KERNEL32.@)
4375 BOOL WINAPI CreateUmsThreadContext(PUMS_CONTEXT *ctx)
4377 FIXME( "%p: stub\n", ctx );
4378 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4379 return FALSE;
4382 /***********************************************************************
4383 * DeleteProcThreadAttributeList (KERNEL32.@)
4385 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4387 return;
4390 /***********************************************************************
4391 * DeleteUmsCompletionList (KERNEL32.@)
4393 BOOL WINAPI DeleteUmsCompletionList(PUMS_COMPLETION_LIST list)
4395 FIXME( "%p: stub\n", list );
4396 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4397 return FALSE;
4400 /***********************************************************************
4401 * DeleteUmsThreadContext (KERNEL32.@)
4403 BOOL WINAPI DeleteUmsThreadContext(PUMS_CONTEXT ctx)
4405 FIXME( "%p: stub\n", ctx );
4406 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4407 return FALSE;
4410 /***********************************************************************
4411 * DequeueUmsCompletionListItems (KERNEL32.@)
4413 BOOL WINAPI DequeueUmsCompletionListItems(void *list, DWORD timeout, PUMS_CONTEXT *ctx)
4415 FIXME( "%p,%08x,%p: stub\n", list, timeout, ctx );
4416 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4417 return FALSE;
4420 /***********************************************************************
4421 * EnterUmsSchedulingMode (KERNEL32.@)
4423 BOOL WINAPI EnterUmsSchedulingMode(UMS_SCHEDULER_STARTUP_INFO *info)
4425 FIXME( "%p: stub\n", info );
4426 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4427 return FALSE;
4430 /***********************************************************************
4431 * ExecuteUmsThread (KERNEL32.@)
4433 BOOL WINAPI ExecuteUmsThread(PUMS_CONTEXT ctx)
4435 FIXME( "%p: stub\n", ctx );
4436 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4437 return FALSE;
4440 /***********************************************************************
4441 * GetCurrentUmsThread (KERNEL32.@)
4443 PUMS_CONTEXT WINAPI GetCurrentUmsThread(void)
4445 FIXME( "stub\n" );
4446 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4447 return FALSE;
4450 /***********************************************************************
4451 * GetNextUmsListItem (KERNEL32.@)
4453 PUMS_CONTEXT WINAPI GetNextUmsListItem(PUMS_CONTEXT ctx)
4455 FIXME( "%p: stub\n", ctx );
4456 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4457 return NULL;
4460 /***********************************************************************
4461 * GetUmsCompletionListEvent (KERNEL32.@)
4463 BOOL WINAPI GetUmsCompletionListEvent(PUMS_COMPLETION_LIST list, HANDLE *event)
4465 FIXME( "%p,%p: stub\n", list, event );
4466 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4467 return FALSE;
4470 /***********************************************************************
4471 * QueryUmsThreadInformation (KERNEL32.@)
4473 BOOL WINAPI QueryUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4474 void *buf, ULONG length, ULONG *ret_length)
4476 FIXME( "%p,%08x,%p,%08x,%p: stub\n", ctx, class, buf, length, ret_length );
4477 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4478 return FALSE;
4481 /***********************************************************************
4482 * SetUmsThreadInformation (KERNEL32.@)
4484 BOOL WINAPI SetUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4485 void *buf, ULONG length)
4487 FIXME( "%p,%08x,%p,%08x: stub\n", ctx, class, buf, length );
4488 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4489 return FALSE;
4492 /***********************************************************************
4493 * UmsThreadYield (KERNEL32.@)
4495 BOOL WINAPI UmsThreadYield(void *param)
4497 FIXME( "%p: stub\n", param );
4498 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4499 return FALSE;
4502 /**********************************************************************
4503 * BaseFlushAppcompatCache (KERNEL32.@)
4505 BOOL WINAPI BaseFlushAppcompatCache(void)
4507 FIXME(": stub\n");
4508 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4509 return FALSE;
4512 /**********************************************************************
4513 * SetProcessMitigationPolicy (KERNEL32.@)
4515 BOOL WINAPI SetProcessMitigationPolicy(PROCESS_MITIGATION_POLICY policy, void *buffer, SIZE_T length)
4517 FIXME("(%d, %p, %lu): stub\n", policy, buffer, length);
4519 return TRUE;