winemenubuilder: Fix encoder method argument.
[wine.git] / dlls / kernel32 / process.c
blob53b1b2d933a674a52fb2fd086a43bfe7ec0d5145
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 WCHAR winevdm[] = {'C',':','\\','w','i','n','d','o','w','s',
111 '\\','s','y','s','t','e','m','3','2',
112 '\\','w','i','n','e','v','d','m','.','e','x','e',0};
114 static const char * const cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
116 static void exec_process( LPCWSTR name );
118 extern void SHELL_LoadRegistry(void);
120 /* return values for get_binary_info */
121 enum binary_type
123 BINARY_UNKNOWN = 0,
124 BINARY_PE,
125 BINARY_WIN16,
126 BINARY_UNIX_EXE,
127 BINARY_UNIX_LIB
131 /***********************************************************************
132 * contains_path
134 static inline BOOL contains_path( LPCWSTR name )
136 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
140 /***********************************************************************
141 * is_special_env_var
143 * Check if an environment variable needs to be handled specially when
144 * passed through the Unix environment (i.e. prefixed with "WINE").
146 static inline BOOL is_special_env_var( const char *var )
148 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
149 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
150 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
151 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
152 !strncmp( var, "TMP=", sizeof("TMP=")-1 ) ||
153 !strncmp( var, "QT_", sizeof("QT_")-1 ) ||
154 !strncmp( var, "VK_", sizeof("VK_")-1 ));
158 /***********************************************************************
159 * is_path_prefix
161 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
163 unsigned int len = strlenW( prefix );
165 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
166 while (filename[len] == '\\') len++;
167 return len;
171 /***********************************************************************
172 * is_64bit_arch
174 static inline BOOL is_64bit_arch( cpu_type_t cpu )
176 return (cpu == CPU_x86_64 || cpu == CPU_ARM64);
180 /***********************************************************************
181 * get_pe_info
183 static NTSTATUS get_pe_info( HANDLE handle, pe_image_info_t *info )
185 NTSTATUS status;
186 HANDLE mapping;
188 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY,
189 NULL, NULL, PAGE_READONLY, SEC_IMAGE, handle );
190 if (status) return status;
192 SERVER_START_REQ( get_mapping_info )
194 req->handle = wine_server_obj_handle( mapping );
195 req->access = SECTION_QUERY;
196 wine_server_set_reply( req, info, sizeof(*info) );
197 status = wine_server_call( req );
199 SERVER_END_REQ;
200 CloseHandle( mapping );
201 return status;
205 /***********************************************************************
206 * get_binary_info
208 static enum binary_type get_binary_info( HANDLE hfile, pe_image_info_t *info )
210 union
212 struct
214 unsigned char magic[4];
215 unsigned char class;
216 unsigned char data;
217 unsigned char ignored1[10];
218 unsigned short type;
219 unsigned short machine;
220 unsigned char ignored2[8];
221 unsigned int phoff;
222 unsigned char ignored3[12];
223 unsigned short phnum;
224 } elf;
225 struct
227 unsigned char magic[4];
228 unsigned char class;
229 unsigned char data;
230 unsigned char ignored1[10];
231 unsigned short type;
232 unsigned short machine;
233 unsigned char ignored2[12];
234 unsigned __int64 phoff;
235 unsigned char ignored3[16];
236 unsigned short phnum;
237 } elf64;
238 struct
240 unsigned int magic;
241 unsigned int cputype;
242 unsigned int cpusubtype;
243 unsigned int filetype;
244 } macho;
245 IMAGE_DOS_HEADER mz;
246 } header;
248 DWORD len;
249 NTSTATUS status;
251 memset( info, 0, sizeof(*info) );
253 status = get_pe_info( hfile, info );
254 switch (status)
256 case STATUS_SUCCESS:
257 return BINARY_PE;
258 case STATUS_INVALID_IMAGE_WIN_32:
259 return BINARY_PE;
260 case STATUS_INVALID_IMAGE_WIN_64:
261 return BINARY_PE;
262 case STATUS_INVALID_IMAGE_WIN_16:
263 case STATUS_INVALID_IMAGE_NE_FORMAT:
264 case STATUS_INVALID_IMAGE_PROTECT:
265 return BINARY_WIN16;
268 /* Seek to the start of the file and read the header information. */
269 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return BINARY_UNKNOWN;
270 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
271 return BINARY_UNKNOWN;
273 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
275 #ifdef WORDS_BIGENDIAN
276 BOOL byteswap = (header.elf.data == 1);
277 #else
278 BOOL byteswap = (header.elf.data == 2);
279 #endif
280 if (byteswap)
282 header.elf.type = RtlUshortByteSwap( header.elf.type );
283 header.elf.machine = RtlUshortByteSwap( header.elf.machine );
285 switch(header.elf.machine)
287 case 3: info->cpu = CPU_x86; break;
288 case 20: info->cpu = CPU_POWERPC; break;
289 case 40: info->cpu = CPU_ARM; break;
290 case 62: info->cpu = CPU_x86_64; break;
291 case 183: info->cpu = CPU_ARM64; break;
293 switch(header.elf.type)
295 case 2:
296 return BINARY_UNIX_EXE;
297 case 3:
299 LARGE_INTEGER phoff;
300 unsigned short phnum;
301 unsigned int type;
302 if (header.elf.class == 2)
304 phoff.QuadPart = byteswap ? RtlUlonglongByteSwap( header.elf64.phoff ) : header.elf64.phoff;
305 phnum = byteswap ? RtlUshortByteSwap( header.elf64.phnum ) : header.elf64.phnum;
307 else
309 phoff.QuadPart = byteswap ? RtlUlongByteSwap( header.elf.phoff ) : header.elf.phoff;
310 phnum = byteswap ? RtlUshortByteSwap( header.elf.phnum ) : header.elf.phnum;
312 while (phnum--)
314 if (SetFilePointerEx( hfile, phoff, NULL, FILE_BEGIN ) == -1) return BINARY_UNKNOWN;
315 if (!ReadFile( hfile, &type, sizeof(type), &len, NULL ) || len < sizeof(type))
316 return BINARY_UNKNOWN;
317 if (byteswap) type = RtlUlongByteSwap( type );
318 if (type == 3) return BINARY_UNIX_EXE;
319 phoff.QuadPart += (header.elf.class == 2) ? 56 : 32;
321 return BINARY_UNIX_LIB;
325 /* Mach-o File with Endian set to Big Endian or Little Endian */
326 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe ||
327 header.macho.magic == 0xfeedfacf || header.macho.magic == 0xcffaedfe)
329 if (header.macho.magic == 0xcefaedfe || header.macho.magic == 0xcffaedfe)
331 header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
332 header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
334 switch(header.macho.cputype)
336 case 0x00000007: info->cpu = CPU_x86; break;
337 case 0x01000007: info->cpu = CPU_x86_64; break;
338 case 0x0000000c: info->cpu = CPU_ARM; break;
339 case 0x0100000c: info->cpu = CPU_ARM64; break;
340 case 0x00000012: info->cpu = CPU_POWERPC; break;
342 switch(header.macho.filetype)
344 case 2: return BINARY_UNIX_EXE;
345 case 8: return BINARY_UNIX_LIB;
347 switch(header.macho.filetype)
349 case 2: return BINARY_UNIX_EXE;
350 case 8: return BINARY_UNIX_LIB;
353 return BINARY_UNKNOWN;
357 /***************************************************************************
358 * get_builtin_path
360 * Get the path of a builtin module when the native file does not exist.
362 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
363 UINT size, BOOL *is_64bit )
365 WCHAR *file_part;
366 UINT len;
367 void *redir_disabled = 0;
369 *is_64bit = (sizeof(void*) > sizeof(int));
371 /* builtin names cannot be empty or contain spaces */
372 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
374 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
375 Wow64RevertWow64FsRedirection( redir_disabled );
377 if (contains_path( libname ))
379 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
380 filename, &file_part ) > size * sizeof(WCHAR))
381 return FALSE; /* too long */
383 if ((len = is_path_prefix( DIR_System, filename )))
385 if (is_wow64 && redir_disabled) *is_64bit = TRUE;
387 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
389 *is_64bit = FALSE;
391 else return FALSE;
393 if (filename + len != file_part) return FALSE;
395 else
397 len = strlenW( DIR_System );
398 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
399 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
400 file_part = filename + len;
401 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
402 strcpyW( file_part, libname );
403 if (is_wow64 && redir_disabled) *is_64bit = TRUE;
405 if (ext && !strchrW( file_part, '.' ))
407 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
408 return FALSE; /* too long */
409 strcatW( file_part, ext );
411 return TRUE;
415 /***********************************************************************
416 * open_exe_file
418 * Open a specific exe file, taking load order into account.
419 * Returns the file handle or 0 for a builtin exe.
421 static HANDLE open_exe_file( const WCHAR *name, BOOL *is_64bit )
423 HANDLE handle;
425 TRACE("looking for %s\n", debugstr_w(name) );
427 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
428 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
430 WCHAR buffer[MAX_PATH];
431 /* file doesn't exist, check for builtin */
432 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), is_64bit ))
433 handle = 0;
435 return handle;
439 /***********************************************************************
440 * find_exe_file
442 * Open an exe file, and return the full name and file handle.
443 * Returns FALSE if file could not be found.
445 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
447 TRACE("looking for %s\n", debugstr_w(name) );
449 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
450 /* no builtin found, try native without extension in case it is a Unix app */
451 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
453 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
454 *handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
455 NULL, OPEN_EXISTING, 0, 0 );
456 return (*handle != INVALID_HANDLE_VALUE);
460 /***********************************************************************
461 * build_initial_environment
463 * Build the Win32 environment from the Unix environment
465 static BOOL build_initial_environment(void)
467 SIZE_T size = 1;
468 char **e;
469 WCHAR *p, *endptr;
470 void *ptr;
471 char **env = __wine_get_main_environment();
473 /* Compute the total size of the Unix environment */
474 for (e = env; *e; e++)
476 if (is_special_env_var( *e )) continue;
477 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
479 size *= sizeof(WCHAR);
481 /* Now allocate the environment */
482 ptr = NULL;
483 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
484 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
485 return FALSE;
487 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
488 endptr = p + size / sizeof(WCHAR);
490 /* And fill it with the Unix environment */
491 for (e = env; *e; e++)
493 char *str = *e;
495 /* skip Unix special variables and use the Wine variants instead */
496 if (!strncmp( str, "WINE", 4 ))
498 if (is_special_env_var( str + 4 )) str += 4;
499 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
501 else if (is_special_env_var( str )) continue; /* skip it */
503 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
504 p += strlenW(p) + 1;
506 *p = 0;
507 return TRUE;
511 /***********************************************************************
512 * set_registry_variables
514 * Set environment variables by enumerating the values of a key;
515 * helper for set_registry_environment().
516 * Note that Windows happily truncates the value if it's too big.
518 static void set_registry_variables( HANDLE hkey, ULONG type )
520 static const WCHAR pathW[] = {'P','A','T','H'};
521 static const WCHAR sep[] = {';',0};
522 UNICODE_STRING env_name, env_value;
523 NTSTATUS status;
524 DWORD size;
525 int index;
526 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
527 WCHAR tmpbuf[1024];
528 UNICODE_STRING tmp;
529 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
531 tmp.Buffer = tmpbuf;
532 tmp.MaximumLength = sizeof(tmpbuf);
534 for (index = 0; ; index++)
536 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
537 buffer, sizeof(buffer), &size );
538 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
539 break;
540 if (info->Type != type)
541 continue;
542 env_name.Buffer = info->Name;
543 env_name.Length = env_name.MaximumLength = info->NameLength;
544 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
545 env_value.Length = info->DataLength;
546 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
547 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
548 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
549 if (!env_value.Length) continue;
550 if (info->Type == REG_EXPAND_SZ)
552 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
553 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
554 RtlCopyUnicodeString( &env_value, &tmp );
556 /* PATH is magic */
557 if (env_name.Length == sizeof(pathW) &&
558 !memicmpW( env_name.Buffer, pathW, ARRAY_SIZE( pathW )) &&
559 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
561 RtlAppendUnicodeToString( &tmp, sep );
562 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
563 RtlCopyUnicodeString( &env_value, &tmp );
565 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
570 /***********************************************************************
571 * set_registry_environment
573 * Set the environment variables specified in the registry.
575 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
576 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
577 * on the order in which the variables are processed. But on Windows it
578 * does not really matter since they only use %SystemDrive% and
579 * %SystemRoot% which are predefined. But Wine defines these in the
580 * registry, so we need two passes.
582 static BOOL set_registry_environment( BOOL volatile_only )
584 static const WCHAR env_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
585 'M','a','c','h','i','n','e','\\',
586 'S','y','s','t','e','m','\\',
587 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
588 'C','o','n','t','r','o','l','\\',
589 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
590 'E','n','v','i','r','o','n','m','e','n','t',0};
591 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
592 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};
594 OBJECT_ATTRIBUTES attr;
595 UNICODE_STRING nameW;
596 HANDLE hkey;
597 BOOL ret = FALSE;
599 attr.Length = sizeof(attr);
600 attr.RootDirectory = 0;
601 attr.ObjectName = &nameW;
602 attr.Attributes = 0;
603 attr.SecurityDescriptor = NULL;
604 attr.SecurityQualityOfService = NULL;
606 /* first the system environment variables */
607 RtlInitUnicodeString( &nameW, env_keyW );
608 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
610 set_registry_variables( hkey, REG_SZ );
611 set_registry_variables( hkey, REG_EXPAND_SZ );
612 NtClose( hkey );
613 ret = TRUE;
616 /* then the ones for the current user */
617 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
618 RtlInitUnicodeString( &nameW, envW );
619 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
621 set_registry_variables( hkey, REG_SZ );
622 set_registry_variables( hkey, REG_EXPAND_SZ );
623 NtClose( hkey );
626 RtlInitUnicodeString( &nameW, volatile_envW );
627 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
629 set_registry_variables( hkey, REG_SZ );
630 set_registry_variables( hkey, REG_EXPAND_SZ );
631 NtClose( hkey );
634 NtClose( attr.RootDirectory );
635 return ret;
639 /***********************************************************************
640 * get_reg_value
642 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
644 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
645 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
646 DWORD len, size = sizeof(buffer);
647 WCHAR *ret = NULL;
648 UNICODE_STRING nameW;
650 RtlInitUnicodeString( &nameW, name );
651 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
652 return NULL;
654 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
655 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
657 if (info->Type == REG_EXPAND_SZ)
659 UNICODE_STRING value, expanded;
661 value.MaximumLength = len * sizeof(WCHAR);
662 value.Buffer = (WCHAR *)info->Data;
663 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
664 value.Length = len * sizeof(WCHAR);
665 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
666 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
667 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
668 else RtlFreeUnicodeString( &expanded );
670 else if (info->Type == REG_SZ)
672 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
674 memcpy( ret, info->Data, len * sizeof(WCHAR) );
675 ret[len] = 0;
678 return ret;
682 /***********************************************************************
683 * set_additional_environment
685 * Set some additional environment variables not specified in the registry.
687 static void set_additional_environment(void)
689 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
690 'M','a','c','h','i','n','e','\\',
691 'S','o','f','t','w','a','r','e','\\',
692 'M','i','c','r','o','s','o','f','t','\\',
693 'W','i','n','d','o','w','s',' ','N','T','\\',
694 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
695 'P','r','o','f','i','l','e','L','i','s','t',0};
696 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
697 static const WCHAR public_valueW[] = {'P','u','b','l','i','c',0};
698 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
699 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
700 static const WCHAR programdataW[] = {'P','r','o','g','r','a','m','D','a','t','a',0};
701 static const WCHAR publicW[] = {'P','U','B','L','I','C',0};
702 OBJECT_ATTRIBUTES attr;
703 UNICODE_STRING nameW;
704 WCHAR *profile_dir = NULL, *program_data_dir = NULL, *public_dir = NULL;
705 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
706 HANDLE hkey;
707 DWORD len;
709 /* ComputerName */
710 len = ARRAY_SIZE( buf );
711 if (GetComputerNameW( buf, &len ))
712 SetEnvironmentVariableW( computernameW, buf );
714 /* set the ALLUSERSPROFILE variables */
716 attr.Length = sizeof(attr);
717 attr.RootDirectory = 0;
718 attr.ObjectName = &nameW;
719 attr.Attributes = 0;
720 attr.SecurityDescriptor = NULL;
721 attr.SecurityQualityOfService = NULL;
722 RtlInitUnicodeString( &nameW, profile_keyW );
723 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
725 profile_dir = get_reg_value( hkey, profiles_valueW );
726 program_data_dir = get_reg_value( hkey, programdataW );
727 public_dir = get_reg_value( hkey, public_valueW );
728 NtClose( hkey );
731 if (program_data_dir)
733 SetEnvironmentVariableW( allusersW, program_data_dir );
734 SetEnvironmentVariableW( programdataW, program_data_dir );
737 if (public_dir)
739 SetEnvironmentVariableW( publicW, public_dir );
742 HeapFree( GetProcessHeap(), 0, profile_dir );
743 HeapFree( GetProcessHeap(), 0, program_data_dir );
744 HeapFree( GetProcessHeap(), 0, public_dir );
747 /***********************************************************************
748 * set_wow64_environment
750 * Set the environment variables that change across 32/64/Wow64.
752 static void set_wow64_environment(void)
754 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};
755 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};
756 static const WCHAR x86W[] = {'x','8','6',0};
757 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
758 'M','a','c','h','i','n','e','\\',
759 'S','o','f','t','w','a','r','e','\\',
760 'M','i','c','r','o','s','o','f','t','\\',
761 'W','i','n','d','o','w','s','\\',
762 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
763 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
764 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
765 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
766 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
767 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
768 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
769 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
770 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
772 OBJECT_ATTRIBUTES attr;
773 UNICODE_STRING nameW;
774 WCHAR arch[64];
775 WCHAR *value;
776 HANDLE hkey;
778 /* set the PROCESSOR_ARCHITECTURE variable */
780 if (GetEnvironmentVariableW( arch6432W, arch, ARRAY_SIZE( arch )))
782 if (is_win64)
784 SetEnvironmentVariableW( archW, arch );
785 SetEnvironmentVariableW( arch6432W, NULL );
788 else if (GetEnvironmentVariableW( archW, arch, ARRAY_SIZE( arch )))
790 if (is_wow64)
792 SetEnvironmentVariableW( arch6432W, arch );
793 SetEnvironmentVariableW( archW, x86W );
797 attr.Length = sizeof(attr);
798 attr.RootDirectory = 0;
799 attr.ObjectName = &nameW;
800 attr.Attributes = 0;
801 attr.SecurityDescriptor = NULL;
802 attr.SecurityQualityOfService = NULL;
803 RtlInitUnicodeString( &nameW, versionW );
804 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
806 /* set the ProgramFiles variables */
808 if ((value = get_reg_value( hkey, progdirW )))
810 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
811 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
812 HeapFree( GetProcessHeap(), 0, value );
814 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
816 SetEnvironmentVariableW( progfilesW, value );
817 HeapFree( GetProcessHeap(), 0, value );
820 /* set the CommonProgramFiles variables */
822 if ((value = get_reg_value( hkey, commondirW )))
824 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
825 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
826 HeapFree( GetProcessHeap(), 0, value );
828 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
830 SetEnvironmentVariableW( commonfilesW, value );
831 HeapFree( GetProcessHeap(), 0, value );
834 NtClose( hkey );
837 /***********************************************************************
838 * set_library_wargv
840 * Set the Wine library Unicode argv global variables.
842 static void set_library_wargv( char **argv )
844 int argc;
845 char *q;
846 WCHAR *p;
847 WCHAR **wargv;
848 DWORD total = 0;
850 for (argc = 0; argv[argc]; argc++)
851 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
853 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
854 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
855 p = (WCHAR *)(wargv + argc + 1);
856 for (argc = 0; argv[argc]; argc++)
858 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
859 wargv[argc] = p;
860 p += reslen;
861 total -= reslen;
863 wargv[argc] = NULL;
865 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
867 for (argc = 0; wargv[argc]; argc++)
868 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
870 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
871 q = (char *)(argv + argc + 1);
872 for (argc = 0; wargv[argc]; argc++)
874 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
875 argv[argc] = q;
876 q += reslen;
877 total -= reslen;
879 argv[argc] = NULL;
881 __wine_main_argc = argc;
882 __wine_main_argv = argv;
883 __wine_main_wargv = wargv;
887 /***********************************************************************
888 * update_library_argv0
890 * Update the argv[0] global variable with the binary we have found.
892 static void update_library_argv0( const WCHAR *argv0 )
894 DWORD len = strlenW( argv0 );
896 if (len > strlenW( __wine_main_wargv[0] ))
898 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
900 strcpyW( __wine_main_wargv[0], argv0 );
902 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
903 if (len > strlen( __wine_main_argv[0] ) + 1)
905 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
907 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
911 /***********************************************************************
912 * build_command_line
914 * Build the command line of a process from the argv array.
916 * Note that it does NOT necessarily include the file name.
917 * Sometimes we don't even have any command line options at all.
919 * We must quote and escape characters so that the argv array can be rebuilt
920 * from the command line:
921 * - spaces and tabs must be quoted
922 * 'a b' -> '"a b"'
923 * - quotes must be escaped
924 * '"' -> '\"'
925 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
926 * resulting in an odd number of '\' followed by a '"'
927 * '\"' -> '\\\"'
928 * '\\"' -> '\\\\\"'
929 * - '\'s are followed by the closing '"' must be doubled,
930 * resulting in an even number of '\' followed by a '"'
931 * ' \' -> '" \\"'
932 * ' \\' -> '" \\\\"'
933 * - '\'s that are not followed by a '"' can be left as is
934 * 'a\b' == 'a\b'
935 * 'a\\b' == 'a\\b'
937 static BOOL build_command_line( WCHAR **argv )
939 int len;
940 WCHAR **arg;
941 LPWSTR p;
942 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
944 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
946 len = 0;
947 for (arg = argv; *arg; arg++)
949 BOOL has_space;
950 int bcount;
951 WCHAR* a;
953 has_space=FALSE;
954 bcount=0;
955 a=*arg;
956 if( !*a ) has_space=TRUE;
957 while (*a!='\0') {
958 if (*a=='\\') {
959 bcount++;
960 } else {
961 if (*a==' ' || *a=='\t') {
962 has_space=TRUE;
963 } else if (*a=='"') {
964 /* doubling of '\' preceding a '"',
965 * plus escaping of said '"'
967 len+=2*bcount+1;
969 bcount=0;
971 a++;
973 len+=(a-*arg)+1 /* for the separating space */;
974 if (has_space)
975 len+=2+bcount; /* for the quotes and doubling of '\' preceding the closing quote */
978 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
979 return FALSE;
981 p = rupp->CommandLine.Buffer;
982 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
983 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
984 for (arg = argv; *arg; arg++)
986 BOOL has_space,has_quote;
987 WCHAR* a;
988 int bcount;
990 /* Check for quotes and spaces in this argument */
991 has_space=has_quote=FALSE;
992 a=*arg;
993 if( !*a ) has_space=TRUE;
994 while (*a!='\0') {
995 if (*a==' ' || *a=='\t') {
996 has_space=TRUE;
997 if (has_quote)
998 break;
999 } else if (*a=='"') {
1000 has_quote=TRUE;
1001 if (has_space)
1002 break;
1004 a++;
1007 /* Now transfer it to the command line */
1008 if (has_space)
1009 *p++='"';
1010 if (has_quote || has_space) {
1011 bcount=0;
1012 a=*arg;
1013 while (*a!='\0') {
1014 if (*a=='\\') {
1015 *p++=*a;
1016 bcount++;
1017 } else {
1018 if (*a=='"') {
1019 int i;
1021 /* Double all the '\\' preceding this '"', plus one */
1022 for (i=0;i<=bcount;i++)
1023 *p++='\\';
1024 *p++='"';
1025 } else {
1026 *p++=*a;
1028 bcount=0;
1030 a++;
1032 } else {
1033 WCHAR* x = *arg;
1034 while ((*p=*x++)) p++;
1036 if (has_space) {
1037 int i;
1039 /* Double all the '\' preceding the closing quote */
1040 for (i=0;i<bcount;i++)
1041 *p++='\\';
1042 *p++='"';
1044 *p++=' ';
1046 if (p > rupp->CommandLine.Buffer)
1047 p--; /* remove last space */
1048 *p = '\0';
1050 return TRUE;
1054 /***********************************************************************
1055 * init_current_directory
1057 * Initialize the current directory from the Unix cwd or the parent info.
1059 static void init_current_directory( CURDIR *cur_dir )
1061 UNICODE_STRING dir_str;
1062 const char *pwd;
1063 char *cwd;
1064 int size;
1066 /* if we received a cur dir from the parent, try this first */
1068 if (cur_dir->DosPath.Length)
1070 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
1073 /* now try to get it from the Unix cwd */
1075 for (size = 256; ; size *= 2)
1077 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
1078 if (getcwd( cwd, size )) break;
1079 HeapFree( GetProcessHeap(), 0, cwd );
1080 if (errno == ERANGE) continue;
1081 cwd = NULL;
1082 break;
1085 /* try to use PWD if it is valid, so that we don't resolve symlinks */
1087 pwd = getenv( "PWD" );
1088 if (cwd)
1090 struct stat st1, st2;
1092 if (!pwd || stat( pwd, &st1 ) == -1 ||
1093 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
1094 pwd = cwd;
1097 if (pwd)
1099 ANSI_STRING unix_name;
1100 UNICODE_STRING nt_name;
1101 RtlInitAnsiString( &unix_name, pwd );
1102 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
1104 UNICODE_STRING dos_path;
1105 /* skip the \??\ prefix, nt_name is 0 terminated */
1106 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
1107 RtlSetCurrentDirectory_U( &dos_path );
1108 RtlFreeUnicodeString( &nt_name );
1112 if (!cur_dir->DosPath.Length) /* still not initialized */
1114 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
1115 "starting in the Windows directory.\n", cwd ? cwd : "" );
1116 RtlInitUnicodeString( &dir_str, DIR_Windows );
1117 RtlSetCurrentDirectory_U( &dir_str );
1119 HeapFree( GetProcessHeap(), 0, cwd );
1121 done:
1122 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
1126 /***********************************************************************
1127 * init_windows_dirs
1129 * Create the windows and system directories if necessary.
1131 static void init_windows_dirs(void)
1133 static const WCHAR default_syswow64W[] = {'C',':','\\','w','i','n','d','o','w','s',
1134 '\\','s','y','s','w','o','w','6','4',0};
1136 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1137 ERR( "directory %s could not be created, error %u\n",
1138 debugstr_w(DIR_Windows), GetLastError() );
1139 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1140 ERR( "directory %s could not be created, error %u\n",
1141 debugstr_w(DIR_System), GetLastError() );
1143 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
1145 DIR_SysWow64 = default_syswow64W;
1146 memcpy( winevdm, default_syswow64W, sizeof(default_syswow64W) - sizeof(WCHAR) );
1147 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1148 ERR( "directory %s could not be created, error %u\n",
1149 debugstr_w(DIR_SysWow64), GetLastError() );
1154 /***********************************************************************
1155 * start_wineboot
1157 * Start the wineboot process if necessary. Return the handles to wait on.
1159 static void start_wineboot( HANDLE handles[2] )
1161 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1163 handles[1] = 0;
1164 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1166 ERR( "failed to create wineboot event, expect trouble\n" );
1167 return;
1169 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1171 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1172 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1173 STARTUPINFOW si;
1174 PROCESS_INFORMATION pi;
1175 void *redir;
1176 WCHAR app[MAX_PATH];
1177 WCHAR cmdline[MAX_PATH + ARRAY_SIZE( wineboot ) + ARRAY_SIZE( args )];
1179 memset( &si, 0, sizeof(si) );
1180 si.cb = sizeof(si);
1181 si.dwFlags = STARTF_USESTDHANDLES;
1182 si.hStdInput = 0;
1183 si.hStdOutput = 0;
1184 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1186 GetSystemDirectoryW( app, MAX_PATH - ARRAY_SIZE( wineboot ));
1187 lstrcatW( app, wineboot );
1189 Wow64DisableWow64FsRedirection( &redir );
1190 strcpyW( cmdline, app );
1191 strcatW( cmdline, args );
1192 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1194 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1195 CloseHandle( pi.hThread );
1196 handles[1] = pi.hProcess;
1198 else
1200 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1201 CloseHandle( handles[0] );
1202 handles[0] = 0;
1204 Wow64RevertWow64FsRedirection( redir );
1209 #ifdef __i386__
1210 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1211 __ASM_GLOBAL_FUNC( call_process_entry,
1212 "pushl %ebp\n\t"
1213 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1214 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1215 "movl %esp,%ebp\n\t"
1216 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1217 "pushl 4(%ebp)\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1218 "pushl 4(%ebp)\n\t" /* Driller expects readable address at this offset */
1219 "pushl 4(%ebp)\n\t"
1220 "pushl 8(%ebp)\n\t"
1221 "call *12(%ebp)\n\t"
1222 "leave\n\t"
1223 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1224 __ASM_CFI(".cfi_same_value %ebp\n\t")
1225 "ret" )
1227 extern void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb ) DECLSPEC_HIDDEN;
1228 extern void WINAPI start_process_wrapper(void) DECLSPEC_HIDDEN;
1229 __ASM_GLOBAL_FUNC( start_process_wrapper,
1230 "pushl %ebp\n\t"
1231 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1232 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1233 "movl %esp,%ebp\n\t"
1234 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1235 "pushl %ebx\n\t" /* arg */
1236 "pushl %eax\n\t" /* entry */
1237 "call " __ASM_NAME("start_process") )
1238 #else
1239 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1241 return entry( peb );
1243 static void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb );
1244 #define start_process_wrapper start_process
1245 #endif
1247 /***********************************************************************
1248 * start_process
1250 * Startup routine of a new process. Runs on the new process stack.
1252 void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb )
1254 BOOL being_debugged;
1256 if (!entry)
1258 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1259 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1260 ExitThread( 1 );
1263 TRACE_(relay)( "\1Starting process %s (entryproc=%p)\n",
1264 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1266 __TRY
1268 if (!CheckRemoteDebuggerPresent( GetCurrentProcess(), &being_debugged ))
1269 being_debugged = FALSE;
1271 SetLastError( 0 ); /* clear error code */
1272 if (being_debugged) DbgBreakPoint();
1273 ExitThread( call_process_entry( peb, entry ));
1275 __EXCEPT(UnhandledExceptionFilter)
1277 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1279 __ENDTRY
1280 abort(); /* should not be reached */
1284 /***********************************************************************
1285 * set_process_name
1287 * Change the process name in the ps output.
1289 static void set_process_name( int argc, char *argv[] )
1291 BOOL shift_strings;
1292 char *p, *name;
1293 int i;
1295 #ifdef HAVE_SETPROCTITLE
1296 setproctitle("-%s", argv[1]);
1297 shift_strings = FALSE;
1298 #else
1299 p = argv[0];
1301 shift_strings = (argc >= 2);
1302 for (i = 1; i < argc; i++)
1304 p += strlen(p) + 1;
1305 if (p != argv[i])
1307 shift_strings = FALSE;
1308 break;
1311 #endif
1313 if (shift_strings)
1315 int offset = argv[1] - argv[0];
1316 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1317 memmove( argv[0], argv[1], end - argv[1] );
1318 memset( end - offset, 0, offset );
1319 for (i = 1; i < argc; i++)
1320 argv[i-1] = argv[i] - offset;
1321 argv[i-1] = NULL;
1323 else
1325 /* remove argv[0] */
1326 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1329 name = argv[0];
1330 if ((p = strrchr( name, '\\' ))) name = p + 1;
1331 if ((p = strrchr( name, '/' ))) name = p + 1;
1333 #if defined(HAVE_SETPROGNAME)
1334 setprogname( name );
1335 #endif
1337 #ifdef HAVE_PRCTL
1338 #ifndef PR_SET_NAME
1339 # define PR_SET_NAME 15
1340 #endif
1341 prctl( PR_SET_NAME, name );
1342 #endif /* HAVE_PRCTL */
1346 /***********************************************************************
1347 * __wine_kernel_init
1349 * Wine initialisation: load and start the main exe file.
1351 void CDECL __wine_kernel_init(void)
1353 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1354 static const WCHAR dotW[] = {'.',0};
1356 WCHAR *p, main_exe_name[MAX_PATH+1];
1357 PEB *peb = NtCurrentTeb()->Peb;
1358 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1359 HANDLE boot_events[2];
1360 BOOL got_environment = TRUE;
1362 /* Initialize everything */
1364 setbuf(stdout,NULL);
1365 setbuf(stderr,NULL);
1366 kernel32_handle = GetModuleHandleW(kernel32W);
1367 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1368 RtlSetUnhandledExceptionFilter( UnhandledExceptionFilter );
1370 LOCALE_Init();
1372 if (!params->Environment)
1374 /* Copy the parent environment */
1375 if (!build_initial_environment()) exit(1);
1377 /* convert old configuration to new format */
1378 convert_old_config();
1380 got_environment = set_registry_environment( FALSE );
1381 set_additional_environment();
1384 init_windows_dirs();
1385 init_current_directory( &params->CurrentDirectory );
1387 set_process_name( __wine_main_argc, __wine_main_argv );
1388 set_library_wargv( __wine_main_argv );
1389 boot_events[0] = boot_events[1] = 0;
1391 if (peb->ProcessParameters->ImagePathName.Buffer)
1393 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1395 else
1397 BOOL is_64bit;
1399 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1400 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &is_64bit ))
1402 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1403 ExitProcess( GetLastError() );
1405 update_library_argv0( main_exe_name );
1406 if (!build_command_line( __wine_main_wargv )) goto error;
1407 start_wineboot( boot_events );
1410 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1411 p = strrchrW( main_exe_name, '.' );
1412 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1414 TRACE( "starting process name=%s argv[0]=%s\n",
1415 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1417 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1418 MODULE_get_dll_load_path( main_exe_name, -1 ));
1420 if (boot_events[0])
1422 DWORD timeout = 2 * 60 * 1000, count = 1;
1424 if (boot_events[1]) count++;
1425 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1426 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1427 ERR( "boot event wait timed out\n" );
1428 CloseHandle( boot_events[0] );
1429 if (boot_events[1]) CloseHandle( boot_events[1] );
1430 /* reload environment now that wineboot has run */
1431 set_registry_environment( got_environment );
1432 set_additional_environment();
1434 set_wow64_environment();
1436 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1438 DWORD_PTR args[1];
1439 WCHAR msgW[1024];
1440 char msg[1024];
1441 DWORD error = GetLastError();
1443 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1444 if (error == ERROR_BAD_EXE_FORMAT ||
1445 error == ERROR_INVALID_ADDRESS ||
1446 error == ERROR_NOT_ENOUGH_MEMORY)
1448 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1449 /* if we get back here, it failed */
1451 else if (error == ERROR_MOD_NOT_FOUND)
1453 if (!strcmpiW( main_exe_name, winevdm ) && __wine_main_argc > 3)
1455 /* args 1 and 2 are --app-name full_path */
1456 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1457 debugstr_w(__wine_main_wargv[3]) );
1458 ExitProcess( ERROR_BAD_EXE_FORMAT );
1460 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1461 ExitProcess( ERROR_FILE_NOT_FOUND );
1463 args[0] = (DWORD_PTR)main_exe_name;
1464 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1465 NULL, error, 0, msgW, ARRAY_SIZE( msgW ), (__ms_va_list *)args );
1466 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1467 MESSAGE( "wine: %s", msg );
1468 ExitProcess( error );
1471 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1473 LdrInitializeThunk( start_process_wrapper, 0, 0, 0 );
1475 error:
1476 ExitProcess( GetLastError() );
1480 /***********************************************************************
1481 * build_argv
1483 * Build an argv array from a command-line.
1484 * 'reserved' is the number of args to reserve before the first one.
1486 static char **build_argv( const UNICODE_STRING *cmdlineW, int reserved )
1488 int argc;
1489 char** argv;
1490 char *arg,*s,*d,*cmdline;
1491 int in_quotes,bcount,len;
1493 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW->Buffer, cmdlineW->Length / sizeof(WCHAR),
1494 NULL, 0, NULL, NULL );
1495 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1496 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW->Buffer, cmdlineW->Length / sizeof(WCHAR),
1497 cmdline, len, NULL, NULL );
1498 cmdline[len++] = 0;
1500 argc=reserved+1;
1501 bcount=0;
1502 in_quotes=0;
1503 s=cmdline;
1504 while (1) {
1505 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1506 /* space */
1507 argc++;
1508 /* skip the remaining spaces */
1509 while (*s==' ' || *s=='\t') {
1510 s++;
1512 if (*s=='\0')
1513 break;
1514 bcount=0;
1515 continue;
1516 } else if (*s=='\\') {
1517 /* '\', count them */
1518 bcount++;
1519 } else if ((*s=='"') && ((bcount & 1)==0)) {
1520 /* unescaped '"' */
1521 in_quotes=!in_quotes;
1522 bcount=0;
1523 } else {
1524 /* a regular character */
1525 bcount=0;
1527 s++;
1529 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1531 HeapFree( GetProcessHeap(), 0, cmdline );
1532 return NULL;
1535 arg = d = s = (char *)(argv + argc);
1536 memcpy( d, cmdline, len );
1537 bcount=0;
1538 in_quotes=0;
1539 argc=reserved;
1540 while (*s) {
1541 if ((*s==' ' || *s=='\t') && !in_quotes) {
1542 /* Close the argument and copy it */
1543 *d=0;
1544 argv[argc++]=arg;
1546 /* skip the remaining spaces */
1547 do {
1548 s++;
1549 } while (*s==' ' || *s=='\t');
1551 /* Start with a new argument */
1552 arg=d=s;
1553 bcount=0;
1554 } else if (*s=='\\') {
1555 /* '\\' */
1556 *d++=*s++;
1557 bcount++;
1558 } else if (*s=='"') {
1559 /* '"' */
1560 if ((bcount & 1)==0) {
1561 /* Preceded by an even number of '\', this is half that
1562 * number of '\', plus a '"' which we discard.
1564 d-=bcount/2;
1565 s++;
1566 in_quotes=!in_quotes;
1567 } else {
1568 /* Preceded by an odd number of '\', this is half that
1569 * number of '\' followed by a '"'
1571 d=d-bcount/2-1;
1572 *d++='"';
1573 s++;
1575 bcount=0;
1576 } else {
1577 /* a regular character */
1578 *d++=*s++;
1579 bcount=0;
1582 if (*arg) {
1583 *d='\0';
1584 argv[argc++]=arg;
1586 argv[argc]=NULL;
1588 HeapFree( GetProcessHeap(), 0, cmdline );
1589 return argv;
1593 /***********************************************************************
1594 * build_envp
1596 * Build the environment of a new child process.
1598 static char **build_envp( const WCHAR *envW )
1600 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1602 const WCHAR *end;
1603 char **envp;
1604 char *env, *p;
1605 int count = 1, length;
1606 unsigned int i;
1608 for (end = envW; *end; count++) end += strlenW(end) + 1;
1609 end++;
1610 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1611 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1612 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1614 for (p = env; *p; p += strlen(p) + 1)
1615 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1617 for (i = 0; i < ARRAY_SIZE( unix_vars ); i++)
1619 if (!(p = getenv(unix_vars[i]))) continue;
1620 length += strlen(unix_vars[i]) + strlen(p) + 2;
1621 count++;
1624 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1626 char **envptr = envp;
1627 char *dst = (char *)(envp + count);
1629 /* some variables must not be modified, so we get them directly from the unix env */
1630 for (i = 0; i < ARRAY_SIZE( unix_vars ); i++)
1632 if (!(p = getenv(unix_vars[i]))) continue;
1633 *envptr++ = strcpy( dst, unix_vars[i] );
1634 strcat( dst, "=" );
1635 strcat( dst, p );
1636 dst += strlen(dst) + 1;
1639 /* now put the Windows environment strings */
1640 for (p = env; *p; p += strlen(p) + 1)
1642 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1643 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1644 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1645 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1646 if (is_special_env_var( p )) /* prefix it with "WINE" */
1648 *envptr++ = strcpy( dst, "WINE" );
1649 strcat( dst, p );
1651 else
1653 *envptr++ = strcpy( dst, p );
1655 dst += strlen(dst) + 1;
1657 *envptr = 0;
1659 HeapFree( GetProcessHeap(), 0, env );
1660 return envp;
1664 /***********************************************************************
1665 * fork_and_exec
1667 * Fork and exec a new Unix binary, checking for errors.
1669 static int fork_and_exec( const RTL_USER_PROCESS_PARAMETERS *params, const char *newdir )
1671 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1672 int pid, err;
1673 char *filename, **argv, **envp;
1675 if (!(filename = wine_get_unix_file_name( params->ImagePathName.Buffer ))) return -1;
1677 #ifdef HAVE_PIPE2
1678 if (pipe2( fd, O_CLOEXEC ) == -1)
1679 #endif
1681 if (pipe(fd) == -1)
1683 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1684 HeapFree( GetProcessHeap(), 0, filename );
1685 return -1;
1687 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1688 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1691 wine_server_handle_to_fd( params->hStdInput, FILE_READ_DATA, &stdin_fd, NULL );
1692 wine_server_handle_to_fd( params->hStdOutput, FILE_WRITE_DATA, &stdout_fd, NULL );
1693 wine_server_handle_to_fd( params->hStdError, FILE_WRITE_DATA, &stderr_fd, NULL );
1695 argv = build_argv( &params->CommandLine, 0 );
1696 envp = build_envp( params->Environment );
1698 if (!(pid = fork())) /* child */
1700 if (!(pid = fork())) /* grandchild */
1702 close( fd[0] );
1704 if (params->ConsoleFlags || params->ConsoleHandle == KERNEL32_CONSOLE_ALLOC ||
1705 (params->hStdInput == INVALID_HANDLE_VALUE && params->hStdOutput == INVALID_HANDLE_VALUE))
1707 int nullfd = open( "/dev/null", O_RDWR );
1708 setsid();
1709 /* close stdin and stdout */
1710 if (nullfd != -1)
1712 dup2( nullfd, 0 );
1713 dup2( nullfd, 1 );
1714 close( nullfd );
1717 else
1719 if (stdin_fd != -1)
1721 dup2( stdin_fd, 0 );
1722 close( stdin_fd );
1724 if (stdout_fd != -1)
1726 dup2( stdout_fd, 1 );
1727 close( stdout_fd );
1729 if (stderr_fd != -1)
1731 dup2( stderr_fd, 2 );
1732 close( stderr_fd );
1736 /* Reset signals that we previously set to SIG_IGN */
1737 signal( SIGPIPE, SIG_DFL );
1739 if (newdir) chdir(newdir);
1741 if (argv && envp) execve( filename, argv, envp );
1744 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1746 err = errno;
1747 write( fd[1], &err, sizeof(err) );
1748 _exit(1);
1751 _exit(0); /* child if fork succeeded */
1753 HeapFree( GetProcessHeap(), 0, argv );
1754 HeapFree( GetProcessHeap(), 0, envp );
1755 HeapFree( GetProcessHeap(), 0, filename );
1756 if (stdin_fd != -1) close( stdin_fd );
1757 if (stdout_fd != -1) close( stdout_fd );
1758 if (stderr_fd != -1) close( stderr_fd );
1759 close( fd[1] );
1760 if (pid != -1)
1762 /* reap child */
1763 do {
1764 err = waitpid(pid, NULL, 0);
1765 } while (err < 0 && errno == EINTR);
1767 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1769 errno = err;
1770 pid = -1;
1773 if (pid == -1) FILE_SetDosError();
1774 close( fd[0] );
1775 return pid;
1779 static inline const WCHAR *get_params_string( const RTL_USER_PROCESS_PARAMETERS *params,
1780 const UNICODE_STRING *str )
1782 if (params->Flags & PROCESS_PARAMS_FLAG_NORMALIZED) return str->Buffer;
1783 return (const WCHAR *)((const char *)params + (UINT_PTR)str->Buffer);
1786 static inline DWORD append_string( void **ptr, const RTL_USER_PROCESS_PARAMETERS *params,
1787 const UNICODE_STRING *str )
1789 const WCHAR *buffer = get_params_string( params, str );
1790 memcpy( *ptr, buffer, str->Length );
1791 *ptr = (WCHAR *)*ptr + str->Length / sizeof(WCHAR);
1792 return str->Length;
1795 /***********************************************************************
1796 * create_startup_info
1798 static startup_info_t *create_startup_info( const RTL_USER_PROCESS_PARAMETERS *params, DWORD *info_size )
1800 startup_info_t *info;
1801 DWORD size;
1802 void *ptr;
1804 size = sizeof(*info);
1805 size += params->CurrentDirectory.DosPath.Length;
1806 size += params->DllPath.Length;
1807 size += params->ImagePathName.Length;
1808 size += params->CommandLine.Length;
1809 size += params->WindowTitle.Length;
1810 size += params->Desktop.Length;
1811 size += params->ShellInfo.Length;
1812 size += params->RuntimeInfo.Length;
1813 size = (size + 1) & ~1;
1814 *info_size = size;
1816 if (!(info = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) return NULL;
1818 info->console_flags = params->ConsoleFlags;
1819 info->console = wine_server_obj_handle( params->ConsoleHandle );
1820 info->hstdin = wine_server_obj_handle( params->hStdInput );
1821 info->hstdout = wine_server_obj_handle( params->hStdOutput );
1822 info->hstderr = wine_server_obj_handle( params->hStdError );
1823 info->x = params->dwX;
1824 info->y = params->dwY;
1825 info->xsize = params->dwXSize;
1826 info->ysize = params->dwYSize;
1827 info->xchars = params->dwXCountChars;
1828 info->ychars = params->dwYCountChars;
1829 info->attribute = params->dwFillAttribute;
1830 info->flags = params->dwFlags;
1831 info->show = params->wShowWindow;
1833 ptr = info + 1;
1834 info->curdir_len = append_string( &ptr, params, &params->CurrentDirectory.DosPath );
1835 info->dllpath_len = append_string( &ptr, params, &params->DllPath );
1836 info->imagepath_len = append_string( &ptr, params, &params->ImagePathName );
1837 info->cmdline_len = append_string( &ptr, params, &params->CommandLine );
1838 info->title_len = append_string( &ptr, params, &params->WindowTitle );
1839 info->desktop_len = append_string( &ptr, params, &params->Desktop );
1840 info->shellinfo_len = append_string( &ptr, params, &params->ShellInfo );
1841 info->runtime_len = append_string( &ptr, params, &params->RuntimeInfo );
1842 return info;
1846 /***********************************************************************
1847 * create_process_params
1849 static RTL_USER_PROCESS_PARAMETERS *create_process_params( LPCWSTR filename, LPCWSTR cmdline,
1850 LPCWSTR cur_dir, void *env, DWORD flags,
1851 const STARTUPINFOW *startup )
1853 RTL_USER_PROCESS_PARAMETERS *params;
1854 UNICODE_STRING imageW, curdirW, cmdlineW, titleW, desktopW, runtimeW, newdirW;
1855 WCHAR imagepath[MAX_PATH];
1856 WCHAR *envW = env;
1858 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1859 lstrcpynW( imagepath, filename, MAX_PATH );
1860 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1861 lstrcpynW( imagepath, filename, MAX_PATH );
1863 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1865 char *e = env;
1866 DWORD lenW;
1868 while (*e) e += strlen(e) + 1;
1869 e++; /* final null */
1870 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char *)env, NULL, 0 );
1871 if ((envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
1872 MultiByteToWideChar( CP_ACP, 0, env, e - (char *)env, envW, lenW );
1875 newdirW.Buffer = NULL;
1876 if (cur_dir)
1878 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdirW, NULL, NULL ))
1879 cur_dir = newdirW.Buffer + 4; /* skip \??\ prefix */
1880 else
1881 cur_dir = NULL;
1883 RtlInitUnicodeString( &imageW, imagepath );
1884 RtlInitUnicodeString( &curdirW, cur_dir );
1885 RtlInitUnicodeString( &cmdlineW, cmdline );
1886 RtlInitUnicodeString( &titleW, startup->lpTitle ? startup->lpTitle : imagepath );
1887 RtlInitUnicodeString( &desktopW, startup->lpDesktop );
1888 runtimeW.Buffer = (WCHAR *)startup->lpReserved2;
1889 runtimeW.Length = runtimeW.MaximumLength = startup->cbReserved2;
1890 if (RtlCreateProcessParametersEx( &params, &imageW, NULL, cur_dir ? &curdirW : NULL,
1891 &cmdlineW, envW, &titleW, &desktopW,
1892 NULL, &runtimeW, PROCESS_PARAMS_FLAG_NORMALIZED ))
1894 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1895 return NULL;
1898 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1899 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = KERNEL32_CONSOLE_ALLOC;
1901 if (startup->dwFlags & STARTF_USESTDHANDLES)
1903 params->hStdInput = startup->hStdInput;
1904 params->hStdOutput = startup->hStdOutput;
1905 params->hStdError = startup->hStdError;
1907 else if (flags & DETACHED_PROCESS)
1909 params->hStdInput = INVALID_HANDLE_VALUE;
1910 params->hStdOutput = INVALID_HANDLE_VALUE;
1911 params->hStdError = INVALID_HANDLE_VALUE;
1913 else
1915 params->hStdInput = NtCurrentTeb()->Peb->ProcessParameters->hStdInput;
1916 params->hStdOutput = NtCurrentTeb()->Peb->ProcessParameters->hStdOutput;
1917 params->hStdError = NtCurrentTeb()->Peb->ProcessParameters->hStdError;
1920 if (flags & CREATE_NEW_CONSOLE)
1922 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1923 if (is_console_handle(params->hStdInput)) params->hStdInput = INVALID_HANDLE_VALUE;
1924 if (is_console_handle(params->hStdOutput)) params->hStdOutput = INVALID_HANDLE_VALUE;
1925 if (is_console_handle(params->hStdError)) params->hStdError = INVALID_HANDLE_VALUE;
1927 else
1929 if (is_console_handle(params->hStdInput)) params->hStdInput = (HANDLE)((UINT_PTR)params->hStdInput & ~3);
1930 if (is_console_handle(params->hStdOutput)) params->hStdOutput = (HANDLE)((UINT_PTR)params->hStdOutput & ~3);
1931 if (is_console_handle(params->hStdError)) params->hStdError = (HANDLE)((UINT_PTR)params->hStdError & ~3);
1934 params->dwX = startup->dwX;
1935 params->dwY = startup->dwY;
1936 params->dwXSize = startup->dwXSize;
1937 params->dwYSize = startup->dwYSize;
1938 params->dwXCountChars = startup->dwXCountChars;
1939 params->dwYCountChars = startup->dwYCountChars;
1940 params->dwFillAttribute = startup->dwFillAttribute;
1941 params->dwFlags = startup->dwFlags;
1942 params->wShowWindow = startup->wShowWindow;
1944 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1945 return params;
1948 /***********************************************************************
1949 * get_alternate_loader
1951 * Get the name of the alternate (32 or 64 bit) Wine loader.
1953 static const char *get_alternate_loader( char **ret_env )
1955 char *env;
1956 const char *loader = NULL;
1957 const char *loader_env = getenv( "WINELOADER" );
1959 *ret_env = NULL;
1961 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1963 if (loader_env)
1965 int len = strlen( loader_env );
1966 if (!is_win64)
1968 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1969 strcpy( env, "WINELOADER=" );
1970 strcat( env, loader_env );
1971 strcat( env, "64" );
1973 else
1975 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1976 strcpy( env, "WINELOADER=" );
1977 strcat( env, loader_env );
1978 len += sizeof("WINELOADER=") - 1;
1979 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1981 if (!loader)
1983 if ((loader = strrchr( env, '/' ))) loader++;
1984 else loader = env;
1986 *ret_env = env;
1988 if (!loader) loader = is_win64 ? "wine" : "wine64";
1989 return loader;
1992 #ifdef __APPLE__
1993 /***********************************************************************
1994 * terminate_main_thread
1996 * On some versions of Mac OS X, the execve system call fails with
1997 * ENOTSUP if the process has multiple threads. Wine is always multi-
1998 * threaded on Mac OS X because it specifically reserves the main thread
1999 * for use by the system frameworks (see apple_main_thread() in
2000 * libs/wine/loader.c). So, when we need to exec without first forking,
2001 * we need to terminate the main thread first. We do this by installing
2002 * a custom run loop source onto the main run loop and signaling it.
2003 * The source's "perform" callback is pthread_exit and it will be
2004 * executed on the main thread, terminating it.
2006 * Returns TRUE if there's still hope the main thread has terminated or
2007 * will soon. Return FALSE if we've given up.
2009 static BOOL terminate_main_thread(void)
2011 static int delayms;
2013 if (!delayms)
2015 CFRunLoopSourceContext source_context = { 0 };
2016 CFRunLoopSourceRef source;
2018 source_context.perform = pthread_exit;
2019 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
2020 return FALSE;
2022 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
2023 CFRunLoopSourceSignal( source );
2024 CFRunLoopWakeUp( CFRunLoopGetMain() );
2025 CFRelease( source );
2027 delayms = 20;
2030 if (delayms > 1000)
2031 return FALSE;
2033 usleep(delayms * 1000);
2034 delayms *= 2;
2036 return TRUE;
2038 #endif
2040 /***********************************************************************
2041 * spawn_loader
2043 static pid_t spawn_loader( const RTL_USER_PROCESS_PARAMETERS *params, int socketfd,
2044 const char *unixdir, char *winedebug, const pe_image_info_t *pe_info )
2046 pid_t pid;
2047 int stdin_fd = -1, stdout_fd = -1;
2048 char *wineloader = NULL;
2049 const char *loader = NULL;
2050 char **argv;
2052 argv = build_argv( &params->CommandLine, 1 );
2054 if (!is_win64 ^ !is_64bit_arch( pe_info->cpu ))
2055 loader = get_alternate_loader( &wineloader );
2057 wine_server_handle_to_fd( params->hStdInput, FILE_READ_DATA, &stdin_fd, NULL );
2058 wine_server_handle_to_fd( params->hStdOutput, FILE_WRITE_DATA, &stdout_fd, NULL );
2060 if (!(pid = fork())) /* child */
2062 if (!(pid = fork())) /* grandchild */
2064 char preloader_reserve[64], socket_env[64];
2065 ULONGLONG res_start = pe_info->base;
2066 ULONGLONG res_end = pe_info->base + pe_info->map_size;
2068 if (params->ConsoleFlags || params->ConsoleHandle == KERNEL32_CONSOLE_ALLOC ||
2069 (params->hStdInput == INVALID_HANDLE_VALUE && params->hStdOutput == INVALID_HANDLE_VALUE))
2071 int fd = open( "/dev/null", O_RDWR );
2072 setsid();
2073 /* close stdin and stdout */
2074 if (fd != -1)
2076 dup2( fd, 0 );
2077 dup2( fd, 1 );
2078 close( fd );
2081 else
2083 if (stdin_fd != -1) dup2( stdin_fd, 0 );
2084 if (stdout_fd != -1) dup2( stdout_fd, 1 );
2087 if (stdin_fd != -1) close( stdin_fd );
2088 if (stdout_fd != -1) close( stdout_fd );
2090 /* Reset signals that we previously set to SIG_IGN */
2091 signal( SIGPIPE, SIG_DFL );
2093 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
2094 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
2095 (ULONG)(res_start >> 32), (ULONG)res_start, (ULONG)(res_end >> 32), (ULONG)res_end );
2097 putenv( preloader_reserve );
2098 putenv( socket_env );
2099 if (winedebug) putenv( winedebug );
2100 if (wineloader) putenv( wineloader );
2101 if (unixdir) chdir(unixdir);
2103 if (argv) wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
2104 _exit(1);
2107 _exit(pid == -1);
2110 if (pid != -1)
2112 /* reap child */
2113 pid_t wret;
2114 do {
2115 wret = waitpid(pid, NULL, 0);
2116 } while (wret < 0 && errno == EINTR);
2119 if (stdin_fd != -1) close( stdin_fd );
2120 if (stdout_fd != -1) close( stdout_fd );
2121 HeapFree( GetProcessHeap(), 0, wineloader );
2122 HeapFree( GetProcessHeap(), 0, argv );
2123 return pid;
2126 /***********************************************************************
2127 * exec_loader
2129 static NTSTATUS exec_loader( const RTL_USER_PROCESS_PARAMETERS *params, int socketfd,
2130 const pe_image_info_t *pe_info )
2132 char *wineloader = NULL;
2133 const char *loader = NULL;
2134 char **argv;
2135 char preloader_reserve[64], socket_env[64];
2136 ULONGLONG res_start = pe_info->base;
2137 ULONGLONG res_end = pe_info->base + pe_info->map_size;
2139 if (!(argv = build_argv( &params->CommandLine, 1 ))) return STATUS_NO_MEMORY;
2141 if (!is_win64 ^ !is_64bit_arch( pe_info->cpu ))
2142 loader = get_alternate_loader( &wineloader );
2144 /* Reset signals that we previously set to SIG_IGN */
2145 signal( SIGPIPE, SIG_DFL );
2147 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
2148 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
2149 (ULONG)(res_start >> 32), (ULONG)res_start, (ULONG)(res_end >> 32), (ULONG)res_end );
2151 putenv( preloader_reserve );
2152 putenv( socket_env );
2153 if (wineloader) putenv( wineloader );
2157 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
2159 #ifdef __APPLE__
2160 while (errno == ENOTSUP && terminate_main_thread());
2161 #else
2162 while (0);
2163 #endif
2165 HeapFree( GetProcessHeap(), 0, wineloader );
2166 HeapFree( GetProcessHeap(), 0, argv );
2167 return STATUS_INVALID_IMAGE_FORMAT;
2170 /* creates a struct security_descriptor and contained information in one contiguous piece of memory */
2171 static NTSTATUS alloc_object_attributes( const SECURITY_ATTRIBUTES *attr, struct object_attributes **ret,
2172 data_size_t *ret_len )
2174 unsigned int len = sizeof(**ret);
2175 PSID owner = NULL, group = NULL;
2176 ACL *dacl, *sacl;
2177 BOOLEAN dacl_present, sacl_present, defaulted;
2178 PSECURITY_DESCRIPTOR sd = NULL;
2179 NTSTATUS status;
2181 *ret = NULL;
2182 *ret_len = 0;
2184 if (attr) sd = attr->lpSecurityDescriptor;
2186 if (sd)
2188 len += sizeof(struct security_descriptor);
2190 if ((status = RtlGetOwnerSecurityDescriptor( sd, &owner, &defaulted ))) return status;
2191 if ((status = RtlGetGroupSecurityDescriptor( sd, &group, &defaulted ))) return status;
2192 if ((status = RtlGetSaclSecurityDescriptor( sd, &sacl_present, &sacl, &defaulted ))) return status;
2193 if ((status = RtlGetDaclSecurityDescriptor( sd, &dacl_present, &dacl, &defaulted ))) return status;
2194 if (owner) len += RtlLengthSid( owner );
2195 if (group) len += RtlLengthSid( group );
2196 if (sacl_present && sacl) len += sacl->AclSize;
2197 if (dacl_present && dacl) len += dacl->AclSize;
2200 len = (len + 3) & ~3; /* DWORD-align the entire structure */
2202 *ret = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, len );
2203 if (!*ret) return STATUS_NO_MEMORY;
2205 (*ret)->attributes = (attr && attr->bInheritHandle) ? OBJ_INHERIT : 0;
2207 if (sd)
2209 struct security_descriptor *descr = (struct security_descriptor *)(*ret + 1);
2210 unsigned char *ptr = (unsigned char *)(descr + 1);
2212 descr->control = ((SECURITY_DESCRIPTOR *)sd)->Control & ~SE_SELF_RELATIVE;
2213 if (owner) descr->owner_len = RtlLengthSid( owner );
2214 if (group) descr->group_len = RtlLengthSid( group );
2215 if (sacl_present && sacl) descr->sacl_len = sacl->AclSize;
2216 if (dacl_present && dacl) descr->dacl_len = dacl->AclSize;
2218 memcpy( ptr, owner, descr->owner_len );
2219 ptr += descr->owner_len;
2220 memcpy( ptr, group, descr->group_len );
2221 ptr += descr->group_len;
2222 memcpy( ptr, sacl, descr->sacl_len );
2223 ptr += descr->sacl_len;
2224 memcpy( ptr, dacl, descr->dacl_len );
2225 (*ret)->sd_len = (sizeof(*descr) + descr->owner_len + descr->group_len + descr->sacl_len +
2226 descr->dacl_len + sizeof(WCHAR) - 1) & ~(sizeof(WCHAR) - 1);
2228 *ret_len = len;
2229 return STATUS_SUCCESS;
2232 /***********************************************************************
2233 * replace_process
2235 * Replace the existing process by exec'ing a new one.
2237 static BOOL replace_process( HANDLE handle, const RTL_USER_PROCESS_PARAMETERS *params,
2238 const pe_image_info_t *pe_info )
2240 NTSTATUS status;
2241 int socketfd[2];
2243 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2245 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2246 return FALSE;
2248 #ifdef SO_PASSCRED
2249 else
2251 int enable = 1;
2252 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2254 #endif
2255 wine_server_send_fd( socketfd[1] );
2256 close( socketfd[1] );
2258 SERVER_START_REQ( exec_process )
2260 req->socket_fd = socketfd[1];
2261 req->exe_file = wine_server_obj_handle( handle );
2262 req->cpu = pe_info->cpu;
2263 status = wine_server_call( req );
2265 SERVER_END_REQ;
2267 switch (status)
2269 case STATUS_INVALID_IMAGE_WIN_64:
2270 ERR( "64-bit application %s not supported in 32-bit prefix\n",
2271 debugstr_w( params->ImagePathName.Buffer ));
2272 break;
2273 case STATUS_INVALID_IMAGE_FORMAT:
2274 ERR( "%s not supported on this installation (%s binary)\n",
2275 debugstr_w( params->ImagePathName.Buffer ), cpu_names[pe_info->cpu] );
2276 break;
2277 case STATUS_SUCCESS:
2278 status = exec_loader( params, socketfd[0], pe_info );
2279 break;
2281 close( socketfd[0] );
2282 SetLastError( RtlNtStatusToDosError( status ));
2283 return FALSE;
2287 /***********************************************************************
2288 * create_process
2290 * Create a new process. If hFile is a valid handle we have an exe
2291 * file, otherwise it is a Winelib app.
2293 static BOOL create_process( HANDLE hFile, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2294 BOOL inherit, DWORD flags, const RTL_USER_PROCESS_PARAMETERS *params,
2295 LPPROCESS_INFORMATION info, LPCSTR unixdir, const pe_image_info_t *pe_info )
2297 NTSTATUS status;
2298 BOOL success = FALSE;
2299 HANDLE process_info, process_handle = 0;
2300 struct object_attributes *objattr;
2301 data_size_t attr_len;
2302 WCHAR *env_end;
2303 char *winedebug = NULL;
2304 startup_info_t *startup_info;
2305 DWORD startup_info_size;
2306 int socketfd[2];
2307 pid_t pid;
2308 int err;
2310 /* create the socket for the new process */
2312 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2314 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2315 return FALSE;
2317 #ifdef SO_PASSCRED
2318 else
2320 int enable = 1;
2321 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2323 #endif
2325 if (!(startup_info = create_startup_info( params, &startup_info_size )))
2327 close( socketfd[0] );
2328 close( socketfd[1] );
2329 return FALSE;
2331 env_end = params->Environment;
2332 while (*env_end)
2334 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2335 if (!winedebug && !strncmpW( env_end, WINEDEBUG, ARRAY_SIZE( WINEDEBUG ) - 1 ))
2337 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2338 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2339 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2341 env_end += strlenW(env_end) + 1;
2343 env_end++;
2345 wine_server_send_fd( socketfd[1] );
2346 close( socketfd[1] );
2348 /* create the process on the server side */
2350 alloc_object_attributes( psa, &objattr, &attr_len );
2351 SERVER_START_REQ( new_process )
2353 req->inherit_all = inherit;
2354 req->create_flags = flags;
2355 req->socket_fd = socketfd[1];
2356 req->exe_file = wine_server_obj_handle( hFile );
2357 req->access = PROCESS_ALL_ACCESS;
2358 req->cpu = pe_info->cpu;
2359 req->info_size = startup_info_size;
2360 wine_server_add_data( req, objattr, attr_len );
2361 wine_server_add_data( req, startup_info, startup_info_size );
2362 wine_server_add_data( req, params->Environment, (env_end - params->Environment) * sizeof(WCHAR) );
2363 if (!(status = wine_server_call( req )))
2365 info->dwProcessId = (DWORD)reply->pid;
2366 process_handle = wine_server_ptr_handle( reply->handle );
2368 process_info = wine_server_ptr_handle( reply->info );
2370 SERVER_END_REQ;
2371 HeapFree( GetProcessHeap(), 0, objattr );
2373 if (!status)
2375 alloc_object_attributes( tsa, &objattr, &attr_len );
2376 SERVER_START_REQ( new_thread )
2378 req->process = wine_server_obj_handle( process_handle );
2379 req->access = THREAD_ALL_ACCESS;
2380 req->suspend = !!(flags & CREATE_SUSPENDED);
2381 req->request_fd = -1;
2382 wine_server_add_data( req, objattr, attr_len );
2383 if (!(status = wine_server_call( req )))
2385 info->hProcess = process_handle;
2386 info->hThread = wine_server_ptr_handle( reply->handle );
2387 info->dwThreadId = reply->tid;
2390 SERVER_END_REQ;
2391 HeapFree( GetProcessHeap(), 0, objattr );
2394 if (status)
2396 switch (status)
2398 case STATUS_INVALID_IMAGE_WIN_64:
2399 ERR( "64-bit application %s not supported in 32-bit prefix\n",
2400 debugstr_w( params->ImagePathName.Buffer ));
2401 break;
2402 case STATUS_INVALID_IMAGE_FORMAT:
2403 ERR( "%s not supported on this installation (%s binary)\n",
2404 debugstr_w( params->ImagePathName.Buffer ), cpu_names[pe_info->cpu] );
2405 break;
2407 close( socketfd[0] );
2408 CloseHandle( process_handle );
2409 HeapFree( GetProcessHeap(), 0, startup_info );
2410 HeapFree( GetProcessHeap(), 0, winedebug );
2411 SetLastError( RtlNtStatusToDosError( status ));
2412 return FALSE;
2415 HeapFree( GetProcessHeap(), 0, startup_info );
2417 /* create the child process */
2419 pid = spawn_loader( params, socketfd[0], unixdir, winedebug, pe_info );
2421 close( socketfd[0] );
2422 HeapFree( GetProcessHeap(), 0, winedebug );
2423 if (pid == -1)
2425 FILE_SetDosError();
2426 goto error;
2429 /* wait for the new process info to be ready */
2431 WaitForSingleObject( process_info, INFINITE );
2432 SERVER_START_REQ( get_new_process_info )
2434 req->info = wine_server_obj_handle( process_info );
2435 wine_server_call( req );
2436 success = reply->success;
2437 err = reply->exit_code;
2439 SERVER_END_REQ;
2441 if (!success)
2443 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2444 goto error;
2446 CloseHandle( process_info );
2447 return success;
2449 error:
2450 CloseHandle( process_info );
2451 CloseHandle( info->hProcess );
2452 CloseHandle( info->hThread );
2453 info->hProcess = info->hThread = 0;
2454 info->dwProcessId = info->dwThreadId = 0;
2455 return FALSE;
2459 /***********************************************************************
2460 * get_vdm_params
2462 * Build the parameters needed to launch a new VDM process.
2464 static RTL_USER_PROCESS_PARAMETERS *get_vdm_params( const RTL_USER_PROCESS_PARAMETERS *params,
2465 pe_image_info_t *pe_info )
2467 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2469 WCHAR *new_cmd_line;
2470 RTL_USER_PROCESS_PARAMETERS *new_params;
2471 UNICODE_STRING imageW, cmdlineW;
2473 new_cmd_line = HeapAlloc(GetProcessHeap(), 0,
2474 (strlenW(params->ImagePathName.Buffer) +
2475 strlenW(params->CommandLine.Buffer) +
2476 strlenW(winevdm) + 16) * sizeof(WCHAR));
2477 if (!new_cmd_line)
2479 SetLastError( ERROR_OUTOFMEMORY );
2480 return NULL;
2482 sprintfW( new_cmd_line, argsW, winevdm, params->ImagePathName.Buffer, params->CommandLine.Buffer );
2483 RtlInitUnicodeString( &imageW, winevdm );
2484 RtlInitUnicodeString( &cmdlineW, new_cmd_line );
2485 if (RtlCreateProcessParametersEx( &new_params, &imageW, &params->DllPath,
2486 &params->CurrentDirectory.DosPath, &cmdlineW,
2487 params->Environment, &params->WindowTitle, &params->Desktop,
2488 &params->ShellInfo, &params->RuntimeInfo,
2489 PROCESS_PARAMS_FLAG_NORMALIZED ))
2491 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2492 SetLastError( ERROR_OUTOFMEMORY );
2493 return FALSE;
2495 new_params->hStdInput = params->hStdInput;
2496 new_params->hStdOutput = params->hStdOutput;
2497 new_params->hStdError = params->hStdError;
2498 new_params->dwX = params->dwX;
2499 new_params->dwY = params->dwY;
2500 new_params->dwXSize = params->dwXSize;
2501 new_params->dwYSize = params->dwYSize;
2502 new_params->dwXCountChars = params->dwXCountChars;
2503 new_params->dwYCountChars = params->dwYCountChars;
2504 new_params->dwFillAttribute = params->dwFillAttribute;
2505 new_params->dwFlags = params->dwFlags;
2506 new_params->wShowWindow = params->wShowWindow;
2508 memset( pe_info, 0, sizeof(*pe_info) );
2509 pe_info->cpu = CPU_x86;
2510 return new_params;
2514 /***********************************************************************
2515 * create_vdm_process
2517 * Create a new VDM process for a 16-bit or DOS application.
2519 static BOOL create_vdm_process( LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2520 BOOL inherit, DWORD flags, const RTL_USER_PROCESS_PARAMETERS *params,
2521 LPPROCESS_INFORMATION info, LPCSTR unixdir )
2523 BOOL ret;
2524 pe_image_info_t pe_info;
2525 RTL_USER_PROCESS_PARAMETERS *new_params;
2527 if (!(new_params = get_vdm_params( params, &pe_info ))) return FALSE;
2529 ret = create_process( 0, psa, tsa, inherit, flags, new_params, info, unixdir, &pe_info );
2530 RtlDestroyProcessParameters( new_params );
2531 return ret;
2535 /***********************************************************************
2536 * create_cmd_process
2538 * Create a new cmd shell process for a .BAT file.
2540 static BOOL create_cmd_process( LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2541 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2542 const RTL_USER_PROCESS_PARAMETERS *params,
2543 LPPROCESS_INFORMATION info )
2546 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2547 static const WCHAR cmdW[] = {'\\','c','m','d','.','e','x','e',0};
2548 static const WCHAR slashscW[] = {' ','/','s','/','c',' ',0};
2549 static const WCHAR quotW[] = {'"',0};
2550 WCHAR comspec[MAX_PATH];
2551 WCHAR *newcmdline, *cur_dir = NULL;
2552 BOOL ret;
2554 if (!GetEnvironmentVariableW( comspecW, comspec, ARRAY_SIZE( comspec )))
2556 GetSystemDirectoryW( comspec, (sizeof(comspec) - sizeof(cmdW))/sizeof(WCHAR) );
2557 strcatW( comspec, cmdW );
2559 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2560 (strlenW(comspec) + 7 +
2561 strlenW(params->CommandLine.Buffer) + 2) * sizeof(WCHAR))))
2562 return FALSE;
2564 strcpyW( newcmdline, comspec );
2565 strcatW( newcmdline, slashscW );
2566 strcatW( newcmdline, quotW );
2567 strcatW( newcmdline, params->CommandLine.Buffer );
2568 strcatW( newcmdline, quotW );
2569 if (params->CurrentDirectory.DosPath.Length) cur_dir = params->CurrentDirectory.DosPath.Buffer;
2570 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2571 flags | CREATE_UNICODE_ENVIRONMENT, params->Environment, cur_dir,
2572 startup, info );
2573 HeapFree( GetProcessHeap(), 0, newcmdline );
2574 return ret;
2578 /*************************************************************************
2579 * get_file_name
2581 * Helper for CreateProcess: retrieve the file name to load from the
2582 * app name and command line. Store the file name in buffer, and
2583 * return a possibly modified command line.
2584 * Also returns a handle to the opened file if it's a Windows binary.
2586 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2587 int buflen, HANDLE *handle, BOOL *is_64bit )
2589 static const WCHAR quotesW[] = {'"','%','s','"',0};
2591 WCHAR *name, *pos, *first_space, *ret = NULL;
2592 const WCHAR *p;
2594 /* if we have an app name, everything is easy */
2596 if (appname)
2598 /* use the unmodified app name as file name */
2599 lstrcpynW( buffer, appname, buflen );
2600 *handle = open_exe_file( buffer, is_64bit );
2601 if (!(ret = cmdline) || !cmdline[0])
2603 /* no command-line, create one */
2604 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2605 sprintfW( ret, quotesW, appname );
2607 return ret;
2610 /* first check for a quoted file name */
2612 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2614 int len = p - cmdline - 1;
2615 /* extract the quoted portion as file name */
2616 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2617 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2618 name[len] = 0;
2620 if (!find_exe_file( name, buffer, buflen, handle )) goto done;
2621 ret = cmdline; /* no change necessary */
2622 goto done;
2625 /* now try the command-line word by word */
2627 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2628 return NULL;
2629 pos = name;
2630 p = cmdline;
2631 first_space = NULL;
2633 for (;;)
2635 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2636 *pos = 0;
2637 if (find_exe_file( name, buffer, buflen, handle ))
2639 ret = cmdline;
2640 break;
2642 if (!first_space) first_space = pos;
2643 if (!(*pos++ = *p++)) break;
2646 if (!ret)
2648 SetLastError( ERROR_FILE_NOT_FOUND );
2650 else if (first_space) /* build a new command-line with quotes */
2652 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2653 goto done;
2654 sprintfW( ret, quotesW, name );
2655 strcatW( ret, p );
2658 done:
2659 HeapFree( GetProcessHeap(), 0, name );
2660 return ret;
2663 /**********************************************************************
2664 * CreateProcessInternalW (KERNEL32.@)
2666 BOOL WINAPI CreateProcessInternalW( HANDLE token, LPCWSTR app_name, LPWSTR cmd_line,
2667 LPSECURITY_ATTRIBUTES process_attr, LPSECURITY_ATTRIBUTES thread_attr,
2668 BOOL inherit, DWORD flags, LPVOID env, LPCWSTR cur_dir,
2669 LPSTARTUPINFOW startup_info, LPPROCESS_INFORMATION info,
2670 HANDLE *new_token )
2672 BOOL retv = FALSE;
2673 HANDLE hFile = 0;
2674 char *unixdir = NULL;
2675 WCHAR name[MAX_PATH];
2676 WCHAR *tidy_cmdline, *p;
2677 RTL_USER_PROCESS_PARAMETERS *params = NULL;
2678 pe_image_info_t pe_info;
2679 enum binary_type type;
2680 BOOL is_64bit;
2682 /* Process the AppName and/or CmdLine to get module name and path */
2684 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2686 if (token) FIXME("Creating a process with a token is not yet implemented\n");
2687 if (new_token) FIXME("No support for returning created process token\n");
2689 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, ARRAY_SIZE( name ), &hFile, &is_64bit )))
2690 return FALSE;
2691 if (hFile == INVALID_HANDLE_VALUE) goto done;
2693 /* Warn if unsupported features are used */
2695 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2696 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2697 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2698 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2699 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2701 if (cur_dir)
2703 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2705 SetLastError(ERROR_DIRECTORY);
2706 goto done;
2709 else
2711 WCHAR buf[MAX_PATH];
2712 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2715 info->hThread = info->hProcess = 0;
2716 info->dwProcessId = info->dwThreadId = 0;
2718 if (!(params = create_process_params( name, tidy_cmdline, cur_dir, env, flags, startup_info )))
2720 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2721 goto done;
2724 if (!hFile)
2726 memset( &pe_info, 0, sizeof(pe_info) );
2727 type = BINARY_UNIX_LIB;
2728 /* assume current arch */
2729 #if defined(__i386__) || defined(__x86_64__)
2730 pe_info.cpu = is_64bit ? CPU_x86_64 : CPU_x86;
2731 #elif defined(__powerpc__)
2732 pe_info.cpu = CPU_POWERPC;
2733 #elif defined(__arm__)
2734 pe_info.cpu = CPU_ARM;
2735 #elif defined(__aarch64__)
2736 pe_info.cpu = CPU_ARM64;
2737 #endif
2739 else type = get_binary_info( hFile, &pe_info );
2741 switch (type)
2743 case BINARY_PE:
2744 if (pe_info.image_charact & IMAGE_FILE_DLL)
2746 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2747 SetLastError( ERROR_BAD_EXE_FORMAT );
2748 break;
2750 TRACE( "starting %s as Win%d binary (%s-%s, %s)\n",
2751 debugstr_w(name), is_64bit_arch(pe_info.cpu) ? 64 : 32,
2752 wine_dbgstr_longlong(pe_info.base), wine_dbgstr_longlong(pe_info.base + pe_info.map_size),
2753 cpu_names[pe_info.cpu] );
2754 retv = create_process( hFile, process_attr, thread_attr,
2755 inherit, flags, params, info, unixdir, &pe_info );
2756 break;
2757 case BINARY_WIN16:
2758 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2759 retv = create_vdm_process( process_attr, thread_attr, inherit, flags, params, info, unixdir );
2760 break;
2761 case BINARY_UNIX_LIB:
2762 TRACE( "starting %s as %d-bit Winelib app\n",
2763 debugstr_w(name), is_64bit_arch(pe_info.cpu) ? 64 : 32 );
2764 retv = create_process( hFile, process_attr, thread_attr,
2765 inherit, flags, params, info, unixdir, &pe_info );
2766 break;
2767 case BINARY_UNKNOWN:
2768 /* check for .com or .bat extension */
2769 if ((p = strrchrW( name, '.' )))
2771 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2773 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2774 retv = create_vdm_process( process_attr, thread_attr,
2775 inherit, flags, params, info, unixdir );
2776 break;
2778 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2780 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2781 retv = create_cmd_process( process_attr, thread_attr,
2782 inherit, flags, startup_info, params, info );
2783 break;
2786 /* fall through */
2787 case BINARY_UNIX_EXE:
2788 /* unknown file, try as unix executable */
2789 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2790 retv = (fork_and_exec( params, unixdir ) != -1);
2791 break;
2793 if (hFile) CloseHandle( hFile );
2795 done:
2796 RtlDestroyProcessParameters( params );
2797 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2798 HeapFree( GetProcessHeap(), 0, unixdir );
2799 if (retv)
2800 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2801 return retv;
2805 /**********************************************************************
2806 * CreateProcessInternalA (KERNEL32.@)
2808 BOOL WINAPI CreateProcessInternalA( HANDLE token, LPCSTR app_name, LPSTR cmd_line,
2809 LPSECURITY_ATTRIBUTES process_attr, LPSECURITY_ATTRIBUTES thread_attr,
2810 BOOL inherit, DWORD flags, LPVOID env, LPCSTR cur_dir,
2811 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info,
2812 HANDLE *new_token )
2814 BOOL ret = FALSE;
2815 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2816 UNICODE_STRING desktopW, titleW;
2817 STARTUPINFOW infoW;
2819 desktopW.Buffer = NULL;
2820 titleW.Buffer = NULL;
2821 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2822 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2823 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2825 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2826 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2828 memcpy( &infoW, startup_info, sizeof(infoW) );
2829 infoW.lpDesktop = desktopW.Buffer;
2830 infoW.lpTitle = titleW.Buffer;
2832 if (startup_info->lpReserved)
2833 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2834 debugstr_a(startup_info->lpReserved));
2836 ret = CreateProcessInternalW( token, app_nameW, cmd_lineW, process_attr, thread_attr,
2837 inherit, flags, env, cur_dirW, &infoW, info, new_token );
2838 done:
2839 HeapFree( GetProcessHeap(), 0, app_nameW );
2840 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2841 HeapFree( GetProcessHeap(), 0, cur_dirW );
2842 RtlFreeUnicodeString( &desktopW );
2843 RtlFreeUnicodeString( &titleW );
2844 return ret;
2848 /**********************************************************************
2849 * CreateProcessA (KERNEL32.@)
2851 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2852 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2853 DWORD flags, LPVOID env, LPCSTR cur_dir,
2854 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2856 return CreateProcessInternalA( NULL, app_name, cmd_line, process_attr, thread_attr,
2857 inherit, flags, env, cur_dir, startup_info, info, NULL );
2861 /**********************************************************************
2862 * CreateProcessW (KERNEL32.@)
2864 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2865 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2866 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2867 LPPROCESS_INFORMATION info )
2869 return CreateProcessInternalW( NULL, app_name, cmd_line, process_attr, thread_attr,
2870 inherit, flags, env, cur_dir, startup_info, info, NULL );
2874 /**********************************************************************
2875 * CreateProcessAsUserA (KERNEL32.@)
2877 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessAsUserA( HANDLE token, LPCSTR app_name, LPSTR cmd_line,
2878 LPSECURITY_ATTRIBUTES process_attr,
2879 LPSECURITY_ATTRIBUTES thread_attr,
2880 BOOL inherit, DWORD flags, LPVOID env, LPCSTR cur_dir,
2881 LPSTARTUPINFOA startup_info,
2882 LPPROCESS_INFORMATION info )
2884 return CreateProcessInternalA( token, app_name, cmd_line, process_attr, thread_attr,
2885 inherit, flags, env, cur_dir, startup_info, info, NULL );
2889 /**********************************************************************
2890 * CreateProcessAsUserW (KERNEL32.@)
2892 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessAsUserW( HANDLE token, LPCWSTR app_name, LPWSTR cmd_line,
2893 LPSECURITY_ATTRIBUTES process_attr,
2894 LPSECURITY_ATTRIBUTES thread_attr,
2895 BOOL inherit, DWORD flags, LPVOID env, LPCWSTR cur_dir,
2896 LPSTARTUPINFOW startup_info,
2897 LPPROCESS_INFORMATION info )
2899 return CreateProcessInternalW( token, app_name, cmd_line, process_attr, thread_attr,
2900 inherit, flags, env, cur_dir, startup_info, info, NULL );
2904 /**********************************************************************
2905 * exec_process
2907 static void exec_process( LPCWSTR name )
2909 HANDLE hFile;
2910 WCHAR *p;
2911 STARTUPINFOW startup_info = { sizeof(startup_info) };
2912 RTL_USER_PROCESS_PARAMETERS *params, *new_params;
2913 pe_image_info_t pe_info;
2914 BOOL is_64bit;
2916 hFile = open_exe_file( name, &is_64bit );
2917 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2919 if (!(params = create_process_params( name, GetCommandLineW(), NULL, NULL, 0, &startup_info )))
2920 return;
2922 /* Determine executable type */
2924 switch (get_binary_info( hFile, &pe_info ))
2926 case BINARY_PE:
2927 if (pe_info.image_charact & IMAGE_FILE_DLL) break;
2928 TRACE( "starting %s as Win%d binary (%s-%s, %s)\n",
2929 debugstr_w(name), is_64bit_arch(pe_info.cpu) ? 64 : 32,
2930 wine_dbgstr_longlong(pe_info.base), wine_dbgstr_longlong(pe_info.base + pe_info.map_size),
2931 cpu_names[pe_info.cpu] );
2932 replace_process( hFile, params, &pe_info );
2933 break;
2934 case BINARY_UNIX_LIB:
2935 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2936 replace_process( hFile, params, &pe_info );
2937 break;
2938 case BINARY_UNKNOWN:
2939 /* check for .com or .pif extension */
2940 if (!(p = strrchrW( name, '.' ))) break;
2941 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2942 /* fall through */
2943 case BINARY_WIN16:
2944 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2945 if (!(new_params = get_vdm_params( params, &pe_info ))) break;
2946 replace_process( 0, new_params, &pe_info );
2947 RtlDestroyProcessParameters( new_params );
2948 break;
2949 default:
2950 break;
2952 CloseHandle( hFile );
2953 RtlDestroyProcessParameters( params );
2957 /***********************************************************************
2958 * wait_input_idle
2960 * Wrapper to call WaitForInputIdle USER function
2962 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2964 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2966 HMODULE mod = GetModuleHandleA( "user32.dll" );
2967 if (mod)
2969 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2970 if (ptr) return ptr( process, timeout );
2972 return 0;
2976 /***********************************************************************
2977 * WinExec (KERNEL32.@)
2979 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2981 PROCESS_INFORMATION info;
2982 STARTUPINFOA startup;
2983 char *cmdline;
2984 UINT ret;
2986 memset( &startup, 0, sizeof(startup) );
2987 startup.cb = sizeof(startup);
2988 startup.dwFlags = STARTF_USESHOWWINDOW;
2989 startup.wShowWindow = nCmdShow;
2991 /* cmdline needs to be writable for CreateProcess */
2992 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2993 strcpy( cmdline, lpCmdLine );
2995 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2996 0, NULL, NULL, &startup, &info ))
2998 /* Give 30 seconds to the app to come up */
2999 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
3000 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
3001 ret = 33;
3002 /* Close off the handles */
3003 CloseHandle( info.hThread );
3004 CloseHandle( info.hProcess );
3006 else if ((ret = GetLastError()) >= 32)
3008 FIXME("Strange error set by CreateProcess: %d\n", ret );
3009 ret = 11;
3011 HeapFree( GetProcessHeap(), 0, cmdline );
3012 return ret;
3016 /**********************************************************************
3017 * LoadModule (KERNEL32.@)
3019 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
3021 LOADPARMS32 *params = paramBlock;
3022 PROCESS_INFORMATION info;
3023 STARTUPINFOA startup;
3024 DWORD ret;
3025 LPSTR cmdline, p;
3026 char filename[MAX_PATH];
3027 BYTE len;
3029 if (!name) return ERROR_FILE_NOT_FOUND;
3031 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
3032 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
3033 return GetLastError();
3035 len = (BYTE)params->lpCmdLine[0];
3036 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
3037 return ERROR_NOT_ENOUGH_MEMORY;
3039 strcpy( cmdline, filename );
3040 p = cmdline + strlen(cmdline);
3041 *p++ = ' ';
3042 memcpy( p, params->lpCmdLine + 1, len );
3043 p[len] = 0;
3045 memset( &startup, 0, sizeof(startup) );
3046 startup.cb = sizeof(startup);
3047 if (params->lpCmdShow)
3049 startup.dwFlags = STARTF_USESHOWWINDOW;
3050 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
3053 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
3054 params->lpEnvAddress, NULL, &startup, &info ))
3056 /* Give 30 seconds to the app to come up */
3057 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
3058 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
3059 ret = 33;
3060 /* Close off the handles */
3061 CloseHandle( info.hThread );
3062 CloseHandle( info.hProcess );
3064 else if ((ret = GetLastError()) >= 32)
3066 FIXME("Strange error set by CreateProcess: %u\n", ret );
3067 ret = 11;
3070 HeapFree( GetProcessHeap(), 0, cmdline );
3071 return ret;
3075 /******************************************************************************
3076 * TerminateProcess (KERNEL32.@)
3078 * Terminates a process.
3080 * PARAMS
3081 * handle [I] Process to terminate.
3082 * exit_code [I] Exit code.
3084 * RETURNS
3085 * Success: TRUE.
3086 * Failure: FALSE, check GetLastError().
3088 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
3090 NTSTATUS status;
3092 if (!handle)
3094 SetLastError( ERROR_INVALID_HANDLE );
3095 return FALSE;
3098 status = NtTerminateProcess( handle, exit_code );
3099 if (status) SetLastError( RtlNtStatusToDosError(status) );
3100 return !status;
3103 /***********************************************************************
3104 * ExitProcess (KERNEL32.@)
3106 * Exits the current process.
3108 * PARAMS
3109 * status [I] Status code to exit with.
3111 * RETURNS
3112 * Nothing.
3114 #ifdef __i386__
3115 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
3116 "pushl %ebp\n\t"
3117 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
3118 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
3119 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
3120 "pushl 8(%ebp)\n\t"
3121 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
3122 "leave\n\t"
3123 "ret $4" )
3124 #else
3126 void WINAPI ExitProcess( DWORD status )
3128 RtlExitUserProcess( status );
3131 #endif
3133 /***********************************************************************
3134 * GetExitCodeProcess [KERNEL32.@]
3136 * Gets termination status of specified process.
3138 * PARAMS
3139 * hProcess [in] Handle to the process.
3140 * lpExitCode [out] Address to receive termination status.
3142 * RETURNS
3143 * Success: TRUE
3144 * Failure: FALSE
3146 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
3148 NTSTATUS status;
3149 PROCESS_BASIC_INFORMATION pbi;
3151 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3152 sizeof(pbi), NULL);
3153 if (status == STATUS_SUCCESS)
3155 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
3156 return TRUE;
3158 SetLastError( RtlNtStatusToDosError(status) );
3159 return FALSE;
3163 /***********************************************************************
3164 * SetErrorMode (KERNEL32.@)
3166 UINT WINAPI SetErrorMode( UINT mode )
3168 UINT old;
3170 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
3171 &old, sizeof(old), NULL );
3172 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
3173 &mode, sizeof(mode) );
3174 return old;
3177 /***********************************************************************
3178 * GetErrorMode (KERNEL32.@)
3180 UINT WINAPI GetErrorMode( void )
3182 UINT mode;
3184 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
3185 &mode, sizeof(mode), NULL );
3186 return mode;
3189 /**********************************************************************
3190 * TlsAlloc [KERNEL32.@]
3192 * Allocates a thread local storage index.
3194 * RETURNS
3195 * Success: TLS index.
3196 * Failure: 0xFFFFFFFF
3198 DWORD WINAPI TlsAlloc( void )
3200 DWORD index;
3201 PEB * const peb = NtCurrentTeb()->Peb;
3203 RtlAcquirePebLock();
3204 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
3205 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
3206 else
3208 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
3209 if (index != ~0U)
3211 if (!NtCurrentTeb()->TlsExpansionSlots &&
3212 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
3213 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
3215 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
3216 index = ~0U;
3217 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3219 else
3221 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
3222 index += TLS_MINIMUM_AVAILABLE;
3225 else SetLastError( ERROR_NO_MORE_ITEMS );
3227 RtlReleasePebLock();
3228 return index;
3232 /**********************************************************************
3233 * TlsFree [KERNEL32.@]
3235 * Releases a thread local storage index, making it available for reuse.
3237 * PARAMS
3238 * index [in] TLS index to free.
3240 * RETURNS
3241 * Success: TRUE
3242 * Failure: FALSE
3244 BOOL WINAPI TlsFree( DWORD index )
3246 BOOL ret;
3248 RtlAcquirePebLock();
3249 if (index >= TLS_MINIMUM_AVAILABLE)
3251 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
3252 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
3254 else
3256 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
3257 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
3259 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
3260 else SetLastError( ERROR_INVALID_PARAMETER );
3261 RtlReleasePebLock();
3262 return ret;
3266 /**********************************************************************
3267 * TlsGetValue [KERNEL32.@]
3269 * Gets value in a thread's TLS slot.
3271 * PARAMS
3272 * index [in] TLS index to retrieve value for.
3274 * RETURNS
3275 * Success: Value stored in calling thread's TLS slot for index.
3276 * Failure: 0 and GetLastError() returns NO_ERROR.
3278 LPVOID WINAPI TlsGetValue( DWORD index )
3280 LPVOID ret;
3282 if (index < TLS_MINIMUM_AVAILABLE)
3284 ret = NtCurrentTeb()->TlsSlots[index];
3286 else
3288 index -= TLS_MINIMUM_AVAILABLE;
3289 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
3291 SetLastError( ERROR_INVALID_PARAMETER );
3292 return NULL;
3294 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
3295 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
3297 SetLastError( ERROR_SUCCESS );
3298 return ret;
3302 /**********************************************************************
3303 * TlsSetValue [KERNEL32.@]
3305 * Stores a value in the thread's TLS slot.
3307 * PARAMS
3308 * index [in] TLS index to set value for.
3309 * value [in] Value to be stored.
3311 * RETURNS
3312 * Success: TRUE
3313 * Failure: FALSE
3315 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
3317 if (index < TLS_MINIMUM_AVAILABLE)
3319 NtCurrentTeb()->TlsSlots[index] = value;
3321 else
3323 index -= TLS_MINIMUM_AVAILABLE;
3324 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
3326 SetLastError( ERROR_INVALID_PARAMETER );
3327 return FALSE;
3329 if (!NtCurrentTeb()->TlsExpansionSlots &&
3330 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
3331 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
3333 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3334 return FALSE;
3336 NtCurrentTeb()->TlsExpansionSlots[index] = value;
3338 return TRUE;
3342 /***********************************************************************
3343 * GetProcessFlags (KERNEL32.@)
3345 DWORD WINAPI GetProcessFlags( DWORD processid )
3347 IMAGE_NT_HEADERS *nt;
3348 DWORD flags = 0;
3350 if (processid && processid != GetCurrentProcessId()) return 0;
3352 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3354 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
3355 flags |= PDB32_CONSOLE_PROC;
3357 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
3358 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
3359 return flags;
3363 /*********************************************************************
3364 * OpenProcess (KERNEL32.@)
3366 * Opens a handle to a process.
3368 * PARAMS
3369 * access [I] Desired access rights assigned to the returned handle.
3370 * inherit [I] Determines whether or not child processes will inherit the handle.
3371 * id [I] Process identifier of the process to get a handle to.
3373 * RETURNS
3374 * Success: Valid handle to the specified process.
3375 * Failure: NULL, check GetLastError().
3377 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
3379 NTSTATUS status;
3380 HANDLE handle;
3381 OBJECT_ATTRIBUTES attr;
3382 CLIENT_ID cid;
3384 cid.UniqueProcess = ULongToHandle(id);
3385 cid.UniqueThread = 0; /* FIXME ? */
3387 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3388 attr.RootDirectory = NULL;
3389 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3390 attr.SecurityDescriptor = NULL;
3391 attr.SecurityQualityOfService = NULL;
3392 attr.ObjectName = NULL;
3394 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3396 status = NtOpenProcess(&handle, access, &attr, &cid);
3397 if (status != STATUS_SUCCESS)
3399 SetLastError( RtlNtStatusToDosError(status) );
3400 return NULL;
3402 return handle;
3406 /*********************************************************************
3407 * GetProcessId (KERNEL32.@)
3409 * Gets the a unique identifier of a process.
3411 * PARAMS
3412 * hProcess [I] Handle to the process.
3414 * RETURNS
3415 * Success: TRUE.
3416 * Failure: FALSE, check GetLastError().
3418 * NOTES
3420 * The identifier is unique only on the machine and only until the process
3421 * exits (including system shutdown).
3423 DWORD WINAPI GetProcessId( HANDLE hProcess )
3425 NTSTATUS status;
3426 PROCESS_BASIC_INFORMATION pbi;
3428 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3429 sizeof(pbi), NULL);
3430 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3431 SetLastError( RtlNtStatusToDosError(status) );
3432 return 0;
3436 /*********************************************************************
3437 * CloseHandle (KERNEL32.@)
3439 * Closes a handle.
3441 * PARAMS
3442 * handle [I] Handle to close.
3444 * RETURNS
3445 * Success: TRUE.
3446 * Failure: FALSE, check GetLastError().
3448 BOOL WINAPI CloseHandle( HANDLE handle )
3450 NTSTATUS status;
3452 /* stdio handles need special treatment */
3453 if (handle == (HANDLE)STD_INPUT_HANDLE)
3454 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3455 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3456 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3457 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3458 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3460 if (is_console_handle(handle))
3461 return CloseConsoleHandle(handle);
3463 status = NtClose( handle );
3464 if (status) SetLastError( RtlNtStatusToDosError(status) );
3465 return !status;
3469 /*********************************************************************
3470 * GetHandleInformation (KERNEL32.@)
3472 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3474 OBJECT_DATA_INFORMATION info;
3475 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3477 if (status) SetLastError( RtlNtStatusToDosError(status) );
3478 else if (flags)
3480 *flags = 0;
3481 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3482 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3484 return !status;
3488 /*********************************************************************
3489 * SetHandleInformation (KERNEL32.@)
3491 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3493 OBJECT_DATA_INFORMATION info;
3494 NTSTATUS status;
3496 /* if not setting both fields, retrieve current value first */
3497 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3498 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3500 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3502 SetLastError( RtlNtStatusToDosError(status) );
3503 return FALSE;
3506 if (mask & HANDLE_FLAG_INHERIT)
3507 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3508 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3509 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3511 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3512 if (status) SetLastError( RtlNtStatusToDosError(status) );
3513 return !status;
3517 /*********************************************************************
3518 * DuplicateHandle (KERNEL32.@)
3520 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3521 HANDLE dest_process, HANDLE *dest,
3522 DWORD access, BOOL inherit, DWORD options )
3524 NTSTATUS status;
3526 if (is_console_handle(source))
3528 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3529 if (source_process != dest_process ||
3530 source_process != GetCurrentProcess())
3532 SetLastError(ERROR_INVALID_PARAMETER);
3533 return FALSE;
3535 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3536 return (*dest != INVALID_HANDLE_VALUE);
3538 status = NtDuplicateObject( source_process, source, dest_process, dest,
3539 access, inherit ? OBJ_INHERIT : 0, options );
3540 if (status) SetLastError( RtlNtStatusToDosError(status) );
3541 return !status;
3545 /***********************************************************************
3546 * ConvertToGlobalHandle (KERNEL32.@)
3548 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3550 HANDLE ret = INVALID_HANDLE_VALUE;
3551 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3552 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3553 return ret;
3557 /***********************************************************************
3558 * SetHandleContext (KERNEL32.@)
3560 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3562 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3563 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3564 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3565 return FALSE;
3569 /***********************************************************************
3570 * GetHandleContext (KERNEL32.@)
3572 DWORD WINAPI GetHandleContext(HANDLE hnd)
3574 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3575 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3576 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3577 return 0;
3581 /***********************************************************************
3582 * CreateSocketHandle (KERNEL32.@)
3584 HANDLE WINAPI CreateSocketHandle(void)
3586 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3587 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3588 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3589 return INVALID_HANDLE_VALUE;
3593 /***********************************************************************
3594 * SetPriorityClass (KERNEL32.@)
3596 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3598 NTSTATUS status;
3599 PROCESS_PRIORITY_CLASS ppc;
3601 ppc.Foreground = FALSE;
3602 switch (priorityclass)
3604 case IDLE_PRIORITY_CLASS:
3605 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3606 case BELOW_NORMAL_PRIORITY_CLASS:
3607 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3608 case NORMAL_PRIORITY_CLASS:
3609 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3610 case ABOVE_NORMAL_PRIORITY_CLASS:
3611 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3612 case HIGH_PRIORITY_CLASS:
3613 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3614 case REALTIME_PRIORITY_CLASS:
3615 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3616 default:
3617 SetLastError(ERROR_INVALID_PARAMETER);
3618 return FALSE;
3621 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3622 &ppc, sizeof(ppc));
3624 if (status != STATUS_SUCCESS)
3626 SetLastError( RtlNtStatusToDosError(status) );
3627 return FALSE;
3629 return TRUE;
3633 /***********************************************************************
3634 * GetPriorityClass (KERNEL32.@)
3636 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3638 NTSTATUS status;
3639 PROCESS_BASIC_INFORMATION pbi;
3641 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3642 sizeof(pbi), NULL);
3643 if (status != STATUS_SUCCESS)
3645 SetLastError( RtlNtStatusToDosError(status) );
3646 return 0;
3648 switch (pbi.BasePriority)
3650 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3651 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3652 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3653 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3654 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3655 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3657 SetLastError( ERROR_INVALID_PARAMETER );
3658 return 0;
3662 /***********************************************************************
3663 * SetProcessAffinityMask (KERNEL32.@)
3665 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3667 NTSTATUS status;
3669 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3670 &affmask, sizeof(DWORD_PTR));
3671 if (status)
3673 SetLastError( RtlNtStatusToDosError(status) );
3674 return FALSE;
3676 return TRUE;
3680 /**********************************************************************
3681 * GetProcessAffinityMask (KERNEL32.@)
3683 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3685 NTSTATUS status = STATUS_SUCCESS;
3687 if (process_mask)
3689 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3690 process_mask, sizeof(*process_mask), NULL )))
3691 SetLastError( RtlNtStatusToDosError(status) );
3693 if (system_mask && status == STATUS_SUCCESS)
3695 SYSTEM_BASIC_INFORMATION info;
3697 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3698 SetLastError( RtlNtStatusToDosError(status) );
3699 else
3700 *system_mask = info.ActiveProcessorsAffinityMask;
3702 return !status;
3706 /***********************************************************************
3707 * SetProcessAffinityUpdateMode (KERNEL32.@)
3709 BOOL WINAPI SetProcessAffinityUpdateMode( HANDLE process, DWORD flags )
3711 FIXME("(%p,0x%08x): stub\n", process, flags);
3712 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3713 return FALSE;
3717 /***********************************************************************
3718 * GetProcessVersion (KERNEL32.@)
3720 DWORD WINAPI GetProcessVersion( DWORD pid )
3722 HANDLE process;
3723 NTSTATUS status;
3724 PROCESS_BASIC_INFORMATION pbi;
3725 SIZE_T count;
3726 PEB peb;
3727 IMAGE_DOS_HEADER dos;
3728 IMAGE_NT_HEADERS nt;
3729 DWORD ver = 0;
3731 if (!pid || pid == GetCurrentProcessId())
3733 IMAGE_NT_HEADERS *pnt;
3735 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3736 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3737 pnt->OptionalHeader.MinorSubsystemVersion);
3738 return 0;
3741 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3742 if (!process) return 0;
3744 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3745 if (status) goto err;
3747 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3748 if (status || count != sizeof(peb)) goto err;
3750 memset(&dos, 0, sizeof(dos));
3751 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3752 if (status || count != sizeof(dos)) goto err;
3753 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3755 memset(&nt, 0, sizeof(nt));
3756 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3757 if (status || count != sizeof(nt)) goto err;
3758 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3760 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3762 err:
3763 CloseHandle(process);
3765 if (status != STATUS_SUCCESS)
3766 SetLastError(RtlNtStatusToDosError(status));
3768 return ver;
3772 /***********************************************************************
3773 * SetProcessWorkingSetSizeEx [KERNEL32.@]
3774 * Sets the min/max working set sizes for a specified process.
3776 * PARAMS
3777 * process [I] Handle to the process of interest
3778 * minset [I] Specifies minimum working set size
3779 * maxset [I] Specifies maximum working set size
3780 * flags [I] Flags to enforce working set sizes
3782 * RETURNS
3783 * Success: TRUE
3784 * Failure: FALSE
3786 BOOL WINAPI SetProcessWorkingSetSizeEx(HANDLE process, SIZE_T minset, SIZE_T maxset, DWORD flags)
3788 WARN("(%p,%ld,%ld,%x): stub - harmless\n", process, minset, maxset, flags);
3789 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3790 /* Trim the working set to zero */
3791 /* Swap the process out of physical RAM */
3793 return TRUE;
3796 /***********************************************************************
3797 * SetProcessWorkingSetSize [KERNEL32.@]
3798 * Sets the min/max working set sizes for a specified process.
3800 * PARAMS
3801 * process [I] Handle to the process of interest
3802 * minset [I] Specifies minimum working set size
3803 * maxset [I] Specifies maximum working set size
3805 * RETURNS
3806 * Success: TRUE
3807 * Failure: FALSE
3809 BOOL WINAPI SetProcessWorkingSetSize(HANDLE process, SIZE_T minset, SIZE_T maxset)
3811 return SetProcessWorkingSetSizeEx(process, minset, maxset, 0);
3814 /***********************************************************************
3815 * K32EmptyWorkingSet (KERNEL32.@)
3817 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3819 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3823 /***********************************************************************
3824 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3826 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3827 SIZE_T *maxset, DWORD *flags)
3829 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3830 /* 32 MB working set size */
3831 if (minset) *minset = 32*1024*1024;
3832 if (maxset) *maxset = 32*1024*1024;
3833 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3834 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3835 return TRUE;
3839 /***********************************************************************
3840 * GetProcessWorkingSetSize (KERNEL32.@)
3842 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3844 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3848 /***********************************************************************
3849 * SetProcessShutdownParameters (KERNEL32.@)
3851 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3853 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3854 shutdown_flags = flags;
3855 shutdown_priority = level;
3856 return TRUE;
3860 /***********************************************************************
3861 * GetProcessShutdownParameters (KERNEL32.@)
3864 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3866 *lpdwLevel = shutdown_priority;
3867 *lpdwFlags = shutdown_flags;
3868 return TRUE;
3872 /***********************************************************************
3873 * GetProcessPriorityBoost (KERNEL32.@)
3875 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3877 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3879 /* Report that no boost is present.. */
3880 *pDisablePriorityBoost = FALSE;
3882 return TRUE;
3885 /***********************************************************************
3886 * SetProcessPriorityBoost (KERNEL32.@)
3888 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3890 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3891 /* Say we can do it. I doubt the program will notice that we don't. */
3892 return TRUE;
3896 /***********************************************************************
3897 * ReadProcessMemory (KERNEL32.@)
3899 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3900 SIZE_T *bytes_read )
3902 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3903 if (status) SetLastError( RtlNtStatusToDosError(status) );
3904 return !status;
3908 /***********************************************************************
3909 * WriteProcessMemory (KERNEL32.@)
3911 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3912 SIZE_T *bytes_written )
3914 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3915 if (status) SetLastError( RtlNtStatusToDosError(status) );
3916 return !status;
3920 /****************************************************************************
3921 * FlushInstructionCache (KERNEL32.@)
3923 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3925 NTSTATUS status;
3926 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3927 if (status) SetLastError( RtlNtStatusToDosError(status) );
3928 return !status;
3932 /******************************************************************
3933 * GetProcessIoCounters (KERNEL32.@)
3935 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3937 NTSTATUS status;
3939 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3940 ioc, sizeof(*ioc), NULL);
3941 if (status) SetLastError( RtlNtStatusToDosError(status) );
3942 return !status;
3945 /******************************************************************
3946 * GetProcessHandleCount (KERNEL32.@)
3948 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3950 NTSTATUS status;
3952 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3953 cnt, sizeof(*cnt), NULL);
3954 if (status) SetLastError( RtlNtStatusToDosError(status) );
3955 return !status;
3958 /******************************************************************
3959 * QueryFullProcessImageNameA (KERNEL32.@)
3961 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3963 BOOL retval;
3964 DWORD pdwSizeW = *pdwSize;
3965 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3967 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3969 if(retval)
3970 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3971 lpExeName, *pdwSize, NULL, NULL));
3972 if(retval)
3973 *pdwSize = strlen(lpExeName);
3975 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3976 return retval;
3979 /******************************************************************
3980 * QueryFullProcessImageNameW (KERNEL32.@)
3982 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3984 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3985 UNICODE_STRING *dynamic_buffer = NULL;
3986 UNICODE_STRING *result = NULL;
3987 NTSTATUS status;
3988 DWORD needed;
3990 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3991 * is a DOS path and we depend on this. */
3992 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3993 sizeof(buffer) - sizeof(WCHAR), &needed);
3994 if (status == STATUS_INFO_LENGTH_MISMATCH)
3996 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3997 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3998 result = dynamic_buffer;
4000 else
4001 result = (PUNICODE_STRING)buffer;
4003 if (status) goto cleanup;
4005 if (dwFlags & PROCESS_NAME_NATIVE)
4007 WCHAR drive[3];
4008 WCHAR device[1024];
4009 DWORD ntlen, devlen;
4011 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
4013 /* We cannot convert it to an NT device path so fail */
4014 status = STATUS_NO_SUCH_DEVICE;
4015 goto cleanup;
4018 /* Find this drive's NT device path */
4019 drive[0] = result->Buffer[0];
4020 drive[1] = ':';
4021 drive[2] = 0;
4022 if (!QueryDosDeviceW(drive, device, ARRAY_SIZE(device)))
4024 status = STATUS_NO_SUCH_DEVICE;
4025 goto cleanup;
4028 devlen = lstrlenW(device);
4029 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
4030 if (ntlen + 1 > *pdwSize)
4032 status = STATUS_BUFFER_TOO_SMALL;
4033 goto cleanup;
4035 *pdwSize = ntlen;
4037 memcpy(lpExeName, device, devlen * sizeof(*device));
4038 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
4039 lpExeName[*pdwSize] = 0;
4040 TRACE("NT path: %s\n", debugstr_w(lpExeName));
4042 else
4044 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
4046 status = STATUS_BUFFER_TOO_SMALL;
4047 goto cleanup;
4050 *pdwSize = result->Length/sizeof(WCHAR);
4051 memcpy( lpExeName, result->Buffer, result->Length );
4052 lpExeName[*pdwSize] = 0;
4055 cleanup:
4056 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
4057 if (status) SetLastError( RtlNtStatusToDosError(status) );
4058 return !status;
4061 /***********************************************************************
4062 * K32GetProcessImageFileNameA (KERNEL32.@)
4064 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
4066 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
4069 /***********************************************************************
4070 * K32GetProcessImageFileNameW (KERNEL32.@)
4072 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
4074 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
4077 /***********************************************************************
4078 * K32EnumProcesses (KERNEL32.@)
4080 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
4082 SYSTEM_PROCESS_INFORMATION *spi;
4083 ULONG size = 0x4000;
4084 void *buf = NULL;
4085 NTSTATUS status;
4087 do {
4088 size *= 2;
4089 HeapFree(GetProcessHeap(), 0, buf);
4090 buf = HeapAlloc(GetProcessHeap(), 0, size);
4091 if (!buf)
4092 return FALSE;
4094 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
4095 } while(status == STATUS_INFO_LENGTH_MISMATCH);
4097 if (status != STATUS_SUCCESS)
4099 HeapFree(GetProcessHeap(), 0, buf);
4100 SetLastError(RtlNtStatusToDosError(status));
4101 return FALSE;
4104 spi = buf;
4106 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
4108 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
4109 *lpcbUsed += sizeof(DWORD);
4111 if (spi->NextEntryOffset == 0)
4112 break;
4114 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
4117 HeapFree(GetProcessHeap(), 0, buf);
4118 return TRUE;
4121 /***********************************************************************
4122 * K32QueryWorkingSet (KERNEL32.@)
4124 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
4126 NTSTATUS status;
4128 TRACE( "(%p, %p, %d)\n", process, buffer, size );
4130 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
4132 if (status)
4134 SetLastError( RtlNtStatusToDosError( status ) );
4135 return FALSE;
4137 return TRUE;
4140 /***********************************************************************
4141 * K32QueryWorkingSetEx (KERNEL32.@)
4143 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
4145 NTSTATUS status;
4147 TRACE( "(%p, %p, %d)\n", process, buffer, size );
4149 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
4151 if (status)
4153 SetLastError( RtlNtStatusToDosError( status ) );
4154 return FALSE;
4156 return TRUE;
4159 /***********************************************************************
4160 * K32GetProcessMemoryInfo (KERNEL32.@)
4162 * Retrieve memory usage information for a given process
4165 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
4166 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
4168 NTSTATUS status;
4169 VM_COUNTERS vmc;
4171 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
4173 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4174 return FALSE;
4177 status = NtQueryInformationProcess(process, ProcessVmCounters,
4178 &vmc, sizeof(vmc), NULL);
4180 if (status)
4182 SetLastError(RtlNtStatusToDosError(status));
4183 return FALSE;
4186 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
4187 pmc->PageFaultCount = vmc.PageFaultCount;
4188 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
4189 pmc->WorkingSetSize = vmc.WorkingSetSize;
4190 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
4191 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
4192 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
4193 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
4194 pmc->PagefileUsage = vmc.PagefileUsage;
4195 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
4197 return TRUE;
4200 /***********************************************************************
4201 * ProcessIdToSessionId (KERNEL32.@)
4202 * This function is available on Terminal Server 4SP4 and Windows 2000
4204 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
4206 if (procid != GetCurrentProcessId())
4207 FIXME("Unsupported for other processes.\n");
4209 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
4210 return TRUE;
4214 /***********************************************************************
4215 * RegisterServiceProcess (KERNEL32.@)
4217 * A service process calls this function to ensure that it continues to run
4218 * even after a user logged off.
4220 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
4222 /* I don't think that Wine needs to do anything in this function */
4223 return 1; /* success */
4227 /**********************************************************************
4228 * IsWow64Process (KERNEL32.@)
4230 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
4232 ULONG_PTR pbi;
4233 NTSTATUS status;
4235 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
4237 if (status != STATUS_SUCCESS)
4239 SetLastError( RtlNtStatusToDosError( status ) );
4240 return FALSE;
4242 *Wow64Process = (pbi != 0);
4243 return TRUE;
4247 /***********************************************************************
4248 * GetCurrentProcess (KERNEL32.@)
4250 * Get a handle to the current process.
4252 * PARAMS
4253 * None.
4255 * RETURNS
4256 * A handle representing the current process.
4258 #undef GetCurrentProcess
4259 HANDLE WINAPI GetCurrentProcess(void)
4261 return (HANDLE)~(ULONG_PTR)0;
4264 /***********************************************************************
4265 * GetLogicalProcessorInformation (KERNEL32.@)
4267 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
4269 NTSTATUS status;
4271 TRACE("(%p,%p)\n", buffer, pBufLen);
4273 if(!pBufLen)
4275 SetLastError(ERROR_INVALID_PARAMETER);
4276 return FALSE;
4279 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
4281 if (status == STATUS_INFO_LENGTH_MISMATCH)
4283 SetLastError( ERROR_INSUFFICIENT_BUFFER );
4284 return FALSE;
4286 if (status != STATUS_SUCCESS)
4288 SetLastError( RtlNtStatusToDosError( status ) );
4289 return FALSE;
4291 return TRUE;
4294 /***********************************************************************
4295 * GetLogicalProcessorInformationEx (KERNEL32.@)
4297 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
4299 NTSTATUS status;
4301 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
4303 if (!len)
4305 SetLastError( ERROR_INVALID_PARAMETER );
4306 return FALSE;
4309 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
4310 buffer, *len, len );
4311 if (status == STATUS_INFO_LENGTH_MISMATCH)
4313 SetLastError( ERROR_INSUFFICIENT_BUFFER );
4314 return FALSE;
4316 if (status != STATUS_SUCCESS)
4318 SetLastError( RtlNtStatusToDosError( status ) );
4319 return FALSE;
4321 return TRUE;
4324 /***********************************************************************
4325 * CmdBatNotification (KERNEL32.@)
4327 * Notifies the system that a batch file has started or finished.
4329 * PARAMS
4330 * bBatchRunning [I] TRUE if a batch file has started or
4331 * FALSE if a batch file has finished executing.
4333 * RETURNS
4334 * Unknown.
4336 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
4338 FIXME("%d\n", bBatchRunning);
4339 return FALSE;
4342 /***********************************************************************
4343 * RegisterApplicationRestart (KERNEL32.@)
4345 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
4347 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
4349 return S_OK;
4352 /**********************************************************************
4353 * WTSGetActiveConsoleSessionId (KERNEL32.@)
4355 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
4357 static int once;
4358 if (!once++) FIXME("stub\n");
4359 /* Return current session id. */
4360 return NtCurrentTeb()->Peb->SessionId;
4363 /**********************************************************************
4364 * GetSystemDEPPolicy (KERNEL32.@)
4366 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
4368 FIXME("stub\n");
4369 return OptIn;
4372 /**********************************************************************
4373 * SetProcessDEPPolicy (KERNEL32.@)
4375 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
4377 FIXME("(%d): stub\n", newDEP);
4378 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4379 return FALSE;
4382 /**********************************************************************
4383 * ApplicationRecoveryFinished (KERNEL32.@)
4385 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
4387 FIXME(": stub\n");
4388 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4391 /**********************************************************************
4392 * ApplicationRecoveryInProgress (KERNEL32.@)
4394 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
4396 FIXME(":%p stub\n", canceled);
4397 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4398 return E_FAIL;
4401 /**********************************************************************
4402 * RegisterApplicationRecoveryCallback (KERNEL32.@)
4404 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
4406 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
4407 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4408 return E_FAIL;
4411 /***********************************************************************
4412 * GetApplicationRestartSettings (KERNEL32.@)
4414 HRESULT WINAPI GetApplicationRestartSettings(HANDLE process, WCHAR *cmdline, DWORD *size, DWORD *flags)
4416 FIXME("%p, %p, %p, %p)\n", process, cmdline, size, flags);
4417 return E_NOTIMPL;
4420 /**********************************************************************
4421 * GetNumaHighestNodeNumber (KERNEL32.@)
4423 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4425 *highestnode = 0;
4426 FIXME("(%p): semi-stub\n", highestnode);
4427 return TRUE;
4430 /**********************************************************************
4431 * GetNumaNodeProcessorMask (KERNEL32.@)
4433 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4435 FIXME("(%c %p): stub\n", node, mask);
4436 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4437 return FALSE;
4440 /**********************************************************************
4441 * GetNumaNodeProcessorMaskEx (KERNEL32.@)
4443 BOOL WINAPI GetNumaNodeProcessorMaskEx(USHORT node, PGROUP_AFFINITY mask)
4445 FIXME("(%hu %p): stub\n", node, mask);
4446 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4447 return FALSE;
4450 /**********************************************************************
4451 * GetNumaAvailableMemoryNode (KERNEL32.@)
4453 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4455 FIXME("(%c %p): stub\n", node, available_bytes);
4456 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4457 return FALSE;
4460 /***********************************************************************
4461 * GetNumaProcessorNode (KERNEL32.@)
4463 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4465 SYSTEM_INFO si;
4467 TRACE("(%d, %p)\n", processor, node);
4469 GetSystemInfo( &si );
4470 if (processor < si.dwNumberOfProcessors)
4472 *node = 0;
4473 return TRUE;
4476 *node = 0xFF;
4477 SetLastError(ERROR_INVALID_PARAMETER);
4478 return FALSE;
4481 /**********************************************************************
4482 * GetProcessDEPPolicy (KERNEL32.@)
4484 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4486 NTSTATUS status;
4487 ULONG dep_flags;
4489 TRACE("(%p %p %p)\n", process, flags, permanent);
4491 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4492 &dep_flags, sizeof(dep_flags), NULL );
4493 if (!status)
4496 if (flags)
4498 *flags = 0;
4499 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4500 *flags |= PROCESS_DEP_ENABLE;
4501 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4502 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4505 if (permanent)
4506 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4509 if (status) SetLastError( RtlNtStatusToDosError(status) );
4510 return !status;
4513 /**********************************************************************
4514 * FlushProcessWriteBuffers (KERNEL32.@)
4516 VOID WINAPI FlushProcessWriteBuffers(void)
4518 static int once = 0;
4520 if (!once++)
4521 FIXME(": stub\n");
4524 /***********************************************************************
4525 * UnregisterApplicationRestart (KERNEL32.@)
4527 HRESULT WINAPI UnregisterApplicationRestart(void)
4529 FIXME(": stub\n");
4530 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4531 return S_OK;
4534 struct proc_thread_attr
4536 DWORD_PTR attr;
4537 SIZE_T size;
4538 void *value;
4541 struct _PROC_THREAD_ATTRIBUTE_LIST
4543 DWORD mask; /* bitmask of items in list */
4544 DWORD size; /* max number of items in list */
4545 DWORD count; /* number of items in list */
4546 DWORD pad;
4547 DWORD_PTR unk;
4548 struct proc_thread_attr attrs[1];
4551 /***********************************************************************
4552 * InitializeProcThreadAttributeList (KERNEL32.@)
4554 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4555 DWORD count, DWORD flags, SIZE_T *size)
4557 SIZE_T needed;
4558 BOOL ret = FALSE;
4560 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4562 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4563 if (list && *size >= needed)
4565 list->mask = 0;
4566 list->size = count;
4567 list->count = 0;
4568 list->unk = 0;
4569 ret = TRUE;
4571 else
4572 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4574 *size = needed;
4575 return ret;
4578 /***********************************************************************
4579 * UpdateProcThreadAttribute (KERNEL32.@)
4581 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4582 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4583 void *prev_ret, SIZE_T *size_ret)
4585 DWORD mask;
4586 struct proc_thread_attr *entry;
4588 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4590 if (list->count >= list->size)
4592 SetLastError(ERROR_GEN_FAILURE);
4593 return FALSE;
4596 switch (attr)
4598 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4599 if (size != sizeof(HANDLE))
4601 SetLastError(ERROR_BAD_LENGTH);
4602 return FALSE;
4604 break;
4606 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4607 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4609 SetLastError(ERROR_BAD_LENGTH);
4610 return FALSE;
4612 break;
4614 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4615 if (size != sizeof(PROCESSOR_NUMBER))
4617 SetLastError(ERROR_BAD_LENGTH);
4618 return FALSE;
4620 break;
4622 case PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY:
4623 if (size != sizeof(DWORD) && size != sizeof(DWORD64))
4625 SetLastError(ERROR_BAD_LENGTH);
4626 return FALSE;
4628 break;
4630 case PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY:
4631 if (size != sizeof(DWORD) && size != sizeof(DWORD64) && size != sizeof(DWORD64) * 2)
4633 SetLastError(ERROR_BAD_LENGTH);
4634 return FALSE;
4636 break;
4638 default:
4639 SetLastError(ERROR_NOT_SUPPORTED);
4640 FIXME("Unhandled attribute number %lu\n", attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4641 return FALSE;
4644 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4646 if (list->mask & mask)
4648 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4649 return FALSE;
4652 list->mask |= mask;
4654 entry = list->attrs + list->count;
4655 entry->attr = attr;
4656 entry->size = size;
4657 entry->value = value;
4658 list->count++;
4660 return TRUE;
4663 /***********************************************************************
4664 * CreateUmsCompletionList (KERNEL32.@)
4666 BOOL WINAPI CreateUmsCompletionList(PUMS_COMPLETION_LIST *list)
4668 FIXME( "%p: stub\n", list );
4669 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4670 return FALSE;
4673 /***********************************************************************
4674 * CreateUmsThreadContext (KERNEL32.@)
4676 BOOL WINAPI CreateUmsThreadContext(PUMS_CONTEXT *ctx)
4678 FIXME( "%p: stub\n", ctx );
4679 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4680 return FALSE;
4683 /***********************************************************************
4684 * DeleteProcThreadAttributeList (KERNEL32.@)
4686 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4688 return;
4691 /***********************************************************************
4692 * DeleteUmsCompletionList (KERNEL32.@)
4694 BOOL WINAPI DeleteUmsCompletionList(PUMS_COMPLETION_LIST list)
4696 FIXME( "%p: stub\n", list );
4697 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4698 return FALSE;
4701 /***********************************************************************
4702 * DeleteUmsThreadContext (KERNEL32.@)
4704 BOOL WINAPI DeleteUmsThreadContext(PUMS_CONTEXT ctx)
4706 FIXME( "%p: stub\n", ctx );
4707 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4708 return FALSE;
4711 /***********************************************************************
4712 * DequeueUmsCompletionListItems (KERNEL32.@)
4714 BOOL WINAPI DequeueUmsCompletionListItems(void *list, DWORD timeout, PUMS_CONTEXT *ctx)
4716 FIXME( "%p,%08x,%p: stub\n", list, timeout, ctx );
4717 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4718 return FALSE;
4721 /***********************************************************************
4722 * EnterUmsSchedulingMode (KERNEL32.@)
4724 BOOL WINAPI EnterUmsSchedulingMode(UMS_SCHEDULER_STARTUP_INFO *info)
4726 FIXME( "%p: stub\n", info );
4727 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4728 return FALSE;
4731 /***********************************************************************
4732 * ExecuteUmsThread (KERNEL32.@)
4734 BOOL WINAPI ExecuteUmsThread(PUMS_CONTEXT ctx)
4736 FIXME( "%p: stub\n", ctx );
4737 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4738 return FALSE;
4741 /***********************************************************************
4742 * GetCurrentUmsThread (KERNEL32.@)
4744 PUMS_CONTEXT WINAPI GetCurrentUmsThread(void)
4746 FIXME( "stub\n" );
4747 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4748 return FALSE;
4751 /***********************************************************************
4752 * GetNextUmsListItem (KERNEL32.@)
4754 PUMS_CONTEXT WINAPI GetNextUmsListItem(PUMS_CONTEXT ctx)
4756 FIXME( "%p: stub\n", ctx );
4757 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4758 return NULL;
4761 /***********************************************************************
4762 * GetUmsCompletionListEvent (KERNEL32.@)
4764 BOOL WINAPI GetUmsCompletionListEvent(PUMS_COMPLETION_LIST list, HANDLE *event)
4766 FIXME( "%p,%p: stub\n", list, event );
4767 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4768 return FALSE;
4771 /***********************************************************************
4772 * QueryUmsThreadInformation (KERNEL32.@)
4774 BOOL WINAPI QueryUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4775 void *buf, ULONG length, ULONG *ret_length)
4777 FIXME( "%p,%08x,%p,%08x,%p: stub\n", ctx, class, buf, length, ret_length );
4778 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4779 return FALSE;
4782 /***********************************************************************
4783 * SetUmsThreadInformation (KERNEL32.@)
4785 BOOL WINAPI SetUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4786 void *buf, ULONG length)
4788 FIXME( "%p,%08x,%p,%08x: stub\n", ctx, class, buf, length );
4789 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4790 return FALSE;
4793 /***********************************************************************
4794 * UmsThreadYield (KERNEL32.@)
4796 BOOL WINAPI UmsThreadYield(void *param)
4798 FIXME( "%p: stub\n", param );
4799 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4800 return FALSE;
4803 /**********************************************************************
4804 * BaseFlushAppcompatCache (KERNEL32.@)
4806 BOOL WINAPI BaseFlushAppcompatCache(void)
4808 FIXME(": stub\n");
4809 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4810 return FALSE;
4813 /**********************************************************************
4814 * SetProcessMitigationPolicy (KERNEL32.@)
4816 BOOL WINAPI SetProcessMitigationPolicy(PROCESS_MITIGATION_POLICY policy, void *buffer, SIZE_T length)
4818 FIXME("(%d, %p, %lu): stub\n", policy, buffer, length);
4820 return TRUE;
4823 /**********************************************************************
4824 * GetProcessMitigationPolicy (KERNEL32.@)
4826 BOOL WINAPI GetProcessMitigationPolicy(HANDLE hProcess, PROCESS_MITIGATION_POLICY policy, void *buffer, SIZE_T length)
4828 FIXME("(%p, %u, %p, %lu): stub\n", hProcess, policy, buffer, length);
4830 return TRUE;