include: Move inline assembly definitions to a new wine/asm.h header.
[wine.git] / dlls / kernel32 / process.c
blobb48aa669b2a4d57634caddbde5a68f7a439069ce
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/asm.h"
65 #include "wine/debug.h"
67 WINE_DEFAULT_DEBUG_CHANNEL(process);
68 WINE_DECLARE_DEBUG_CHANNEL(relay);
70 #ifdef __APPLE__
71 extern char **__wine_get_main_environment(void);
72 #else
73 extern char **__wine_main_environ;
74 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
75 #endif
77 typedef struct
79 LPSTR lpEnvAddress;
80 LPSTR lpCmdLine;
81 LPSTR lpCmdShow;
82 DWORD dwReserved;
83 } LOADPARMS32;
85 static DWORD shutdown_flags = 0;
86 static DWORD shutdown_priority = 0x280;
87 static BOOL is_wow64;
88 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
90 HMODULE kernel32_handle = 0;
91 SYSTEM_BASIC_INFORMATION system_info = { 0 };
93 const WCHAR DIR_Windows[] = {'C',':','\\','w','i','n','d','o','w','s',0};
94 const WCHAR DIR_System[] = {'C',':','\\','w','i','n','d','o','w','s',
95 '\\','s','y','s','t','e','m','3','2',0};
96 const WCHAR *DIR_SysWow64 = NULL;
98 /* Process flags */
99 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
100 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
101 #define PDB32_DOS_PROC 0x0010 /* Dos process */
102 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
103 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
104 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
106 static const WCHAR exeW[] = {'.','e','x','e',0};
107 static const WCHAR comW[] = {'.','c','o','m',0};
108 static const WCHAR batW[] = {'.','b','a','t',0};
109 static const WCHAR cmdW[] = {'.','c','m','d',0};
110 static const WCHAR pifW[] = {'.','p','i','f',0};
111 static WCHAR winevdm[] = {'C',':','\\','w','i','n','d','o','w','s',
112 '\\','s','y','s','t','e','m','3','2',
113 '\\','w','i','n','e','v','d','m','.','e','x','e',0};
115 static const char * const cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
117 static void exec_process( LPCWSTR name );
119 extern void SHELL_LoadRegistry(void);
121 /* return values for get_binary_info */
122 enum binary_type
124 BINARY_UNKNOWN = 0,
125 BINARY_PE,
126 BINARY_WIN16,
127 BINARY_UNIX_EXE,
128 BINARY_UNIX_LIB
132 /***********************************************************************
133 * contains_path
135 static inline BOOL contains_path( LPCWSTR name )
137 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
141 /***********************************************************************
142 * is_special_env_var
144 * Check if an environment variable needs to be handled specially when
145 * passed through the Unix environment (i.e. prefixed with "WINE").
147 static inline BOOL is_special_env_var( const char *var )
149 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
150 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
151 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
152 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
153 !strncmp( var, "TMP=", sizeof("TMP=")-1 ) ||
154 !strncmp( var, "QT_", sizeof("QT_")-1 ) ||
155 !strncmp( var, "VK_", sizeof("VK_")-1 ));
159 /***********************************************************************
160 * is_path_prefix
162 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
164 unsigned int len = strlenW( prefix );
166 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
167 while (filename[len] == '\\') len++;
168 return len;
172 /***********************************************************************
173 * is_64bit_arch
175 static inline BOOL is_64bit_arch( cpu_type_t cpu )
177 return (cpu == CPU_x86_64 || cpu == CPU_ARM64);
181 /***********************************************************************
182 * get_pe_info
184 static NTSTATUS get_pe_info( HANDLE handle, pe_image_info_t *info )
186 NTSTATUS status;
187 HANDLE mapping;
189 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY,
190 NULL, NULL, PAGE_READONLY, SEC_IMAGE, handle );
191 if (status) return status;
193 SERVER_START_REQ( get_mapping_info )
195 req->handle = wine_server_obj_handle( mapping );
196 req->access = SECTION_QUERY;
197 wine_server_set_reply( req, info, sizeof(*info) );
198 status = wine_server_call( req );
200 SERVER_END_REQ;
201 CloseHandle( mapping );
202 return status;
206 /***********************************************************************
207 * get_binary_info
209 static enum binary_type get_binary_info( HANDLE hfile, pe_image_info_t *info )
211 union
213 struct
215 unsigned char magic[4];
216 unsigned char class;
217 unsigned char data;
218 unsigned char ignored1[10];
219 unsigned short type;
220 unsigned short machine;
221 unsigned char ignored2[8];
222 unsigned int phoff;
223 unsigned char ignored3[12];
224 unsigned short phnum;
225 } elf;
226 struct
228 unsigned char magic[4];
229 unsigned char class;
230 unsigned char data;
231 unsigned char ignored1[10];
232 unsigned short type;
233 unsigned short machine;
234 unsigned char ignored2[12];
235 unsigned __int64 phoff;
236 unsigned char ignored3[16];
237 unsigned short phnum;
238 } elf64;
239 struct
241 unsigned int magic;
242 unsigned int cputype;
243 unsigned int cpusubtype;
244 unsigned int filetype;
245 } macho;
246 IMAGE_DOS_HEADER mz;
247 } header;
249 DWORD len;
250 NTSTATUS status;
252 memset( info, 0, sizeof(*info) );
254 status = get_pe_info( hfile, info );
255 switch (status)
257 case STATUS_SUCCESS:
258 return BINARY_PE;
259 case STATUS_INVALID_IMAGE_WIN_32:
260 return BINARY_PE;
261 case STATUS_INVALID_IMAGE_WIN_64:
262 return BINARY_PE;
263 case STATUS_INVALID_IMAGE_WIN_16:
264 case STATUS_INVALID_IMAGE_NE_FORMAT:
265 case STATUS_INVALID_IMAGE_PROTECT:
266 return BINARY_WIN16;
269 /* Seek to the start of the file and read the header information. */
270 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return BINARY_UNKNOWN;
271 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
272 return BINARY_UNKNOWN;
274 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
276 #ifdef WORDS_BIGENDIAN
277 BOOL byteswap = (header.elf.data == 1);
278 #else
279 BOOL byteswap = (header.elf.data == 2);
280 #endif
281 if (byteswap)
283 header.elf.type = RtlUshortByteSwap( header.elf.type );
284 header.elf.machine = RtlUshortByteSwap( header.elf.machine );
286 switch(header.elf.machine)
288 case 3: info->cpu = CPU_x86; break;
289 case 20: info->cpu = CPU_POWERPC; break;
290 case 40: info->cpu = CPU_ARM; break;
291 case 62: info->cpu = CPU_x86_64; break;
292 case 183: info->cpu = CPU_ARM64; break;
294 switch(header.elf.type)
296 case 2:
297 return BINARY_UNIX_EXE;
298 case 3:
300 LARGE_INTEGER phoff;
301 unsigned short phnum;
302 unsigned int type;
303 if (header.elf.class == 2)
305 phoff.QuadPart = byteswap ? RtlUlonglongByteSwap( header.elf64.phoff ) : header.elf64.phoff;
306 phnum = byteswap ? RtlUshortByteSwap( header.elf64.phnum ) : header.elf64.phnum;
308 else
310 phoff.QuadPart = byteswap ? RtlUlongByteSwap( header.elf.phoff ) : header.elf.phoff;
311 phnum = byteswap ? RtlUshortByteSwap( header.elf.phnum ) : header.elf.phnum;
313 while (phnum--)
315 if (SetFilePointerEx( hfile, phoff, NULL, FILE_BEGIN ) == -1) return BINARY_UNKNOWN;
316 if (!ReadFile( hfile, &type, sizeof(type), &len, NULL ) || len < sizeof(type))
317 return BINARY_UNKNOWN;
318 if (byteswap) type = RtlUlongByteSwap( type );
319 if (type == 3) return BINARY_UNIX_EXE;
320 phoff.QuadPart += (header.elf.class == 2) ? 56 : 32;
322 return BINARY_UNIX_LIB;
326 /* Mach-o File with Endian set to Big Endian or Little Endian */
327 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe ||
328 header.macho.magic == 0xfeedfacf || header.macho.magic == 0xcffaedfe)
330 if (header.macho.magic == 0xcefaedfe || header.macho.magic == 0xcffaedfe)
332 header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
333 header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
335 switch(header.macho.cputype)
337 case 0x00000007: info->cpu = CPU_x86; break;
338 case 0x01000007: info->cpu = CPU_x86_64; break;
339 case 0x0000000c: info->cpu = CPU_ARM; break;
340 case 0x0100000c: info->cpu = CPU_ARM64; break;
341 case 0x00000012: info->cpu = CPU_POWERPC; break;
343 switch(header.macho.filetype)
345 case 2: return BINARY_UNIX_EXE;
346 case 8: return BINARY_UNIX_LIB;
349 return BINARY_UNKNOWN;
353 /***************************************************************************
354 * get_builtin_path
356 * Get the path of a builtin module when the native file does not exist.
358 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
359 UINT size, BOOL *is_64bit )
361 WCHAR *file_part;
362 UINT len;
363 void *redir_disabled = 0;
365 *is_64bit = (sizeof(void*) > sizeof(int));
367 /* builtin names cannot be empty or contain spaces */
368 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
370 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
371 Wow64RevertWow64FsRedirection( redir_disabled );
373 if (contains_path( libname ))
375 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
376 filename, &file_part ) > size * sizeof(WCHAR))
377 return FALSE; /* too long */
379 if ((len = is_path_prefix( DIR_System, filename )))
381 if (is_wow64 && redir_disabled) *is_64bit = TRUE;
383 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
385 *is_64bit = FALSE;
387 else return FALSE;
389 if (filename + len != file_part) return FALSE;
391 else
393 len = strlenW( DIR_System );
394 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
395 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
396 file_part = filename + len;
397 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
398 strcpyW( file_part, libname );
399 if (is_wow64 && redir_disabled) *is_64bit = TRUE;
401 if (ext && !strchrW( file_part, '.' ))
403 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
404 return FALSE; /* too long */
405 strcatW( file_part, ext );
407 return TRUE;
411 /***********************************************************************
412 * open_exe_file
414 * Open a specific exe file, taking load order into account.
415 * Returns the file handle or 0 for a builtin exe.
417 static HANDLE open_exe_file( const WCHAR *name, BOOL *is_64bit )
419 HANDLE handle;
421 TRACE("looking for %s\n", debugstr_w(name) );
423 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
424 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
426 WCHAR buffer[MAX_PATH];
427 /* file doesn't exist, check for builtin */
428 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), is_64bit ))
429 handle = 0;
431 return handle;
435 /***********************************************************************
436 * find_exe_file
438 * Open an exe file, and return the full name and file handle.
439 * Returns FALSE if file could not be found.
441 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
443 TRACE("looking for %s\n", debugstr_w(name) );
445 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
446 /* no builtin found, try native without extension in case it is a Unix app */
447 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
449 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
450 *handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
451 NULL, OPEN_EXISTING, 0, 0 );
452 return (*handle != INVALID_HANDLE_VALUE);
456 /***********************************************************************
457 * build_initial_environment
459 * Build the Win32 environment from the Unix environment
461 static BOOL build_initial_environment(void)
463 SIZE_T size = 1;
464 char **e;
465 WCHAR *p, *endptr;
466 void *ptr;
467 char **env = __wine_get_main_environment();
469 /* Compute the total size of the Unix environment */
470 for (e = env; *e; e++)
472 if (is_special_env_var( *e )) continue;
473 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
475 size *= sizeof(WCHAR);
477 /* Now allocate the environment */
478 ptr = NULL;
479 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
480 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
481 return FALSE;
483 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
484 endptr = p + size / sizeof(WCHAR);
486 /* And fill it with the Unix environment */
487 for (e = env; *e; e++)
489 char *str = *e;
491 /* skip Unix special variables and use the Wine variants instead */
492 if (!strncmp( str, "WINE", 4 ))
494 if (is_special_env_var( str + 4 )) str += 4;
495 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
497 else if (is_special_env_var( str )) continue; /* skip it */
499 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
500 p += strlenW(p) + 1;
502 *p = 0;
503 return TRUE;
507 /***********************************************************************
508 * set_registry_variables
510 * Set environment variables by enumerating the values of a key;
511 * helper for set_registry_environment().
512 * Note that Windows happily truncates the value if it's too big.
514 static void set_registry_variables( HANDLE hkey, ULONG type )
516 static const WCHAR pathW[] = {'P','A','T','H'};
517 static const WCHAR sep[] = {';',0};
518 UNICODE_STRING env_name, env_value;
519 NTSTATUS status;
520 DWORD size;
521 int index;
522 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
523 WCHAR tmpbuf[1024];
524 UNICODE_STRING tmp;
525 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
527 tmp.Buffer = tmpbuf;
528 tmp.MaximumLength = sizeof(tmpbuf);
530 for (index = 0; ; index++)
532 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
533 buffer, sizeof(buffer), &size );
534 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
535 break;
536 if (info->Type != type)
537 continue;
538 env_name.Buffer = info->Name;
539 env_name.Length = env_name.MaximumLength = info->NameLength;
540 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
541 env_value.Length = info->DataLength;
542 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
543 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
544 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
545 if (!env_value.Length) continue;
546 if (info->Type == REG_EXPAND_SZ)
548 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
549 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
550 RtlCopyUnicodeString( &env_value, &tmp );
552 /* PATH is magic */
553 if (env_name.Length == sizeof(pathW) &&
554 !strncmpiW( env_name.Buffer, pathW, ARRAY_SIZE( pathW )) &&
555 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
557 RtlAppendUnicodeToString( &tmp, sep );
558 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
559 RtlCopyUnicodeString( &env_value, &tmp );
561 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
566 /***********************************************************************
567 * set_registry_environment
569 * Set the environment variables specified in the registry.
571 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
572 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
573 * on the order in which the variables are processed. But on Windows it
574 * does not really matter since they only use %SystemDrive% and
575 * %SystemRoot% which are predefined. But Wine defines these in the
576 * registry, so we need two passes.
578 static BOOL set_registry_environment( BOOL volatile_only )
580 static const WCHAR env_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
581 'M','a','c','h','i','n','e','\\',
582 'S','y','s','t','e','m','\\',
583 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
584 'C','o','n','t','r','o','l','\\',
585 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
586 'E','n','v','i','r','o','n','m','e','n','t',0};
587 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
588 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};
590 OBJECT_ATTRIBUTES attr;
591 UNICODE_STRING nameW;
592 HANDLE hkey;
593 BOOL ret = FALSE;
595 attr.Length = sizeof(attr);
596 attr.RootDirectory = 0;
597 attr.ObjectName = &nameW;
598 attr.Attributes = 0;
599 attr.SecurityDescriptor = NULL;
600 attr.SecurityQualityOfService = NULL;
602 /* first the system environment variables */
603 RtlInitUnicodeString( &nameW, env_keyW );
604 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
606 set_registry_variables( hkey, REG_SZ );
607 set_registry_variables( hkey, REG_EXPAND_SZ );
608 NtClose( hkey );
609 ret = TRUE;
612 /* then the ones for the current user */
613 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
614 RtlInitUnicodeString( &nameW, envW );
615 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
617 set_registry_variables( hkey, REG_SZ );
618 set_registry_variables( hkey, REG_EXPAND_SZ );
619 NtClose( hkey );
622 RtlInitUnicodeString( &nameW, volatile_envW );
623 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
625 set_registry_variables( hkey, REG_SZ );
626 set_registry_variables( hkey, REG_EXPAND_SZ );
627 NtClose( hkey );
630 NtClose( attr.RootDirectory );
631 return ret;
635 /***********************************************************************
636 * get_reg_value
638 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
640 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
641 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
642 DWORD len, size = sizeof(buffer);
643 WCHAR *ret = NULL;
644 UNICODE_STRING nameW;
646 RtlInitUnicodeString( &nameW, name );
647 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
648 return NULL;
650 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
651 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
653 if (info->Type == REG_EXPAND_SZ)
655 UNICODE_STRING value, expanded;
657 value.MaximumLength = len * sizeof(WCHAR);
658 value.Buffer = (WCHAR *)info->Data;
659 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
660 value.Length = len * sizeof(WCHAR);
661 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
662 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
663 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
664 else RtlFreeUnicodeString( &expanded );
666 else if (info->Type == REG_SZ)
668 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
670 memcpy( ret, info->Data, len * sizeof(WCHAR) );
671 ret[len] = 0;
674 return ret;
678 /***********************************************************************
679 * set_additional_environment
681 * Set some additional environment variables not specified in the registry.
683 static void set_additional_environment(void)
685 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
686 'M','a','c','h','i','n','e','\\',
687 'S','o','f','t','w','a','r','e','\\',
688 'M','i','c','r','o','s','o','f','t','\\',
689 'W','i','n','d','o','w','s',' ','N','T','\\',
690 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
691 'P','r','o','f','i','l','e','L','i','s','t',0};
692 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
693 static const WCHAR public_valueW[] = {'P','u','b','l','i','c',0};
694 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
695 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
696 static const WCHAR programdataW[] = {'P','r','o','g','r','a','m','D','a','t','a',0};
697 static const WCHAR publicW[] = {'P','U','B','L','I','C',0};
698 OBJECT_ATTRIBUTES attr;
699 UNICODE_STRING nameW;
700 WCHAR *profile_dir = NULL, *program_data_dir = NULL, *public_dir = NULL;
701 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
702 HANDLE hkey;
703 DWORD len;
705 /* ComputerName */
706 len = ARRAY_SIZE( buf );
707 if (GetComputerNameW( buf, &len ))
708 SetEnvironmentVariableW( computernameW, buf );
710 /* set the ALLUSERSPROFILE variables */
712 attr.Length = sizeof(attr);
713 attr.RootDirectory = 0;
714 attr.ObjectName = &nameW;
715 attr.Attributes = 0;
716 attr.SecurityDescriptor = NULL;
717 attr.SecurityQualityOfService = NULL;
718 RtlInitUnicodeString( &nameW, profile_keyW );
719 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
721 profile_dir = get_reg_value( hkey, profiles_valueW );
722 program_data_dir = get_reg_value( hkey, programdataW );
723 public_dir = get_reg_value( hkey, public_valueW );
724 NtClose( hkey );
727 if (program_data_dir)
729 SetEnvironmentVariableW( allusersW, program_data_dir );
730 SetEnvironmentVariableW( programdataW, program_data_dir );
733 if (public_dir)
735 SetEnvironmentVariableW( publicW, public_dir );
738 HeapFree( GetProcessHeap(), 0, profile_dir );
739 HeapFree( GetProcessHeap(), 0, program_data_dir );
740 HeapFree( GetProcessHeap(), 0, public_dir );
743 /***********************************************************************
744 * set_wow64_environment
746 * Set the environment variables that change across 32/64/Wow64.
748 static void set_wow64_environment(void)
750 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};
751 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};
752 static const WCHAR x86W[] = {'x','8','6',0};
753 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
754 'M','a','c','h','i','n','e','\\',
755 'S','o','f','t','w','a','r','e','\\',
756 'M','i','c','r','o','s','o','f','t','\\',
757 'W','i','n','d','o','w','s','\\',
758 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
759 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
760 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
761 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
762 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
763 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
764 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
765 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
766 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
768 OBJECT_ATTRIBUTES attr;
769 UNICODE_STRING nameW;
770 WCHAR arch[64];
771 WCHAR *value;
772 HANDLE hkey;
774 /* set the PROCESSOR_ARCHITECTURE variable */
776 if (GetEnvironmentVariableW( arch6432W, arch, ARRAY_SIZE( arch )))
778 if (is_win64)
780 SetEnvironmentVariableW( archW, arch );
781 SetEnvironmentVariableW( arch6432W, NULL );
784 else if (GetEnvironmentVariableW( archW, arch, ARRAY_SIZE( arch )))
786 if (is_wow64)
788 SetEnvironmentVariableW( arch6432W, arch );
789 SetEnvironmentVariableW( archW, x86W );
793 attr.Length = sizeof(attr);
794 attr.RootDirectory = 0;
795 attr.ObjectName = &nameW;
796 attr.Attributes = 0;
797 attr.SecurityDescriptor = NULL;
798 attr.SecurityQualityOfService = NULL;
799 RtlInitUnicodeString( &nameW, versionW );
800 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
802 /* set the ProgramFiles variables */
804 if ((value = get_reg_value( hkey, progdirW )))
806 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
807 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
808 HeapFree( GetProcessHeap(), 0, value );
810 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
812 SetEnvironmentVariableW( progfilesW, value );
813 HeapFree( GetProcessHeap(), 0, value );
816 /* set the CommonProgramFiles variables */
818 if ((value = get_reg_value( hkey, commondirW )))
820 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
821 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
822 HeapFree( GetProcessHeap(), 0, value );
824 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
826 SetEnvironmentVariableW( commonfilesW, value );
827 HeapFree( GetProcessHeap(), 0, value );
830 NtClose( hkey );
833 /***********************************************************************
834 * set_library_wargv
836 * Set the Wine library Unicode argv global variables.
838 static void set_library_wargv( char **argv )
840 int argc;
841 char *q;
842 WCHAR *p;
843 WCHAR **wargv;
844 DWORD total = 0;
846 for (argc = 0; argv[argc]; argc++)
847 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
849 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
850 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
851 p = (WCHAR *)(wargv + argc + 1);
852 for (argc = 0; argv[argc]; argc++)
854 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
855 wargv[argc] = p;
856 p += reslen;
857 total -= reslen;
859 wargv[argc] = NULL;
861 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
863 for (argc = 0; wargv[argc]; argc++)
864 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
866 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
867 q = (char *)(argv + argc + 1);
868 for (argc = 0; wargv[argc]; argc++)
870 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
871 argv[argc] = q;
872 q += reslen;
873 total -= reslen;
875 argv[argc] = NULL;
877 __wine_main_argc = argc;
878 __wine_main_argv = argv;
879 __wine_main_wargv = wargv;
883 /***********************************************************************
884 * update_library_argv0
886 * Update the argv[0] global variable with the binary we have found.
888 static void update_library_argv0( const WCHAR *argv0 )
890 DWORD len = strlenW( argv0 );
892 if (len > strlenW( __wine_main_wargv[0] ))
894 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
896 strcpyW( __wine_main_wargv[0], argv0 );
898 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
899 if (len > strlen( __wine_main_argv[0] ) + 1)
901 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
903 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
907 /***********************************************************************
908 * build_command_line
910 * Build the command line of a process from the argv array.
912 * Note that it does NOT necessarily include the file name.
913 * Sometimes we don't even have any command line options at all.
915 * We must quote and escape characters so that the argv array can be rebuilt
916 * from the command line:
917 * - spaces and tabs must be quoted
918 * 'a b' -> '"a b"'
919 * - quotes must be escaped
920 * '"' -> '\"'
921 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
922 * resulting in an odd number of '\' followed by a '"'
923 * '\"' -> '\\\"'
924 * '\\"' -> '\\\\\"'
925 * - '\'s are followed by the closing '"' must be doubled,
926 * resulting in an even number of '\' followed by a '"'
927 * ' \' -> '" \\"'
928 * ' \\' -> '" \\\\"'
929 * - '\'s that are not followed by a '"' can be left as is
930 * 'a\b' == 'a\b'
931 * 'a\\b' == 'a\\b'
933 static BOOL build_command_line( WCHAR **argv )
935 int len;
936 WCHAR **arg;
937 LPWSTR p;
938 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
940 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
942 len = 0;
943 for (arg = argv; *arg; arg++)
945 BOOL has_space;
946 int bcount;
947 WCHAR* a;
949 has_space=FALSE;
950 bcount=0;
951 a=*arg;
952 if( !*a ) has_space=TRUE;
953 while (*a!='\0') {
954 if (*a=='\\') {
955 bcount++;
956 } else {
957 if (*a==' ' || *a=='\t') {
958 has_space=TRUE;
959 } else if (*a=='"') {
960 /* doubling of '\' preceding a '"',
961 * plus escaping of said '"'
963 len+=2*bcount+1;
965 bcount=0;
967 a++;
969 len+=(a-*arg)+1 /* for the separating space */;
970 if (has_space)
971 len+=2+bcount; /* for the quotes and doubling of '\' preceding the closing quote */
974 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
975 return FALSE;
977 p = rupp->CommandLine.Buffer;
978 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
979 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
980 for (arg = argv; *arg; arg++)
982 BOOL has_space,has_quote;
983 WCHAR* a;
984 int bcount;
986 /* Check for quotes and spaces in this argument */
987 has_space=has_quote=FALSE;
988 a=*arg;
989 if( !*a ) has_space=TRUE;
990 while (*a!='\0') {
991 if (*a==' ' || *a=='\t') {
992 has_space=TRUE;
993 if (has_quote)
994 break;
995 } else if (*a=='"') {
996 has_quote=TRUE;
997 if (has_space)
998 break;
1000 a++;
1003 /* Now transfer it to the command line */
1004 if (has_space)
1005 *p++='"';
1006 if (has_quote || has_space) {
1007 bcount=0;
1008 a=*arg;
1009 while (*a!='\0') {
1010 if (*a=='\\') {
1011 *p++=*a;
1012 bcount++;
1013 } else {
1014 if (*a=='"') {
1015 int i;
1017 /* Double all the '\\' preceding this '"', plus one */
1018 for (i=0;i<=bcount;i++)
1019 *p++='\\';
1020 *p++='"';
1021 } else {
1022 *p++=*a;
1024 bcount=0;
1026 a++;
1028 } else {
1029 WCHAR* x = *arg;
1030 while ((*p=*x++)) p++;
1032 if (has_space) {
1033 int i;
1035 /* Double all the '\' preceding the closing quote */
1036 for (i=0;i<bcount;i++)
1037 *p++='\\';
1038 *p++='"';
1040 *p++=' ';
1042 if (p > rupp->CommandLine.Buffer)
1043 p--; /* remove last space */
1044 *p = '\0';
1046 return TRUE;
1050 /***********************************************************************
1051 * init_current_directory
1053 * Initialize the current directory from the Unix cwd or the parent info.
1055 static void init_current_directory( CURDIR *cur_dir )
1057 UNICODE_STRING dir_str;
1058 const char *pwd;
1059 char *cwd;
1060 int size;
1062 /* if we received a cur dir from the parent, try this first */
1064 if (cur_dir->DosPath.Length)
1066 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
1069 /* now try to get it from the Unix cwd */
1071 for (size = 256; ; size *= 2)
1073 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
1074 if (getcwd( cwd, size )) break;
1075 HeapFree( GetProcessHeap(), 0, cwd );
1076 if (errno == ERANGE) continue;
1077 cwd = NULL;
1078 break;
1081 /* try to use PWD if it is valid, so that we don't resolve symlinks */
1083 pwd = getenv( "PWD" );
1084 if (cwd)
1086 struct stat st1, st2;
1088 if (!pwd || stat( pwd, &st1 ) == -1 ||
1089 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
1090 pwd = cwd;
1093 if (pwd)
1095 ANSI_STRING unix_name;
1096 UNICODE_STRING nt_name;
1097 RtlInitAnsiString( &unix_name, pwd );
1098 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
1100 UNICODE_STRING dos_path;
1101 /* skip the \??\ prefix, nt_name is 0 terminated */
1102 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
1103 RtlSetCurrentDirectory_U( &dos_path );
1104 RtlFreeUnicodeString( &nt_name );
1108 if (!cur_dir->DosPath.Length) /* still not initialized */
1110 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
1111 "starting in the Windows directory.\n", cwd ? cwd : "" );
1112 RtlInitUnicodeString( &dir_str, DIR_Windows );
1113 RtlSetCurrentDirectory_U( &dir_str );
1115 HeapFree( GetProcessHeap(), 0, cwd );
1117 done:
1118 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
1122 /***********************************************************************
1123 * init_windows_dirs
1125 static void init_windows_dirs(void)
1127 static const WCHAR default_syswow64W[] = {'C',':','\\','w','i','n','d','o','w','s',
1128 '\\','s','y','s','w','o','w','6','4',0};
1130 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
1132 DIR_SysWow64 = default_syswow64W;
1133 memcpy( winevdm, default_syswow64W, sizeof(default_syswow64W) - sizeof(WCHAR) );
1138 /***********************************************************************
1139 * start_wineboot
1141 * Start the wineboot process if necessary. Return the handles to wait on.
1143 static void start_wineboot( HANDLE handles[2] )
1145 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1147 handles[1] = 0;
1148 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1150 ERR( "failed to create wineboot event, expect trouble\n" );
1151 return;
1153 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1155 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1156 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1157 STARTUPINFOW si;
1158 PROCESS_INFORMATION pi;
1159 void *redir;
1160 WCHAR app[MAX_PATH];
1161 WCHAR cmdline[MAX_PATH + ARRAY_SIZE( wineboot ) + ARRAY_SIZE( args )];
1163 memset( &si, 0, sizeof(si) );
1164 si.cb = sizeof(si);
1165 si.dwFlags = STARTF_USESTDHANDLES;
1166 si.hStdInput = 0;
1167 si.hStdOutput = 0;
1168 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1170 GetSystemDirectoryW( app, MAX_PATH - ARRAY_SIZE( wineboot ));
1171 lstrcatW( app, wineboot );
1173 Wow64DisableWow64FsRedirection( &redir );
1174 strcpyW( cmdline, app );
1175 strcatW( cmdline, args );
1176 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1178 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1179 CloseHandle( pi.hThread );
1180 handles[1] = pi.hProcess;
1182 else
1184 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1185 CloseHandle( handles[0] );
1186 handles[0] = 0;
1188 Wow64RevertWow64FsRedirection( redir );
1193 #ifdef __i386__
1194 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1195 __ASM_GLOBAL_FUNC( call_process_entry,
1196 "pushl %ebp\n\t"
1197 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1198 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1199 "movl %esp,%ebp\n\t"
1200 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1201 "pushl 4(%ebp)\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1202 "pushl 4(%ebp)\n\t" /* Driller expects readable address at this offset */
1203 "pushl 4(%ebp)\n\t"
1204 "pushl 8(%ebp)\n\t"
1205 "call *12(%ebp)\n\t"
1206 "leave\n\t"
1207 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1208 __ASM_CFI(".cfi_same_value %ebp\n\t")
1209 "ret" )
1211 extern void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb ) DECLSPEC_HIDDEN;
1212 extern void WINAPI start_process_wrapper(void) DECLSPEC_HIDDEN;
1213 __ASM_GLOBAL_FUNC( start_process_wrapper,
1214 "pushl %ebp\n\t"
1215 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1216 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1217 "movl %esp,%ebp\n\t"
1218 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1219 "pushl %ebx\n\t" /* arg */
1220 "pushl %eax\n\t" /* entry */
1221 "call " __ASM_NAME("start_process") )
1222 #else
1223 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1225 return entry( peb );
1227 static void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb );
1228 #define start_process_wrapper start_process
1229 #endif
1231 /***********************************************************************
1232 * start_process
1234 * Startup routine of a new process. Runs on the new process stack.
1236 void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb )
1238 BOOL being_debugged;
1240 if (!entry)
1242 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1243 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1244 ExitThread( 1 );
1247 TRACE_(relay)( "\1Starting process %s (entryproc=%p)\n",
1248 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1250 __TRY
1252 if (!CheckRemoteDebuggerPresent( GetCurrentProcess(), &being_debugged ))
1253 being_debugged = FALSE;
1255 SetLastError( 0 ); /* clear error code */
1256 if (being_debugged) DbgBreakPoint();
1257 ExitThread( call_process_entry( peb, entry ));
1259 __EXCEPT(UnhandledExceptionFilter)
1261 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1263 __ENDTRY
1264 abort(); /* should not be reached */
1268 /***********************************************************************
1269 * set_process_name
1271 * Change the process name in the ps output.
1273 static void set_process_name( int argc, char *argv[] )
1275 BOOL shift_strings;
1276 char *p, *name;
1277 int i;
1279 #ifdef HAVE_SETPROCTITLE
1280 setproctitle("-%s", argv[1]);
1281 shift_strings = FALSE;
1282 #else
1283 p = argv[0];
1285 shift_strings = (argc >= 2);
1286 for (i = 1; i < argc; i++)
1288 p += strlen(p) + 1;
1289 if (p != argv[i])
1291 shift_strings = FALSE;
1292 break;
1295 #endif
1297 if (shift_strings)
1299 int offset = argv[1] - argv[0];
1300 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1301 memmove( argv[0], argv[1], end - argv[1] );
1302 memset( end - offset, 0, offset );
1303 for (i = 1; i < argc; i++)
1304 argv[i-1] = argv[i] - offset;
1305 argv[i-1] = NULL;
1307 else
1309 /* remove argv[0] */
1310 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1313 name = argv[0];
1314 if ((p = strrchr( name, '\\' ))) name = p + 1;
1315 if ((p = strrchr( name, '/' ))) name = p + 1;
1317 #if defined(HAVE_SETPROGNAME)
1318 setprogname( name );
1319 #endif
1321 #ifdef HAVE_PRCTL
1322 #ifndef PR_SET_NAME
1323 # define PR_SET_NAME 15
1324 #endif
1325 prctl( PR_SET_NAME, name );
1326 #endif /* HAVE_PRCTL */
1330 /***********************************************************************
1331 * __wine_kernel_init
1333 * Wine initialisation: load and start the main exe file.
1335 void * CDECL __wine_kernel_init(void)
1337 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1338 static const WCHAR dotW[] = {'.',0};
1340 WCHAR *p, main_exe_name[MAX_PATH+1];
1341 PEB *peb = NtCurrentTeb()->Peb;
1342 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1343 HANDLE boot_events[2];
1344 BOOL got_environment = TRUE;
1346 /* Initialize everything */
1348 setbuf(stdout,NULL);
1349 setbuf(stderr,NULL);
1350 kernel32_handle = GetModuleHandleW(kernel32W);
1351 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1352 RtlSetUnhandledExceptionFilter( UnhandledExceptionFilter );
1354 LOCALE_Init();
1356 if (!params->Environment)
1358 /* Copy the parent environment */
1359 if (!build_initial_environment()) exit(1);
1361 /* convert old configuration to new format */
1362 convert_old_config();
1364 got_environment = set_registry_environment( FALSE );
1365 set_additional_environment();
1368 init_windows_dirs();
1369 init_current_directory( &params->CurrentDirectory );
1371 set_process_name( __wine_main_argc, __wine_main_argv );
1372 set_library_wargv( __wine_main_argv );
1373 boot_events[0] = boot_events[1] = 0;
1375 if (peb->ProcessParameters->ImagePathName.Buffer)
1377 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1379 else
1381 BOOL is_64bit;
1383 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1384 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &is_64bit ))
1386 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1387 ExitProcess( GetLastError() );
1389 update_library_argv0( main_exe_name );
1390 if (!build_command_line( __wine_main_wargv )) goto error;
1391 start_wineboot( boot_events );
1394 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1395 p = strrchrW( main_exe_name, '.' );
1396 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1398 TRACE( "starting process name=%s argv[0]=%s\n",
1399 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1401 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1402 MODULE_get_dll_load_path( main_exe_name, -1 ));
1404 if (boot_events[0])
1406 DWORD timeout = 2 * 60 * 1000, count = 1;
1408 if (boot_events[1]) count++;
1409 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1410 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1411 ERR( "boot event wait timed out\n" );
1412 CloseHandle( boot_events[0] );
1413 if (boot_events[1]) CloseHandle( boot_events[1] );
1414 /* reload environment now that wineboot has run */
1415 set_registry_environment( got_environment );
1416 set_additional_environment();
1418 set_wow64_environment();
1420 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1422 DWORD_PTR args[1];
1423 WCHAR msgW[1024];
1424 char msg[1024];
1425 DWORD error = GetLastError();
1427 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1428 if (error == ERROR_BAD_EXE_FORMAT ||
1429 error == ERROR_INVALID_ADDRESS ||
1430 error == ERROR_NOT_ENOUGH_MEMORY)
1432 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1433 /* if we get back here, it failed */
1435 else if (error == ERROR_MOD_NOT_FOUND)
1437 if (!strcmpiW( main_exe_name, winevdm ) && __wine_main_argc > 3)
1439 /* args 1 and 2 are --app-name full_path */
1440 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1441 debugstr_w(__wine_main_wargv[3]) );
1442 ExitProcess( ERROR_BAD_EXE_FORMAT );
1444 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1445 ExitProcess( ERROR_FILE_NOT_FOUND );
1447 args[0] = (DWORD_PTR)main_exe_name;
1448 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1449 NULL, error, 0, msgW, ARRAY_SIZE( msgW ), (__ms_va_list *)args );
1450 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1451 MESSAGE( "wine: %s", msg );
1452 ExitProcess( error );
1455 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1457 return start_process_wrapper;
1459 error:
1460 ExitProcess( GetLastError() );
1464 /***********************************************************************
1465 * build_argv
1467 * Build an argv array from a command-line.
1468 * 'reserved' is the number of args to reserve before the first one.
1470 static char **build_argv( const UNICODE_STRING *cmdlineW, int reserved )
1472 int argc;
1473 char** argv;
1474 char *arg,*s,*d,*cmdline;
1475 int in_quotes,bcount,len;
1477 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW->Buffer, cmdlineW->Length / sizeof(WCHAR),
1478 NULL, 0, NULL, NULL );
1479 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1480 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW->Buffer, cmdlineW->Length / sizeof(WCHAR),
1481 cmdline, len, NULL, NULL );
1482 cmdline[len++] = 0;
1484 argc=reserved+1;
1485 bcount=0;
1486 in_quotes=0;
1487 s=cmdline;
1488 while (1) {
1489 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1490 /* space */
1491 argc++;
1492 /* skip the remaining spaces */
1493 while (*s==' ' || *s=='\t') {
1494 s++;
1496 if (*s=='\0')
1497 break;
1498 bcount=0;
1499 continue;
1500 } else if (*s=='\\') {
1501 /* '\', count them */
1502 bcount++;
1503 } else if ((*s=='"') && ((bcount & 1)==0)) {
1504 if (in_quotes && s[1] == '"') {
1505 s++;
1506 } else {
1507 /* unescaped '"' */
1508 in_quotes=!in_quotes;
1509 bcount=0;
1511 } else {
1512 /* a regular character */
1513 bcount=0;
1515 s++;
1517 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1519 HeapFree( GetProcessHeap(), 0, cmdline );
1520 return NULL;
1523 arg = d = s = (char *)(argv + argc);
1524 memcpy( d, cmdline, len );
1525 bcount=0;
1526 in_quotes=0;
1527 argc=reserved;
1528 while (*s) {
1529 if ((*s==' ' || *s=='\t') && !in_quotes) {
1530 /* Close the argument and copy it */
1531 *d=0;
1532 argv[argc++]=arg;
1534 /* skip the remaining spaces */
1535 do {
1536 s++;
1537 } while (*s==' ' || *s=='\t');
1539 /* Start with a new argument */
1540 arg=d=s;
1541 bcount=0;
1542 } else if (*s=='\\') {
1543 /* '\\' */
1544 *d++=*s++;
1545 bcount++;
1546 } else if (*s=='"') {
1547 /* '"' */
1548 if ((bcount & 1)==0) {
1549 /* Preceded by an even number of '\', this is half that
1550 * number of '\', plus a '"' which we discard.
1552 d-=bcount/2;
1553 s++;
1554 if(in_quotes && *s == '"') {
1555 *d++='"';
1556 s++;
1557 } else {
1558 in_quotes=!in_quotes;
1560 } else {
1561 /* Preceded by an odd number of '\', this is half that
1562 * number of '\' followed by a '"'
1564 d=d-bcount/2-1;
1565 *d++='"';
1566 s++;
1568 bcount=0;
1569 } else {
1570 /* a regular character */
1571 *d++=*s++;
1572 bcount=0;
1575 if (*arg) {
1576 *d='\0';
1577 argv[argc++]=arg;
1579 argv[argc]=NULL;
1581 HeapFree( GetProcessHeap(), 0, cmdline );
1582 return argv;
1586 /***********************************************************************
1587 * build_envp
1589 * Build the environment of a new child process.
1591 static char **build_envp( const WCHAR *envW )
1593 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1595 const WCHAR *end;
1596 char **envp;
1597 char *env, *p;
1598 int count = 1, length;
1599 unsigned int i;
1601 for (end = envW; *end; count++) end += strlenW(end) + 1;
1602 end++;
1603 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1604 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1605 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1607 for (p = env; *p; p += strlen(p) + 1)
1608 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1610 for (i = 0; i < ARRAY_SIZE( unix_vars ); i++)
1612 if (!(p = getenv(unix_vars[i]))) continue;
1613 length += strlen(unix_vars[i]) + strlen(p) + 2;
1614 count++;
1617 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1619 char **envptr = envp;
1620 char *dst = (char *)(envp + count);
1622 /* some variables must not be modified, so we get them directly from the unix env */
1623 for (i = 0; i < ARRAY_SIZE( unix_vars ); i++)
1625 if (!(p = getenv(unix_vars[i]))) continue;
1626 *envptr++ = strcpy( dst, unix_vars[i] );
1627 strcat( dst, "=" );
1628 strcat( dst, p );
1629 dst += strlen(dst) + 1;
1632 /* now put the Windows environment strings */
1633 for (p = env; *p; p += strlen(p) + 1)
1635 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1636 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1637 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1638 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1639 if (is_special_env_var( p )) /* prefix it with "WINE" */
1641 *envptr++ = strcpy( dst, "WINE" );
1642 strcat( dst, p );
1644 else
1646 *envptr++ = strcpy( dst, p );
1648 dst += strlen(dst) + 1;
1650 *envptr = 0;
1652 HeapFree( GetProcessHeap(), 0, env );
1653 return envp;
1657 /***********************************************************************
1658 * fork_and_exec
1660 * Fork and exec a new Unix binary, checking for errors.
1662 static int fork_and_exec( const RTL_USER_PROCESS_PARAMETERS *params, const char *newdir )
1664 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1665 int pid, err;
1666 char *filename, **argv, **envp;
1668 if (!(filename = wine_get_unix_file_name( params->ImagePathName.Buffer ))) return -1;
1670 #ifdef HAVE_PIPE2
1671 if (pipe2( fd, O_CLOEXEC ) == -1)
1672 #endif
1674 if (pipe(fd) == -1)
1676 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1677 HeapFree( GetProcessHeap(), 0, filename );
1678 return -1;
1680 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1681 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1684 wine_server_handle_to_fd( params->hStdInput, FILE_READ_DATA, &stdin_fd, NULL );
1685 wine_server_handle_to_fd( params->hStdOutput, FILE_WRITE_DATA, &stdout_fd, NULL );
1686 wine_server_handle_to_fd( params->hStdError, FILE_WRITE_DATA, &stderr_fd, NULL );
1688 argv = build_argv( &params->CommandLine, 0 );
1689 envp = build_envp( params->Environment );
1691 if (!(pid = fork())) /* child */
1693 if (!(pid = fork())) /* grandchild */
1695 close( fd[0] );
1697 if (params->ConsoleFlags || params->ConsoleHandle == KERNEL32_CONSOLE_ALLOC ||
1698 (params->hStdInput == INVALID_HANDLE_VALUE && params->hStdOutput == INVALID_HANDLE_VALUE))
1700 int nullfd = open( "/dev/null", O_RDWR );
1701 setsid();
1702 /* close stdin and stdout */
1703 if (nullfd != -1)
1705 dup2( nullfd, 0 );
1706 dup2( nullfd, 1 );
1707 close( nullfd );
1710 else
1712 if (stdin_fd != -1)
1714 dup2( stdin_fd, 0 );
1715 close( stdin_fd );
1717 if (stdout_fd != -1)
1719 dup2( stdout_fd, 1 );
1720 close( stdout_fd );
1722 if (stderr_fd != -1)
1724 dup2( stderr_fd, 2 );
1725 close( stderr_fd );
1729 /* Reset signals that we previously set to SIG_IGN */
1730 signal( SIGPIPE, SIG_DFL );
1732 if (newdir) chdir(newdir);
1734 if (argv && envp) execve( filename, argv, envp );
1737 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1739 err = errno;
1740 write( fd[1], &err, sizeof(err) );
1741 _exit(1);
1744 _exit(0); /* child if fork succeeded */
1746 HeapFree( GetProcessHeap(), 0, argv );
1747 HeapFree( GetProcessHeap(), 0, envp );
1748 HeapFree( GetProcessHeap(), 0, filename );
1749 if (stdin_fd != -1) close( stdin_fd );
1750 if (stdout_fd != -1) close( stdout_fd );
1751 if (stderr_fd != -1) close( stderr_fd );
1752 close( fd[1] );
1753 if (pid != -1)
1755 /* reap child */
1756 do {
1757 err = waitpid(pid, NULL, 0);
1758 } while (err < 0 && errno == EINTR);
1760 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1762 errno = err;
1763 pid = -1;
1766 if (pid == -1) FILE_SetDosError();
1767 close( fd[0] );
1768 return pid;
1772 static inline const WCHAR *get_params_string( const RTL_USER_PROCESS_PARAMETERS *params,
1773 const UNICODE_STRING *str )
1775 if (params->Flags & PROCESS_PARAMS_FLAG_NORMALIZED) return str->Buffer;
1776 return (const WCHAR *)((const char *)params + (UINT_PTR)str->Buffer);
1779 static inline DWORD append_string( void **ptr, const RTL_USER_PROCESS_PARAMETERS *params,
1780 const UNICODE_STRING *str )
1782 const WCHAR *buffer = get_params_string( params, str );
1783 memcpy( *ptr, buffer, str->Length );
1784 *ptr = (WCHAR *)*ptr + str->Length / sizeof(WCHAR);
1785 return str->Length;
1788 /***********************************************************************
1789 * create_startup_info
1791 static startup_info_t *create_startup_info( const RTL_USER_PROCESS_PARAMETERS *params, DWORD *info_size )
1793 startup_info_t *info;
1794 DWORD size;
1795 void *ptr;
1797 size = sizeof(*info);
1798 size += params->CurrentDirectory.DosPath.Length;
1799 size += params->DllPath.Length;
1800 size += params->ImagePathName.Length;
1801 size += params->CommandLine.Length;
1802 size += params->WindowTitle.Length;
1803 size += params->Desktop.Length;
1804 size += params->ShellInfo.Length;
1805 size += params->RuntimeInfo.Length;
1806 size = (size + 1) & ~1;
1807 *info_size = size;
1809 if (!(info = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) return NULL;
1811 info->console_flags = params->ConsoleFlags;
1812 info->console = wine_server_obj_handle( params->ConsoleHandle );
1813 info->hstdin = wine_server_obj_handle( params->hStdInput );
1814 info->hstdout = wine_server_obj_handle( params->hStdOutput );
1815 info->hstderr = wine_server_obj_handle( params->hStdError );
1816 info->x = params->dwX;
1817 info->y = params->dwY;
1818 info->xsize = params->dwXSize;
1819 info->ysize = params->dwYSize;
1820 info->xchars = params->dwXCountChars;
1821 info->ychars = params->dwYCountChars;
1822 info->attribute = params->dwFillAttribute;
1823 info->flags = params->dwFlags;
1824 info->show = params->wShowWindow;
1826 ptr = info + 1;
1827 info->curdir_len = append_string( &ptr, params, &params->CurrentDirectory.DosPath );
1828 info->dllpath_len = append_string( &ptr, params, &params->DllPath );
1829 info->imagepath_len = append_string( &ptr, params, &params->ImagePathName );
1830 info->cmdline_len = append_string( &ptr, params, &params->CommandLine );
1831 info->title_len = append_string( &ptr, params, &params->WindowTitle );
1832 info->desktop_len = append_string( &ptr, params, &params->Desktop );
1833 info->shellinfo_len = append_string( &ptr, params, &params->ShellInfo );
1834 info->runtime_len = append_string( &ptr, params, &params->RuntimeInfo );
1835 return info;
1839 /***********************************************************************
1840 * create_process_params
1842 static RTL_USER_PROCESS_PARAMETERS *create_process_params( LPCWSTR filename, LPCWSTR cmdline,
1843 LPCWSTR cur_dir, void *env, DWORD flags,
1844 const STARTUPINFOW *startup )
1846 RTL_USER_PROCESS_PARAMETERS *params;
1847 UNICODE_STRING imageW, curdirW, cmdlineW, titleW, desktopW, runtimeW, newdirW;
1848 WCHAR imagepath[MAX_PATH];
1849 WCHAR *envW = env;
1851 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1852 lstrcpynW( imagepath, filename, MAX_PATH );
1853 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1854 lstrcpynW( imagepath, filename, MAX_PATH );
1856 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1858 char *e = env;
1859 DWORD lenW;
1861 while (*e) e += strlen(e) + 1;
1862 e++; /* final null */
1863 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char *)env, NULL, 0 );
1864 if ((envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
1865 MultiByteToWideChar( CP_ACP, 0, env, e - (char *)env, envW, lenW );
1868 newdirW.Buffer = NULL;
1869 if (cur_dir)
1871 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdirW, NULL, NULL ))
1872 cur_dir = newdirW.Buffer + 4; /* skip \??\ prefix */
1873 else
1874 cur_dir = NULL;
1876 RtlInitUnicodeString( &imageW, imagepath );
1877 RtlInitUnicodeString( &curdirW, cur_dir );
1878 RtlInitUnicodeString( &cmdlineW, cmdline );
1879 RtlInitUnicodeString( &titleW, startup->lpTitle ? startup->lpTitle : imagepath );
1880 RtlInitUnicodeString( &desktopW, startup->lpDesktop );
1881 runtimeW.Buffer = (WCHAR *)startup->lpReserved2;
1882 runtimeW.Length = runtimeW.MaximumLength = startup->cbReserved2;
1883 if (RtlCreateProcessParametersEx( &params, &imageW, NULL, cur_dir ? &curdirW : NULL,
1884 &cmdlineW, envW, &titleW, &desktopW,
1885 NULL, &runtimeW, PROCESS_PARAMS_FLAG_NORMALIZED ))
1887 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1888 return NULL;
1891 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1892 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = KERNEL32_CONSOLE_ALLOC;
1894 if (startup->dwFlags & STARTF_USESTDHANDLES)
1896 params->hStdInput = startup->hStdInput;
1897 params->hStdOutput = startup->hStdOutput;
1898 params->hStdError = startup->hStdError;
1900 else if (flags & DETACHED_PROCESS)
1902 params->hStdInput = INVALID_HANDLE_VALUE;
1903 params->hStdOutput = INVALID_HANDLE_VALUE;
1904 params->hStdError = INVALID_HANDLE_VALUE;
1906 else
1908 params->hStdInput = NtCurrentTeb()->Peb->ProcessParameters->hStdInput;
1909 params->hStdOutput = NtCurrentTeb()->Peb->ProcessParameters->hStdOutput;
1910 params->hStdError = NtCurrentTeb()->Peb->ProcessParameters->hStdError;
1913 if (flags & CREATE_NEW_CONSOLE)
1915 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1916 if (is_console_handle(params->hStdInput)) params->hStdInput = INVALID_HANDLE_VALUE;
1917 if (is_console_handle(params->hStdOutput)) params->hStdOutput = INVALID_HANDLE_VALUE;
1918 if (is_console_handle(params->hStdError)) params->hStdError = INVALID_HANDLE_VALUE;
1920 else
1922 if (is_console_handle(params->hStdInput)) params->hStdInput = (HANDLE)((UINT_PTR)params->hStdInput & ~3);
1923 if (is_console_handle(params->hStdOutput)) params->hStdOutput = (HANDLE)((UINT_PTR)params->hStdOutput & ~3);
1924 if (is_console_handle(params->hStdError)) params->hStdError = (HANDLE)((UINT_PTR)params->hStdError & ~3);
1927 params->dwX = startup->dwX;
1928 params->dwY = startup->dwY;
1929 params->dwXSize = startup->dwXSize;
1930 params->dwYSize = startup->dwYSize;
1931 params->dwXCountChars = startup->dwXCountChars;
1932 params->dwYCountChars = startup->dwYCountChars;
1933 params->dwFillAttribute = startup->dwFillAttribute;
1934 params->dwFlags = startup->dwFlags;
1935 params->wShowWindow = startup->wShowWindow;
1937 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1938 return params;
1941 /***********************************************************************
1942 * get_alternate_loader
1944 * Get the name of the alternate (32 or 64 bit) Wine loader.
1946 static const char *get_alternate_loader( char **ret_env )
1948 char *env;
1949 const char *loader = NULL;
1950 const char *loader_env = getenv( "WINELOADER" );
1952 *ret_env = NULL;
1954 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "loader/wine64";
1956 if (loader_env)
1958 int len = strlen( loader_env );
1959 if (!is_win64)
1961 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1962 strcpy( env, "WINELOADER=" );
1963 strcat( env, loader_env );
1964 strcat( env, "64" );
1966 else
1968 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1969 strcpy( env, "WINELOADER=" );
1970 strcat( env, loader_env );
1971 len += sizeof("WINELOADER=") - 1;
1972 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1974 if (!loader)
1976 if ((loader = strrchr( env, '/' ))) loader++;
1977 else loader = env;
1979 *ret_env = env;
1981 if (!loader) loader = is_win64 ? "wine" : "wine64";
1982 return loader;
1985 #ifdef __APPLE__
1986 /***********************************************************************
1987 * terminate_main_thread
1989 * On some versions of Mac OS X, the execve system call fails with
1990 * ENOTSUP if the process has multiple threads. Wine is always multi-
1991 * threaded on Mac OS X because it specifically reserves the main thread
1992 * for use by the system frameworks (see apple_main_thread() in
1993 * libs/wine/loader.c). So, when we need to exec without first forking,
1994 * we need to terminate the main thread first. We do this by installing
1995 * a custom run loop source onto the main run loop and signaling it.
1996 * The source's "perform" callback is pthread_exit and it will be
1997 * executed on the main thread, terminating it.
1999 * Returns TRUE if there's still hope the main thread has terminated or
2000 * will soon. Return FALSE if we've given up.
2002 static BOOL terminate_main_thread(void)
2004 static int delayms;
2006 if (!delayms)
2008 CFRunLoopSourceContext source_context = { 0 };
2009 CFRunLoopSourceRef source;
2011 source_context.perform = pthread_exit;
2012 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
2013 return FALSE;
2015 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
2016 CFRunLoopSourceSignal( source );
2017 CFRunLoopWakeUp( CFRunLoopGetMain() );
2018 CFRelease( source );
2020 delayms = 20;
2023 if (delayms > 1000)
2024 return FALSE;
2026 usleep(delayms * 1000);
2027 delayms *= 2;
2029 return TRUE;
2031 #endif
2034 /***********************************************************************
2035 * set_stdio_fd
2037 static void set_stdio_fd( int stdin_fd, int stdout_fd )
2039 int fd = -1;
2041 if (stdin_fd == -1 || stdout_fd == -1)
2043 fd = open( "/dev/null", O_RDWR );
2044 if (stdin_fd == -1) stdin_fd = fd;
2045 if (stdout_fd == -1) stdout_fd = fd;
2048 dup2( stdin_fd, 0 );
2049 dup2( stdout_fd, 1 );
2050 if (fd != -1) close( fd );
2054 /***********************************************************************
2055 * spawn_loader
2057 static pid_t spawn_loader( const RTL_USER_PROCESS_PARAMETERS *params, int socketfd,
2058 const char *unixdir, char *winedebug, const pe_image_info_t *pe_info )
2060 pid_t pid;
2061 int stdin_fd = -1, stdout_fd = -1;
2062 char *wineloader = NULL;
2063 const char *loader = NULL;
2064 char **argv;
2066 argv = build_argv( &params->CommandLine, 1 );
2068 if (!is_win64 ^ !is_64bit_arch( pe_info->cpu ))
2069 loader = get_alternate_loader( &wineloader );
2071 wine_server_handle_to_fd( params->hStdInput, FILE_READ_DATA, &stdin_fd, NULL );
2072 wine_server_handle_to_fd( params->hStdOutput, FILE_WRITE_DATA, &stdout_fd, NULL );
2074 if (!(pid = fork())) /* child */
2076 if (!(pid = fork())) /* grandchild */
2078 char preloader_reserve[64], socket_env[64];
2079 ULONGLONG res_start = pe_info->base;
2080 ULONGLONG res_end = pe_info->base + pe_info->map_size;
2082 if (params->ConsoleFlags || params->ConsoleHandle == KERNEL32_CONSOLE_ALLOC ||
2083 (params->hStdInput == INVALID_HANDLE_VALUE && params->hStdOutput == INVALID_HANDLE_VALUE))
2085 setsid();
2086 set_stdio_fd( -1, -1 ); /* close stdin and stdout */
2088 else set_stdio_fd( stdin_fd, stdout_fd );
2090 if (stdin_fd != -1) close( stdin_fd );
2091 if (stdout_fd != -1) close( stdout_fd );
2093 /* Reset signals that we previously set to SIG_IGN */
2094 signal( SIGPIPE, SIG_DFL );
2096 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
2097 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
2098 (ULONG)(res_start >> 32), (ULONG)res_start, (ULONG)(res_end >> 32), (ULONG)res_end );
2100 putenv( preloader_reserve );
2101 putenv( socket_env );
2102 if (winedebug) putenv( winedebug );
2103 if (wineloader) putenv( wineloader );
2104 if (unixdir) chdir(unixdir);
2106 if (argv) wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
2107 _exit(1);
2110 _exit(pid == -1);
2113 if (pid != -1)
2115 /* reap child */
2116 pid_t wret;
2117 do {
2118 wret = waitpid(pid, NULL, 0);
2119 } while (wret < 0 && errno == EINTR);
2122 if (stdin_fd != -1) close( stdin_fd );
2123 if (stdout_fd != -1) close( stdout_fd );
2124 HeapFree( GetProcessHeap(), 0, wineloader );
2125 HeapFree( GetProcessHeap(), 0, argv );
2126 return pid;
2129 /***********************************************************************
2130 * exec_loader
2132 static NTSTATUS exec_loader( const RTL_USER_PROCESS_PARAMETERS *params, int socketfd,
2133 const pe_image_info_t *pe_info )
2135 char *wineloader = NULL;
2136 const char *loader = NULL;
2137 char **argv;
2138 char preloader_reserve[64], socket_env[64];
2139 ULONGLONG res_start = pe_info->base;
2140 ULONGLONG res_end = pe_info->base + pe_info->map_size;
2142 if (!(argv = build_argv( &params->CommandLine, 1 ))) return STATUS_NO_MEMORY;
2144 if (!is_win64 ^ !is_64bit_arch( pe_info->cpu ))
2145 loader = get_alternate_loader( &wineloader );
2147 /* Reset signals that we previously set to SIG_IGN */
2148 signal( SIGPIPE, SIG_DFL );
2150 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
2151 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
2152 (ULONG)(res_start >> 32), (ULONG)res_start, (ULONG)(res_end >> 32), (ULONG)res_end );
2154 putenv( preloader_reserve );
2155 putenv( socket_env );
2156 if (wineloader) putenv( wineloader );
2160 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
2162 #ifdef __APPLE__
2163 while (errno == ENOTSUP && terminate_main_thread());
2164 #else
2165 while (0);
2166 #endif
2168 HeapFree( GetProcessHeap(), 0, wineloader );
2169 HeapFree( GetProcessHeap(), 0, argv );
2170 return STATUS_INVALID_IMAGE_FORMAT;
2173 /* creates a struct security_descriptor and contained information in one contiguous piece of memory */
2174 static NTSTATUS alloc_object_attributes( const SECURITY_ATTRIBUTES *attr, struct object_attributes **ret,
2175 data_size_t *ret_len )
2177 unsigned int len = sizeof(**ret);
2178 PSID owner = NULL, group = NULL;
2179 ACL *dacl, *sacl;
2180 BOOLEAN dacl_present, sacl_present, defaulted;
2181 PSECURITY_DESCRIPTOR sd = NULL;
2182 NTSTATUS status;
2184 *ret = NULL;
2185 *ret_len = 0;
2187 if (attr) sd = attr->lpSecurityDescriptor;
2189 if (sd)
2191 len += sizeof(struct security_descriptor);
2193 if ((status = RtlGetOwnerSecurityDescriptor( sd, &owner, &defaulted ))) return status;
2194 if ((status = RtlGetGroupSecurityDescriptor( sd, &group, &defaulted ))) return status;
2195 if ((status = RtlGetSaclSecurityDescriptor( sd, &sacl_present, &sacl, &defaulted ))) return status;
2196 if ((status = RtlGetDaclSecurityDescriptor( sd, &dacl_present, &dacl, &defaulted ))) return status;
2197 if (owner) len += RtlLengthSid( owner );
2198 if (group) len += RtlLengthSid( group );
2199 if (sacl_present && sacl) len += sacl->AclSize;
2200 if (dacl_present && dacl) len += dacl->AclSize;
2203 len = (len + 3) & ~3; /* DWORD-align the entire structure */
2205 *ret = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, len );
2206 if (!*ret) return STATUS_NO_MEMORY;
2208 (*ret)->attributes = (attr && attr->bInheritHandle) ? OBJ_INHERIT : 0;
2210 if (sd)
2212 struct security_descriptor *descr = (struct security_descriptor *)(*ret + 1);
2213 unsigned char *ptr = (unsigned char *)(descr + 1);
2215 descr->control = ((SECURITY_DESCRIPTOR *)sd)->Control & ~SE_SELF_RELATIVE;
2216 if (owner) descr->owner_len = RtlLengthSid( owner );
2217 if (group) descr->group_len = RtlLengthSid( group );
2218 if (sacl_present && sacl) descr->sacl_len = sacl->AclSize;
2219 if (dacl_present && dacl) descr->dacl_len = dacl->AclSize;
2221 memcpy( ptr, owner, descr->owner_len );
2222 ptr += descr->owner_len;
2223 memcpy( ptr, group, descr->group_len );
2224 ptr += descr->group_len;
2225 memcpy( ptr, sacl, descr->sacl_len );
2226 ptr += descr->sacl_len;
2227 memcpy( ptr, dacl, descr->dacl_len );
2228 (*ret)->sd_len = (sizeof(*descr) + descr->owner_len + descr->group_len + descr->sacl_len +
2229 descr->dacl_len + sizeof(WCHAR) - 1) & ~(sizeof(WCHAR) - 1);
2231 *ret_len = len;
2232 return STATUS_SUCCESS;
2235 /***********************************************************************
2236 * replace_process
2238 * Replace the existing process by exec'ing a new one.
2240 static BOOL replace_process( HANDLE handle, const RTL_USER_PROCESS_PARAMETERS *params,
2241 const pe_image_info_t *pe_info )
2243 NTSTATUS status;
2244 int socketfd[2];
2246 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2248 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2249 return FALSE;
2251 #ifdef SO_PASSCRED
2252 else
2254 int enable = 1;
2255 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2257 #endif
2258 wine_server_send_fd( socketfd[1] );
2259 close( socketfd[1] );
2261 SERVER_START_REQ( exec_process )
2263 req->socket_fd = socketfd[1];
2264 req->exe_file = wine_server_obj_handle( handle );
2265 req->cpu = pe_info->cpu;
2266 status = wine_server_call( req );
2268 SERVER_END_REQ;
2270 switch (status)
2272 case STATUS_INVALID_IMAGE_WIN_64:
2273 ERR( "64-bit application %s not supported in 32-bit prefix\n",
2274 debugstr_w( params->ImagePathName.Buffer ));
2275 break;
2276 case STATUS_INVALID_IMAGE_FORMAT:
2277 ERR( "%s not supported on this installation (%s binary)\n",
2278 debugstr_w( params->ImagePathName.Buffer ), cpu_names[pe_info->cpu] );
2279 break;
2280 case STATUS_SUCCESS:
2281 status = exec_loader( params, socketfd[0], pe_info );
2282 break;
2284 close( socketfd[0] );
2285 SetLastError( RtlNtStatusToDosError( status ));
2286 return FALSE;
2290 /***********************************************************************
2291 * create_process
2293 * Create a new process. If hFile is a valid handle we have an exe
2294 * file, otherwise it is a Winelib app.
2296 static BOOL create_process( HANDLE hFile, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2297 BOOL inherit, DWORD flags, const RTL_USER_PROCESS_PARAMETERS *params,
2298 LPPROCESS_INFORMATION info, LPCSTR unixdir, const pe_image_info_t *pe_info )
2300 NTSTATUS status;
2301 BOOL success = FALSE;
2302 HANDLE process_info, process_handle = 0;
2303 struct object_attributes *objattr;
2304 data_size_t attr_len;
2305 WCHAR *env_end;
2306 char *winedebug = NULL;
2307 startup_info_t *startup_info;
2308 DWORD startup_info_size;
2309 int socketfd[2];
2310 pid_t pid;
2311 int err;
2313 /* create the socket for the new process */
2315 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2317 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2318 return FALSE;
2320 #ifdef SO_PASSCRED
2321 else
2323 int enable = 1;
2324 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2326 #endif
2328 if (!(startup_info = create_startup_info( params, &startup_info_size )))
2330 close( socketfd[0] );
2331 close( socketfd[1] );
2332 return FALSE;
2334 env_end = params->Environment;
2335 while (*env_end)
2337 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2338 if (!winedebug && !strncmpW( env_end, WINEDEBUG, ARRAY_SIZE( WINEDEBUG ) - 1 ))
2340 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2341 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2342 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2344 env_end += strlenW(env_end) + 1;
2346 env_end++;
2348 wine_server_send_fd( socketfd[1] );
2349 close( socketfd[1] );
2351 /* create the process on the server side */
2353 alloc_object_attributes( psa, &objattr, &attr_len );
2354 SERVER_START_REQ( new_process )
2356 req->inherit_all = inherit;
2357 req->create_flags = flags;
2358 req->socket_fd = socketfd[1];
2359 req->exe_file = wine_server_obj_handle( hFile );
2360 req->access = PROCESS_ALL_ACCESS;
2361 req->cpu = pe_info->cpu;
2362 req->info_size = startup_info_size;
2363 wine_server_add_data( req, objattr, attr_len );
2364 wine_server_add_data( req, startup_info, startup_info_size );
2365 wine_server_add_data( req, params->Environment, (env_end - params->Environment) * sizeof(WCHAR) );
2366 if (!(status = wine_server_call( req )))
2368 info->dwProcessId = (DWORD)reply->pid;
2369 process_handle = wine_server_ptr_handle( reply->handle );
2371 process_info = wine_server_ptr_handle( reply->info );
2373 SERVER_END_REQ;
2374 HeapFree( GetProcessHeap(), 0, objattr );
2376 if (!status)
2378 alloc_object_attributes( tsa, &objattr, &attr_len );
2379 SERVER_START_REQ( new_thread )
2381 req->process = wine_server_obj_handle( process_handle );
2382 req->access = THREAD_ALL_ACCESS;
2383 req->suspend = !!(flags & CREATE_SUSPENDED);
2384 req->request_fd = -1;
2385 wine_server_add_data( req, objattr, attr_len );
2386 if (!(status = wine_server_call( req )))
2388 info->hProcess = process_handle;
2389 info->hThread = wine_server_ptr_handle( reply->handle );
2390 info->dwThreadId = reply->tid;
2393 SERVER_END_REQ;
2394 HeapFree( GetProcessHeap(), 0, objattr );
2397 if (status)
2399 switch (status)
2401 case STATUS_INVALID_IMAGE_WIN_64:
2402 ERR( "64-bit application %s not supported in 32-bit prefix\n",
2403 debugstr_w( params->ImagePathName.Buffer ));
2404 break;
2405 case STATUS_INVALID_IMAGE_FORMAT:
2406 ERR( "%s not supported on this installation (%s binary)\n",
2407 debugstr_w( params->ImagePathName.Buffer ), cpu_names[pe_info->cpu] );
2408 break;
2410 close( socketfd[0] );
2411 CloseHandle( process_handle );
2412 HeapFree( GetProcessHeap(), 0, startup_info );
2413 HeapFree( GetProcessHeap(), 0, winedebug );
2414 SetLastError( RtlNtStatusToDosError( status ));
2415 return FALSE;
2418 HeapFree( GetProcessHeap(), 0, startup_info );
2420 /* create the child process */
2422 pid = spawn_loader( params, socketfd[0], unixdir, winedebug, pe_info );
2424 close( socketfd[0] );
2425 HeapFree( GetProcessHeap(), 0, winedebug );
2426 if (pid == -1)
2428 FILE_SetDosError();
2429 goto error;
2432 /* wait for the new process info to be ready */
2434 WaitForSingleObject( process_info, INFINITE );
2435 SERVER_START_REQ( get_new_process_info )
2437 req->info = wine_server_obj_handle( process_info );
2438 wine_server_call( req );
2439 success = reply->success;
2440 err = reply->exit_code;
2442 SERVER_END_REQ;
2444 if (!success)
2446 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2447 goto error;
2449 CloseHandle( process_info );
2450 return success;
2452 error:
2453 CloseHandle( process_info );
2454 CloseHandle( info->hProcess );
2455 CloseHandle( info->hThread );
2456 info->hProcess = info->hThread = 0;
2457 info->dwProcessId = info->dwThreadId = 0;
2458 return FALSE;
2462 /***********************************************************************
2463 * get_vdm_params
2465 * Build the parameters needed to launch a new VDM process.
2467 static RTL_USER_PROCESS_PARAMETERS *get_vdm_params( const RTL_USER_PROCESS_PARAMETERS *params,
2468 pe_image_info_t *pe_info )
2470 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2472 WCHAR *new_cmd_line;
2473 RTL_USER_PROCESS_PARAMETERS *new_params;
2474 UNICODE_STRING imageW, cmdlineW;
2476 new_cmd_line = HeapAlloc(GetProcessHeap(), 0,
2477 (strlenW(params->ImagePathName.Buffer) +
2478 strlenW(params->CommandLine.Buffer) +
2479 strlenW(winevdm) + 16) * sizeof(WCHAR));
2480 if (!new_cmd_line)
2482 SetLastError( ERROR_OUTOFMEMORY );
2483 return NULL;
2485 sprintfW( new_cmd_line, argsW, winevdm, params->ImagePathName.Buffer, params->CommandLine.Buffer );
2486 RtlInitUnicodeString( &imageW, winevdm );
2487 RtlInitUnicodeString( &cmdlineW, new_cmd_line );
2488 if (RtlCreateProcessParametersEx( &new_params, &imageW, &params->DllPath,
2489 &params->CurrentDirectory.DosPath, &cmdlineW,
2490 params->Environment, &params->WindowTitle, &params->Desktop,
2491 &params->ShellInfo, &params->RuntimeInfo,
2492 PROCESS_PARAMS_FLAG_NORMALIZED ))
2494 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2495 SetLastError( ERROR_OUTOFMEMORY );
2496 return FALSE;
2498 new_params->hStdInput = params->hStdInput;
2499 new_params->hStdOutput = params->hStdOutput;
2500 new_params->hStdError = params->hStdError;
2501 new_params->dwX = params->dwX;
2502 new_params->dwY = params->dwY;
2503 new_params->dwXSize = params->dwXSize;
2504 new_params->dwYSize = params->dwYSize;
2505 new_params->dwXCountChars = params->dwXCountChars;
2506 new_params->dwYCountChars = params->dwYCountChars;
2507 new_params->dwFillAttribute = params->dwFillAttribute;
2508 new_params->dwFlags = params->dwFlags;
2509 new_params->wShowWindow = params->wShowWindow;
2511 memset( pe_info, 0, sizeof(*pe_info) );
2512 pe_info->cpu = CPU_x86;
2513 return new_params;
2517 /***********************************************************************
2518 * create_vdm_process
2520 * Create a new VDM process for a 16-bit or DOS application.
2522 static BOOL create_vdm_process( LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2523 BOOL inherit, DWORD flags, const RTL_USER_PROCESS_PARAMETERS *params,
2524 LPPROCESS_INFORMATION info, LPCSTR unixdir )
2526 BOOL ret;
2527 pe_image_info_t pe_info;
2528 RTL_USER_PROCESS_PARAMETERS *new_params;
2530 if (!(new_params = get_vdm_params( params, &pe_info ))) return FALSE;
2532 ret = create_process( 0, psa, tsa, inherit, flags, new_params, info, unixdir, &pe_info );
2533 RtlDestroyProcessParameters( new_params );
2534 return ret;
2538 /***********************************************************************
2539 * create_cmd_process
2541 * Create a new cmd shell process for a .BAT file.
2543 static BOOL create_cmd_process( LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2544 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2545 const RTL_USER_PROCESS_PARAMETERS *params,
2546 LPPROCESS_INFORMATION info )
2549 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2550 static const WCHAR cmdW[] = {'\\','c','m','d','.','e','x','e',0};
2551 static const WCHAR slashscW[] = {' ','/','s','/','c',' ',0};
2552 static const WCHAR quotW[] = {'"',0};
2553 WCHAR comspec[MAX_PATH];
2554 WCHAR *newcmdline, *cur_dir = NULL;
2555 BOOL ret;
2557 if (!GetEnvironmentVariableW( comspecW, comspec, ARRAY_SIZE( comspec )))
2559 GetSystemDirectoryW( comspec, ARRAY_SIZE( comspec ) - ARRAY_SIZE( cmdW ));
2560 strcatW( comspec, cmdW );
2562 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2563 (strlenW(comspec) + 7 +
2564 strlenW(params->CommandLine.Buffer) + 2) * sizeof(WCHAR))))
2565 return FALSE;
2567 strcpyW( newcmdline, comspec );
2568 strcatW( newcmdline, slashscW );
2569 strcatW( newcmdline, quotW );
2570 strcatW( newcmdline, params->CommandLine.Buffer );
2571 strcatW( newcmdline, quotW );
2572 if (params->CurrentDirectory.DosPath.Length) cur_dir = params->CurrentDirectory.DosPath.Buffer;
2573 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2574 flags | CREATE_UNICODE_ENVIRONMENT, params->Environment, cur_dir,
2575 startup, info );
2576 HeapFree( GetProcessHeap(), 0, newcmdline );
2577 return ret;
2581 /*************************************************************************
2582 * get_file_name
2584 * Helper for CreateProcess: retrieve the file name to load from the
2585 * app name and command line. Store the file name in buffer, and
2586 * return a possibly modified command line.
2587 * Also returns a handle to the opened file if it's a Windows binary.
2589 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2590 int buflen, HANDLE *handle, BOOL *is_64bit )
2592 static const WCHAR quotesW[] = {'"','%','s','"',0};
2594 WCHAR *name, *pos, *first_space, *ret = NULL;
2595 const WCHAR *p;
2597 /* if we have an app name, everything is easy */
2599 if (appname)
2601 /* use the unmodified app name as file name */
2602 lstrcpynW( buffer, appname, buflen );
2603 *handle = open_exe_file( buffer, is_64bit );
2604 if (!(ret = cmdline) || !cmdline[0])
2606 /* no command-line, create one */
2607 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2608 sprintfW( ret, quotesW, appname );
2610 return ret;
2613 /* first check for a quoted file name */
2615 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2617 int len = p - cmdline - 1;
2618 /* extract the quoted portion as file name */
2619 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2620 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2621 name[len] = 0;
2623 if (!find_exe_file( name, buffer, buflen, handle )) goto done;
2624 ret = cmdline; /* no change necessary */
2625 goto done;
2628 /* now try the command-line word by word */
2630 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2631 return NULL;
2632 pos = name;
2633 p = cmdline;
2634 first_space = NULL;
2636 for (;;)
2638 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2639 *pos = 0;
2640 if (find_exe_file( name, buffer, buflen, handle ))
2642 ret = cmdline;
2643 break;
2645 if (!first_space) first_space = pos;
2646 if (!(*pos++ = *p++)) break;
2649 if (!ret)
2651 SetLastError( ERROR_FILE_NOT_FOUND );
2653 else if (first_space) /* build a new command-line with quotes */
2655 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2656 goto done;
2657 sprintfW( ret, quotesW, name );
2658 strcatW( ret, p );
2661 done:
2662 HeapFree( GetProcessHeap(), 0, name );
2663 return ret;
2666 /**********************************************************************
2667 * CreateProcessInternalW (KERNEL32.@)
2669 BOOL WINAPI CreateProcessInternalW( HANDLE token, LPCWSTR app_name, LPWSTR cmd_line,
2670 LPSECURITY_ATTRIBUTES process_attr, LPSECURITY_ATTRIBUTES thread_attr,
2671 BOOL inherit, DWORD flags, LPVOID env, LPCWSTR cur_dir,
2672 LPSTARTUPINFOW startup_info, LPPROCESS_INFORMATION info,
2673 HANDLE *new_token )
2675 BOOL retv = FALSE;
2676 HANDLE hFile = 0;
2677 char *unixdir = NULL;
2678 WCHAR name[MAX_PATH];
2679 WCHAR *tidy_cmdline, *p;
2680 RTL_USER_PROCESS_PARAMETERS *params = NULL;
2681 pe_image_info_t pe_info;
2682 enum binary_type type;
2683 BOOL is_64bit;
2685 /* Process the AppName and/or CmdLine to get module name and path */
2687 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2689 if (token) FIXME("Creating a process with a token is not yet implemented\n");
2690 if (new_token) FIXME("No support for returning created process token\n");
2692 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, ARRAY_SIZE( name ), &hFile, &is_64bit )))
2693 return FALSE;
2694 if (hFile == INVALID_HANDLE_VALUE) goto done;
2696 /* Warn if unsupported features are used */
2698 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2699 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2700 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2701 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2702 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2704 if (cur_dir)
2706 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2708 SetLastError(ERROR_DIRECTORY);
2709 goto done;
2712 else
2714 WCHAR buf[MAX_PATH];
2715 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2718 info->hThread = info->hProcess = 0;
2719 info->dwProcessId = info->dwThreadId = 0;
2721 if (!(params = create_process_params( name, tidy_cmdline, cur_dir, env, flags, startup_info )))
2723 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2724 goto done;
2727 if (!hFile)
2729 memset( &pe_info, 0, sizeof(pe_info) );
2730 type = BINARY_UNIX_LIB;
2731 /* assume current arch */
2732 #if defined(__i386__) || defined(__x86_64__)
2733 pe_info.cpu = is_64bit ? CPU_x86_64 : CPU_x86;
2734 #elif defined(__powerpc__)
2735 pe_info.cpu = CPU_POWERPC;
2736 #elif defined(__arm__)
2737 pe_info.cpu = CPU_ARM;
2738 #elif defined(__aarch64__)
2739 pe_info.cpu = CPU_ARM64;
2740 #endif
2742 else type = get_binary_info( hFile, &pe_info );
2744 switch (type)
2746 case BINARY_PE:
2747 if (pe_info.image_charact & IMAGE_FILE_DLL)
2749 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2750 SetLastError( ERROR_BAD_EXE_FORMAT );
2751 break;
2753 TRACE( "starting %s as Win%d binary (%s-%s, %s)\n",
2754 debugstr_w(name), is_64bit_arch(pe_info.cpu) ? 64 : 32,
2755 wine_dbgstr_longlong(pe_info.base), wine_dbgstr_longlong(pe_info.base + pe_info.map_size),
2756 cpu_names[pe_info.cpu] );
2757 retv = create_process( hFile, process_attr, thread_attr,
2758 inherit, flags, params, info, unixdir, &pe_info );
2759 break;
2760 case BINARY_WIN16:
2761 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2762 retv = create_vdm_process( process_attr, thread_attr, inherit, flags, params, info, unixdir );
2763 break;
2764 case BINARY_UNIX_LIB:
2765 TRACE( "starting %s as %d-bit Winelib app\n",
2766 debugstr_w(name), is_64bit_arch(pe_info.cpu) ? 64 : 32 );
2767 retv = create_process( hFile, process_attr, thread_attr,
2768 inherit, flags, params, info, unixdir, &pe_info );
2769 break;
2770 case BINARY_UNKNOWN:
2771 /* check for .com or .bat extension */
2772 if ((p = strrchrW( name, '.' )))
2774 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2776 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2777 retv = create_vdm_process( process_attr, thread_attr,
2778 inherit, flags, params, info, unixdir );
2779 break;
2781 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2783 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2784 retv = create_cmd_process( process_attr, thread_attr,
2785 inherit, flags, startup_info, params, info );
2786 break;
2789 /* fall through */
2790 case BINARY_UNIX_EXE:
2791 /* unknown file, try as unix executable */
2792 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2793 retv = (fork_and_exec( params, unixdir ) != -1);
2794 break;
2796 if (hFile) CloseHandle( hFile );
2798 done:
2799 RtlDestroyProcessParameters( params );
2800 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2801 HeapFree( GetProcessHeap(), 0, unixdir );
2802 if (retv)
2803 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2804 return retv;
2808 /**********************************************************************
2809 * CreateProcessInternalA (KERNEL32.@)
2811 BOOL WINAPI CreateProcessInternalA( HANDLE token, LPCSTR app_name, LPSTR cmd_line,
2812 LPSECURITY_ATTRIBUTES process_attr, LPSECURITY_ATTRIBUTES thread_attr,
2813 BOOL inherit, DWORD flags, LPVOID env, LPCSTR cur_dir,
2814 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info,
2815 HANDLE *new_token )
2817 BOOL ret = FALSE;
2818 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2819 UNICODE_STRING desktopW, titleW;
2820 STARTUPINFOW infoW;
2822 desktopW.Buffer = NULL;
2823 titleW.Buffer = NULL;
2824 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2825 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2826 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2828 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2829 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2831 memcpy( &infoW, startup_info, sizeof(infoW) );
2832 infoW.lpDesktop = desktopW.Buffer;
2833 infoW.lpTitle = titleW.Buffer;
2835 if (startup_info->lpReserved)
2836 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2837 debugstr_a(startup_info->lpReserved));
2839 ret = CreateProcessInternalW( token, app_nameW, cmd_lineW, process_attr, thread_attr,
2840 inherit, flags, env, cur_dirW, &infoW, info, new_token );
2841 done:
2842 HeapFree( GetProcessHeap(), 0, app_nameW );
2843 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2844 HeapFree( GetProcessHeap(), 0, cur_dirW );
2845 RtlFreeUnicodeString( &desktopW );
2846 RtlFreeUnicodeString( &titleW );
2847 return ret;
2851 /**********************************************************************
2852 * CreateProcessA (KERNEL32.@)
2854 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2855 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2856 DWORD flags, LPVOID env, LPCSTR cur_dir,
2857 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2859 return CreateProcessInternalA( NULL, app_name, cmd_line, process_attr, thread_attr,
2860 inherit, flags, env, cur_dir, startup_info, info, NULL );
2864 /**********************************************************************
2865 * CreateProcessW (KERNEL32.@)
2867 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2868 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2869 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2870 LPPROCESS_INFORMATION info )
2872 return CreateProcessInternalW( NULL, app_name, cmd_line, process_attr, thread_attr,
2873 inherit, flags, env, cur_dir, startup_info, info, NULL );
2877 /**********************************************************************
2878 * CreateProcessAsUserA (KERNEL32.@)
2880 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessAsUserA( HANDLE token, LPCSTR app_name, LPSTR cmd_line,
2881 LPSECURITY_ATTRIBUTES process_attr,
2882 LPSECURITY_ATTRIBUTES thread_attr,
2883 BOOL inherit, DWORD flags, LPVOID env, LPCSTR cur_dir,
2884 LPSTARTUPINFOA startup_info,
2885 LPPROCESS_INFORMATION info )
2887 return CreateProcessInternalA( token, app_name, cmd_line, process_attr, thread_attr,
2888 inherit, flags, env, cur_dir, startup_info, info, NULL );
2892 /**********************************************************************
2893 * CreateProcessAsUserW (KERNEL32.@)
2895 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessAsUserW( HANDLE token, LPCWSTR app_name, LPWSTR cmd_line,
2896 LPSECURITY_ATTRIBUTES process_attr,
2897 LPSECURITY_ATTRIBUTES thread_attr,
2898 BOOL inherit, DWORD flags, LPVOID env, LPCWSTR cur_dir,
2899 LPSTARTUPINFOW startup_info,
2900 LPPROCESS_INFORMATION info )
2902 return CreateProcessInternalW( token, app_name, cmd_line, process_attr, thread_attr,
2903 inherit, flags, env, cur_dir, startup_info, info, NULL );
2907 /**********************************************************************
2908 * exec_process
2910 static void exec_process( LPCWSTR name )
2912 HANDLE hFile;
2913 WCHAR *p;
2914 STARTUPINFOW startup_info = { sizeof(startup_info) };
2915 RTL_USER_PROCESS_PARAMETERS *params, *new_params;
2916 pe_image_info_t pe_info;
2917 BOOL is_64bit;
2919 hFile = open_exe_file( name, &is_64bit );
2920 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2922 if (!(params = create_process_params( name, GetCommandLineW(), NULL, NULL, 0, &startup_info )))
2923 return;
2925 /* Determine executable type */
2927 switch (get_binary_info( hFile, &pe_info ))
2929 case BINARY_PE:
2930 if (pe_info.image_charact & IMAGE_FILE_DLL) break;
2931 TRACE( "starting %s as Win%d binary (%s-%s, %s)\n",
2932 debugstr_w(name), is_64bit_arch(pe_info.cpu) ? 64 : 32,
2933 wine_dbgstr_longlong(pe_info.base), wine_dbgstr_longlong(pe_info.base + pe_info.map_size),
2934 cpu_names[pe_info.cpu] );
2935 replace_process( hFile, params, &pe_info );
2936 break;
2937 case BINARY_UNIX_LIB:
2938 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2939 replace_process( hFile, params, &pe_info );
2940 break;
2941 case BINARY_UNKNOWN:
2942 /* check for .com or .pif extension */
2943 if (!(p = strrchrW( name, '.' ))) break;
2944 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2945 /* fall through */
2946 case BINARY_WIN16:
2947 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2948 if (!(new_params = get_vdm_params( params, &pe_info ))) break;
2949 replace_process( 0, new_params, &pe_info );
2950 RtlDestroyProcessParameters( new_params );
2951 break;
2952 default:
2953 break;
2955 CloseHandle( hFile );
2956 RtlDestroyProcessParameters( params );
2960 /***********************************************************************
2961 * wait_input_idle
2963 * Wrapper to call WaitForInputIdle USER function
2965 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2967 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2969 HMODULE mod = GetModuleHandleA( "user32.dll" );
2970 if (mod)
2972 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2973 if (ptr) return ptr( process, timeout );
2975 return 0;
2979 /***********************************************************************
2980 * WinExec (KERNEL32.@)
2982 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2984 PROCESS_INFORMATION info;
2985 STARTUPINFOA startup;
2986 char *cmdline;
2987 UINT ret;
2989 memset( &startup, 0, sizeof(startup) );
2990 startup.cb = sizeof(startup);
2991 startup.dwFlags = STARTF_USESHOWWINDOW;
2992 startup.wShowWindow = nCmdShow;
2994 /* cmdline needs to be writable for CreateProcess */
2995 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2996 strcpy( cmdline, lpCmdLine );
2998 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2999 0, NULL, NULL, &startup, &info ))
3001 /* Give 30 seconds to the app to come up */
3002 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
3003 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
3004 ret = 33;
3005 /* Close off the handles */
3006 CloseHandle( info.hThread );
3007 CloseHandle( info.hProcess );
3009 else if ((ret = GetLastError()) >= 32)
3011 FIXME("Strange error set by CreateProcess: %d\n", ret );
3012 ret = 11;
3014 HeapFree( GetProcessHeap(), 0, cmdline );
3015 return ret;
3019 /**********************************************************************
3020 * LoadModule (KERNEL32.@)
3022 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
3024 LOADPARMS32 *params = paramBlock;
3025 PROCESS_INFORMATION info;
3026 STARTUPINFOA startup;
3027 DWORD ret;
3028 LPSTR cmdline, p;
3029 char filename[MAX_PATH];
3030 BYTE len;
3032 if (!name) return ERROR_FILE_NOT_FOUND;
3034 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
3035 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
3036 return GetLastError();
3038 len = (BYTE)params->lpCmdLine[0];
3039 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
3040 return ERROR_NOT_ENOUGH_MEMORY;
3042 strcpy( cmdline, filename );
3043 p = cmdline + strlen(cmdline);
3044 *p++ = ' ';
3045 memcpy( p, params->lpCmdLine + 1, len );
3046 p[len] = 0;
3048 memset( &startup, 0, sizeof(startup) );
3049 startup.cb = sizeof(startup);
3050 if (params->lpCmdShow)
3052 startup.dwFlags = STARTF_USESHOWWINDOW;
3053 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
3056 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
3057 params->lpEnvAddress, NULL, &startup, &info ))
3059 /* Give 30 seconds to the app to come up */
3060 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
3061 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
3062 ret = 33;
3063 /* Close off the handles */
3064 CloseHandle( info.hThread );
3065 CloseHandle( info.hProcess );
3067 else if ((ret = GetLastError()) >= 32)
3069 FIXME("Strange error set by CreateProcess: %u\n", ret );
3070 ret = 11;
3073 HeapFree( GetProcessHeap(), 0, cmdline );
3074 return ret;
3078 /******************************************************************************
3079 * TerminateProcess (KERNEL32.@)
3081 * Terminates a process.
3083 * PARAMS
3084 * handle [I] Process to terminate.
3085 * exit_code [I] Exit code.
3087 * RETURNS
3088 * Success: TRUE.
3089 * Failure: FALSE, check GetLastError().
3091 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
3093 NTSTATUS status;
3095 if (!handle)
3097 SetLastError( ERROR_INVALID_HANDLE );
3098 return FALSE;
3101 status = NtTerminateProcess( handle, exit_code );
3102 if (status) SetLastError( RtlNtStatusToDosError(status) );
3103 return !status;
3106 /***********************************************************************
3107 * ExitProcess (KERNEL32.@)
3109 * Exits the current process.
3111 * PARAMS
3112 * status [I] Status code to exit with.
3114 * RETURNS
3115 * Nothing.
3117 #ifdef __i386__
3118 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
3119 "pushl %ebp\n\t"
3120 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
3121 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
3122 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
3123 "pushl 8(%ebp)\n\t"
3124 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
3125 "leave\n\t"
3126 "ret $4" )
3127 #else
3129 void WINAPI ExitProcess( DWORD status )
3131 RtlExitUserProcess( status );
3134 #endif
3136 /***********************************************************************
3137 * GetExitCodeProcess [KERNEL32.@]
3139 * Gets termination status of specified process.
3141 * PARAMS
3142 * hProcess [in] Handle to the process.
3143 * lpExitCode [out] Address to receive termination status.
3145 * RETURNS
3146 * Success: TRUE
3147 * Failure: FALSE
3149 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
3151 NTSTATUS status;
3152 PROCESS_BASIC_INFORMATION pbi;
3154 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3155 sizeof(pbi), NULL);
3156 if (status == STATUS_SUCCESS)
3158 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
3159 return TRUE;
3161 SetLastError( RtlNtStatusToDosError(status) );
3162 return FALSE;
3166 /***********************************************************************
3167 * SetErrorMode (KERNEL32.@)
3169 UINT WINAPI SetErrorMode( UINT mode )
3171 UINT old;
3173 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
3174 &old, sizeof(old), NULL );
3175 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
3176 &mode, sizeof(mode) );
3177 return old;
3180 /***********************************************************************
3181 * GetErrorMode (KERNEL32.@)
3183 UINT WINAPI GetErrorMode( void )
3185 UINT mode;
3187 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
3188 &mode, sizeof(mode), NULL );
3189 return mode;
3192 /**********************************************************************
3193 * TlsAlloc [KERNEL32.@]
3195 * Allocates a thread local storage index.
3197 * RETURNS
3198 * Success: TLS index.
3199 * Failure: 0xFFFFFFFF
3201 DWORD WINAPI TlsAlloc( void )
3203 DWORD index;
3204 PEB * const peb = NtCurrentTeb()->Peb;
3206 RtlAcquirePebLock();
3207 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
3208 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
3209 else
3211 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
3212 if (index != ~0U)
3214 if (!NtCurrentTeb()->TlsExpansionSlots &&
3215 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
3216 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
3218 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
3219 index = ~0U;
3220 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3222 else
3224 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
3225 index += TLS_MINIMUM_AVAILABLE;
3228 else SetLastError( ERROR_NO_MORE_ITEMS );
3230 RtlReleasePebLock();
3231 return index;
3235 /**********************************************************************
3236 * TlsFree [KERNEL32.@]
3238 * Releases a thread local storage index, making it available for reuse.
3240 * PARAMS
3241 * index [in] TLS index to free.
3243 * RETURNS
3244 * Success: TRUE
3245 * Failure: FALSE
3247 BOOL WINAPI TlsFree( DWORD index )
3249 BOOL ret;
3251 RtlAcquirePebLock();
3252 if (index >= TLS_MINIMUM_AVAILABLE)
3254 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
3255 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
3257 else
3259 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
3260 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
3262 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
3263 else SetLastError( ERROR_INVALID_PARAMETER );
3264 RtlReleasePebLock();
3265 return ret;
3269 /**********************************************************************
3270 * TlsGetValue [KERNEL32.@]
3272 * Gets value in a thread's TLS slot.
3274 * PARAMS
3275 * index [in] TLS index to retrieve value for.
3277 * RETURNS
3278 * Success: Value stored in calling thread's TLS slot for index.
3279 * Failure: 0 and GetLastError() returns NO_ERROR.
3281 LPVOID WINAPI TlsGetValue( DWORD index )
3283 LPVOID ret;
3285 if (index < TLS_MINIMUM_AVAILABLE)
3287 ret = NtCurrentTeb()->TlsSlots[index];
3289 else
3291 index -= TLS_MINIMUM_AVAILABLE;
3292 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
3294 SetLastError( ERROR_INVALID_PARAMETER );
3295 return NULL;
3297 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
3298 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
3300 SetLastError( ERROR_SUCCESS );
3301 return ret;
3305 /**********************************************************************
3306 * TlsSetValue [KERNEL32.@]
3308 * Stores a value in the thread's TLS slot.
3310 * PARAMS
3311 * index [in] TLS index to set value for.
3312 * value [in] Value to be stored.
3314 * RETURNS
3315 * Success: TRUE
3316 * Failure: FALSE
3318 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
3320 if (index < TLS_MINIMUM_AVAILABLE)
3322 NtCurrentTeb()->TlsSlots[index] = value;
3324 else
3326 index -= TLS_MINIMUM_AVAILABLE;
3327 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
3329 SetLastError( ERROR_INVALID_PARAMETER );
3330 return FALSE;
3332 if (!NtCurrentTeb()->TlsExpansionSlots &&
3333 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
3334 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
3336 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3337 return FALSE;
3339 NtCurrentTeb()->TlsExpansionSlots[index] = value;
3341 return TRUE;
3345 /***********************************************************************
3346 * GetProcessFlags (KERNEL32.@)
3348 DWORD WINAPI GetProcessFlags( DWORD processid )
3350 IMAGE_NT_HEADERS *nt;
3351 DWORD flags = 0;
3353 if (processid && processid != GetCurrentProcessId()) return 0;
3355 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3357 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
3358 flags |= PDB32_CONSOLE_PROC;
3360 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
3361 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
3362 return flags;
3366 /*********************************************************************
3367 * OpenProcess (KERNEL32.@)
3369 * Opens a handle to a process.
3371 * PARAMS
3372 * access [I] Desired access rights assigned to the returned handle.
3373 * inherit [I] Determines whether or not child processes will inherit the handle.
3374 * id [I] Process identifier of the process to get a handle to.
3376 * RETURNS
3377 * Success: Valid handle to the specified process.
3378 * Failure: NULL, check GetLastError().
3380 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
3382 NTSTATUS status;
3383 HANDLE handle;
3384 OBJECT_ATTRIBUTES attr;
3385 CLIENT_ID cid;
3387 cid.UniqueProcess = ULongToHandle(id);
3388 cid.UniqueThread = 0; /* FIXME ? */
3390 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3391 attr.RootDirectory = NULL;
3392 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3393 attr.SecurityDescriptor = NULL;
3394 attr.SecurityQualityOfService = NULL;
3395 attr.ObjectName = NULL;
3397 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3399 status = NtOpenProcess(&handle, access, &attr, &cid);
3400 if (status != STATUS_SUCCESS)
3402 SetLastError( RtlNtStatusToDosError(status) );
3403 return NULL;
3405 return handle;
3409 /*********************************************************************
3410 * GetProcessId (KERNEL32.@)
3412 * Gets the a unique identifier of a process.
3414 * PARAMS
3415 * hProcess [I] Handle to the process.
3417 * RETURNS
3418 * Success: TRUE.
3419 * Failure: FALSE, check GetLastError().
3421 * NOTES
3423 * The identifier is unique only on the machine and only until the process
3424 * exits (including system shutdown).
3426 DWORD WINAPI GetProcessId( HANDLE hProcess )
3428 NTSTATUS status;
3429 PROCESS_BASIC_INFORMATION pbi;
3431 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3432 sizeof(pbi), NULL);
3433 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3434 SetLastError( RtlNtStatusToDosError(status) );
3435 return 0;
3439 /*********************************************************************
3440 * CloseHandle (KERNEL32.@)
3442 * Closes a handle.
3444 * PARAMS
3445 * handle [I] Handle to close.
3447 * RETURNS
3448 * Success: TRUE.
3449 * Failure: FALSE, check GetLastError().
3451 BOOL WINAPI CloseHandle( HANDLE handle )
3453 NTSTATUS status;
3455 /* stdio handles need special treatment */
3456 if (handle == (HANDLE)STD_INPUT_HANDLE)
3457 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3458 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3459 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3460 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3461 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3463 if (is_console_handle(handle))
3464 return CloseConsoleHandle(handle);
3466 status = NtClose( handle );
3467 if (status) SetLastError( RtlNtStatusToDosError(status) );
3468 return !status;
3472 /*********************************************************************
3473 * GetHandleInformation (KERNEL32.@)
3475 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3477 OBJECT_DATA_INFORMATION info;
3478 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3480 if (status) SetLastError( RtlNtStatusToDosError(status) );
3481 else if (flags)
3483 *flags = 0;
3484 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3485 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3487 return !status;
3491 /*********************************************************************
3492 * SetHandleInformation (KERNEL32.@)
3494 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3496 OBJECT_DATA_INFORMATION info;
3497 NTSTATUS status;
3499 /* if not setting both fields, retrieve current value first */
3500 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3501 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3503 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3505 SetLastError( RtlNtStatusToDosError(status) );
3506 return FALSE;
3509 if (mask & HANDLE_FLAG_INHERIT)
3510 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3511 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3512 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3514 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3515 if (status) SetLastError( RtlNtStatusToDosError(status) );
3516 return !status;
3520 /*********************************************************************
3521 * DuplicateHandle (KERNEL32.@)
3523 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3524 HANDLE dest_process, HANDLE *dest,
3525 DWORD access, BOOL inherit, DWORD options )
3527 NTSTATUS status;
3529 if (is_console_handle(source))
3531 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3532 if (source_process != dest_process ||
3533 source_process != GetCurrentProcess())
3535 SetLastError(ERROR_INVALID_PARAMETER);
3536 return FALSE;
3538 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3539 return (*dest != INVALID_HANDLE_VALUE);
3541 status = NtDuplicateObject( source_process, source, dest_process, dest,
3542 access, inherit ? OBJ_INHERIT : 0, options );
3543 if (status) SetLastError( RtlNtStatusToDosError(status) );
3544 return !status;
3548 /***********************************************************************
3549 * ConvertToGlobalHandle (KERNEL32.@)
3551 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3553 HANDLE ret = INVALID_HANDLE_VALUE;
3554 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3555 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3556 return ret;
3560 /***********************************************************************
3561 * SetHandleContext (KERNEL32.@)
3563 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3565 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3566 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3567 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3568 return FALSE;
3572 /***********************************************************************
3573 * GetHandleContext (KERNEL32.@)
3575 DWORD WINAPI GetHandleContext(HANDLE hnd)
3577 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3578 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3579 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3580 return 0;
3584 /***********************************************************************
3585 * CreateSocketHandle (KERNEL32.@)
3587 HANDLE WINAPI CreateSocketHandle(void)
3589 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3590 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3591 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3592 return INVALID_HANDLE_VALUE;
3596 /***********************************************************************
3597 * SetPriorityClass (KERNEL32.@)
3599 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3601 NTSTATUS status;
3602 PROCESS_PRIORITY_CLASS ppc;
3604 ppc.Foreground = FALSE;
3605 switch (priorityclass)
3607 case IDLE_PRIORITY_CLASS:
3608 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3609 case BELOW_NORMAL_PRIORITY_CLASS:
3610 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3611 case NORMAL_PRIORITY_CLASS:
3612 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3613 case ABOVE_NORMAL_PRIORITY_CLASS:
3614 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3615 case HIGH_PRIORITY_CLASS:
3616 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3617 case REALTIME_PRIORITY_CLASS:
3618 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3619 default:
3620 SetLastError(ERROR_INVALID_PARAMETER);
3621 return FALSE;
3624 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3625 &ppc, sizeof(ppc));
3627 if (status != STATUS_SUCCESS)
3629 SetLastError( RtlNtStatusToDosError(status) );
3630 return FALSE;
3632 return TRUE;
3636 /***********************************************************************
3637 * GetPriorityClass (KERNEL32.@)
3639 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3641 NTSTATUS status;
3642 PROCESS_BASIC_INFORMATION pbi;
3644 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3645 sizeof(pbi), NULL);
3646 if (status != STATUS_SUCCESS)
3648 SetLastError( RtlNtStatusToDosError(status) );
3649 return 0;
3651 switch (pbi.BasePriority)
3653 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3654 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3655 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3656 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3657 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3658 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3660 SetLastError( ERROR_INVALID_PARAMETER );
3661 return 0;
3665 /***********************************************************************
3666 * SetProcessAffinityMask (KERNEL32.@)
3668 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3670 NTSTATUS status;
3672 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3673 &affmask, sizeof(DWORD_PTR));
3674 if (status)
3676 SetLastError( RtlNtStatusToDosError(status) );
3677 return FALSE;
3679 return TRUE;
3683 /**********************************************************************
3684 * GetProcessAffinityMask (KERNEL32.@)
3686 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3688 NTSTATUS status = STATUS_SUCCESS;
3690 if (process_mask)
3692 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3693 process_mask, sizeof(*process_mask), NULL )))
3694 SetLastError( RtlNtStatusToDosError(status) );
3696 if (system_mask && status == STATUS_SUCCESS)
3698 SYSTEM_BASIC_INFORMATION info;
3700 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3701 SetLastError( RtlNtStatusToDosError(status) );
3702 else
3703 *system_mask = info.ActiveProcessorsAffinityMask;
3705 return !status;
3709 /***********************************************************************
3710 * SetProcessAffinityUpdateMode (KERNEL32.@)
3712 BOOL WINAPI SetProcessAffinityUpdateMode( HANDLE process, DWORD flags )
3714 FIXME("(%p,0x%08x): stub\n", process, flags);
3715 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3716 return FALSE;
3720 /***********************************************************************
3721 * GetProcessVersion (KERNEL32.@)
3723 DWORD WINAPI GetProcessVersion( DWORD pid )
3725 HANDLE process;
3726 NTSTATUS status;
3727 PROCESS_BASIC_INFORMATION pbi;
3728 SIZE_T count;
3729 PEB peb;
3730 IMAGE_DOS_HEADER dos;
3731 IMAGE_NT_HEADERS nt;
3732 DWORD ver = 0;
3734 if (!pid || pid == GetCurrentProcessId())
3736 IMAGE_NT_HEADERS *pnt;
3738 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3739 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3740 pnt->OptionalHeader.MinorSubsystemVersion);
3741 return 0;
3744 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3745 if (!process) return 0;
3747 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3748 if (status) goto err;
3750 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3751 if (status || count != sizeof(peb)) goto err;
3753 memset(&dos, 0, sizeof(dos));
3754 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3755 if (status || count != sizeof(dos)) goto err;
3756 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3758 memset(&nt, 0, sizeof(nt));
3759 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3760 if (status || count != sizeof(nt)) goto err;
3761 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3763 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3765 err:
3766 CloseHandle(process);
3768 if (status != STATUS_SUCCESS)
3769 SetLastError(RtlNtStatusToDosError(status));
3771 return ver;
3775 /***********************************************************************
3776 * SetProcessWorkingSetSizeEx [KERNEL32.@]
3777 * Sets the min/max working set sizes for a specified process.
3779 * PARAMS
3780 * process [I] Handle to the process of interest
3781 * minset [I] Specifies minimum working set size
3782 * maxset [I] Specifies maximum working set size
3783 * flags [I] Flags to enforce working set sizes
3785 * RETURNS
3786 * Success: TRUE
3787 * Failure: FALSE
3789 BOOL WINAPI SetProcessWorkingSetSizeEx(HANDLE process, SIZE_T minset, SIZE_T maxset, DWORD flags)
3791 WARN("(%p,%ld,%ld,%x): stub - harmless\n", process, minset, maxset, flags);
3792 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3793 /* Trim the working set to zero */
3794 /* Swap the process out of physical RAM */
3796 return TRUE;
3799 /***********************************************************************
3800 * SetProcessWorkingSetSize [KERNEL32.@]
3801 * Sets the min/max working set sizes for a specified process.
3803 * PARAMS
3804 * process [I] Handle to the process of interest
3805 * minset [I] Specifies minimum working set size
3806 * maxset [I] Specifies maximum working set size
3808 * RETURNS
3809 * Success: TRUE
3810 * Failure: FALSE
3812 BOOL WINAPI SetProcessWorkingSetSize(HANDLE process, SIZE_T minset, SIZE_T maxset)
3814 return SetProcessWorkingSetSizeEx(process, minset, maxset, 0);
3817 /***********************************************************************
3818 * K32EmptyWorkingSet (KERNEL32.@)
3820 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3822 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3826 /***********************************************************************
3827 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3829 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3830 SIZE_T *maxset, DWORD *flags)
3832 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3833 /* 32 MB working set size */
3834 if (minset) *minset = 32*1024*1024;
3835 if (maxset) *maxset = 32*1024*1024;
3836 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3837 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3838 return TRUE;
3842 /***********************************************************************
3843 * GetProcessWorkingSetSize (KERNEL32.@)
3845 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3847 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3851 /***********************************************************************
3852 * SetProcessShutdownParameters (KERNEL32.@)
3854 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3856 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3857 shutdown_flags = flags;
3858 shutdown_priority = level;
3859 return TRUE;
3863 /***********************************************************************
3864 * GetProcessShutdownParameters (KERNEL32.@)
3867 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3869 *lpdwLevel = shutdown_priority;
3870 *lpdwFlags = shutdown_flags;
3871 return TRUE;
3875 /***********************************************************************
3876 * GetProcessPriorityBoost (KERNEL32.@)
3878 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3880 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3882 /* Report that no boost is present.. */
3883 *pDisablePriorityBoost = FALSE;
3885 return TRUE;
3888 /***********************************************************************
3889 * SetProcessPriorityBoost (KERNEL32.@)
3891 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3893 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3894 /* Say we can do it. I doubt the program will notice that we don't. */
3895 return TRUE;
3899 /***********************************************************************
3900 * ReadProcessMemory (KERNEL32.@)
3902 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3903 SIZE_T *bytes_read )
3905 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3906 if (status) SetLastError( RtlNtStatusToDosError(status) );
3907 return !status;
3911 /***********************************************************************
3912 * WriteProcessMemory (KERNEL32.@)
3914 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3915 SIZE_T *bytes_written )
3917 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3918 if (status) SetLastError( RtlNtStatusToDosError(status) );
3919 return !status;
3923 /****************************************************************************
3924 * FlushInstructionCache (KERNEL32.@)
3926 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3928 NTSTATUS status;
3929 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3930 if (status) SetLastError( RtlNtStatusToDosError(status) );
3931 return !status;
3935 /******************************************************************
3936 * GetProcessIoCounters (KERNEL32.@)
3938 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3940 NTSTATUS status;
3942 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3943 ioc, sizeof(*ioc), NULL);
3944 if (status) SetLastError( RtlNtStatusToDosError(status) );
3945 return !status;
3948 /******************************************************************
3949 * GetProcessHandleCount (KERNEL32.@)
3951 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3953 NTSTATUS status;
3955 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3956 cnt, sizeof(*cnt), NULL);
3957 if (status) SetLastError( RtlNtStatusToDosError(status) );
3958 return !status;
3961 /******************************************************************
3962 * QueryFullProcessImageNameA (KERNEL32.@)
3964 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3966 BOOL retval;
3967 DWORD pdwSizeW = *pdwSize;
3968 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3970 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3972 if(retval)
3973 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3974 lpExeName, *pdwSize, NULL, NULL));
3975 if(retval)
3976 *pdwSize = strlen(lpExeName);
3978 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3979 return retval;
3982 /******************************************************************
3983 * QueryFullProcessImageNameW (KERNEL32.@)
3985 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3987 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3988 UNICODE_STRING *dynamic_buffer = NULL;
3989 UNICODE_STRING *result = NULL;
3990 NTSTATUS status;
3991 DWORD needed;
3993 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3994 * is a DOS path and we depend on this. */
3995 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3996 sizeof(buffer) - sizeof(WCHAR), &needed);
3997 if (status == STATUS_INFO_LENGTH_MISMATCH)
3999 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
4000 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
4001 result = dynamic_buffer;
4003 else
4004 result = (PUNICODE_STRING)buffer;
4006 if (status) goto cleanup;
4008 if (dwFlags & PROCESS_NAME_NATIVE)
4010 WCHAR drive[3];
4011 WCHAR device[1024];
4012 DWORD ntlen, devlen;
4014 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
4016 /* We cannot convert it to an NT device path so fail */
4017 status = STATUS_NO_SUCH_DEVICE;
4018 goto cleanup;
4021 /* Find this drive's NT device path */
4022 drive[0] = result->Buffer[0];
4023 drive[1] = ':';
4024 drive[2] = 0;
4025 if (!QueryDosDeviceW(drive, device, ARRAY_SIZE(device)))
4027 status = STATUS_NO_SUCH_DEVICE;
4028 goto cleanup;
4031 devlen = lstrlenW(device);
4032 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
4033 if (ntlen + 1 > *pdwSize)
4035 status = STATUS_BUFFER_TOO_SMALL;
4036 goto cleanup;
4038 *pdwSize = ntlen;
4040 memcpy(lpExeName, device, devlen * sizeof(*device));
4041 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
4042 lpExeName[*pdwSize] = 0;
4043 TRACE("NT path: %s\n", debugstr_w(lpExeName));
4045 else
4047 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
4049 status = STATUS_BUFFER_TOO_SMALL;
4050 goto cleanup;
4053 *pdwSize = result->Length/sizeof(WCHAR);
4054 memcpy( lpExeName, result->Buffer, result->Length );
4055 lpExeName[*pdwSize] = 0;
4058 cleanup:
4059 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
4060 if (status) SetLastError( RtlNtStatusToDosError(status) );
4061 return !status;
4064 /***********************************************************************
4065 * K32GetProcessImageFileNameA (KERNEL32.@)
4067 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
4069 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
4072 /***********************************************************************
4073 * K32GetProcessImageFileNameW (KERNEL32.@)
4075 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
4077 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
4080 /***********************************************************************
4081 * K32EnumProcesses (KERNEL32.@)
4083 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
4085 SYSTEM_PROCESS_INFORMATION *spi;
4086 ULONG size = 0x4000;
4087 void *buf = NULL;
4088 NTSTATUS status;
4090 do {
4091 size *= 2;
4092 HeapFree(GetProcessHeap(), 0, buf);
4093 buf = HeapAlloc(GetProcessHeap(), 0, size);
4094 if (!buf)
4095 return FALSE;
4097 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
4098 } while(status == STATUS_INFO_LENGTH_MISMATCH);
4100 if (status != STATUS_SUCCESS)
4102 HeapFree(GetProcessHeap(), 0, buf);
4103 SetLastError(RtlNtStatusToDosError(status));
4104 return FALSE;
4107 spi = buf;
4109 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
4111 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
4112 *lpcbUsed += sizeof(DWORD);
4114 if (spi->NextEntryOffset == 0)
4115 break;
4117 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
4120 HeapFree(GetProcessHeap(), 0, buf);
4121 return TRUE;
4124 /***********************************************************************
4125 * K32QueryWorkingSet (KERNEL32.@)
4127 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
4129 NTSTATUS status;
4131 TRACE( "(%p, %p, %d)\n", process, buffer, size );
4133 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
4135 if (status)
4137 SetLastError( RtlNtStatusToDosError( status ) );
4138 return FALSE;
4140 return TRUE;
4143 /***********************************************************************
4144 * K32QueryWorkingSetEx (KERNEL32.@)
4146 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
4148 NTSTATUS status;
4150 TRACE( "(%p, %p, %d)\n", process, buffer, size );
4152 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
4154 if (status)
4156 SetLastError( RtlNtStatusToDosError( status ) );
4157 return FALSE;
4159 return TRUE;
4162 /***********************************************************************
4163 * K32GetProcessMemoryInfo (KERNEL32.@)
4165 * Retrieve memory usage information for a given process
4168 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
4169 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
4171 NTSTATUS status;
4172 VM_COUNTERS vmc;
4174 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
4176 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4177 return FALSE;
4180 status = NtQueryInformationProcess(process, ProcessVmCounters,
4181 &vmc, sizeof(vmc), NULL);
4183 if (status)
4185 SetLastError(RtlNtStatusToDosError(status));
4186 return FALSE;
4189 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
4190 pmc->PageFaultCount = vmc.PageFaultCount;
4191 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
4192 pmc->WorkingSetSize = vmc.WorkingSetSize;
4193 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
4194 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
4195 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
4196 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
4197 pmc->PagefileUsage = vmc.PagefileUsage;
4198 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
4200 return TRUE;
4203 /***********************************************************************
4204 * ProcessIdToSessionId (KERNEL32.@)
4205 * This function is available on Terminal Server 4SP4 and Windows 2000
4207 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
4209 if (procid != GetCurrentProcessId())
4210 FIXME("Unsupported for other processes.\n");
4212 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
4213 return TRUE;
4217 /***********************************************************************
4218 * RegisterServiceProcess (KERNEL32.@)
4220 * A service process calls this function to ensure that it continues to run
4221 * even after a user logged off.
4223 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
4225 /* I don't think that Wine needs to do anything in this function */
4226 return 1; /* success */
4230 /**********************************************************************
4231 * IsWow64Process (KERNEL32.@)
4233 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
4235 ULONG_PTR pbi;
4236 NTSTATUS status;
4238 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
4240 if (status != STATUS_SUCCESS)
4242 SetLastError( RtlNtStatusToDosError( status ) );
4243 return FALSE;
4245 *Wow64Process = (pbi != 0);
4246 return TRUE;
4250 /***********************************************************************
4251 * GetCurrentProcess (KERNEL32.@)
4253 * Get a handle to the current process.
4255 * PARAMS
4256 * None.
4258 * RETURNS
4259 * A handle representing the current process.
4261 #undef GetCurrentProcess
4262 HANDLE WINAPI GetCurrentProcess(void)
4264 return (HANDLE)~(ULONG_PTR)0;
4267 /***********************************************************************
4268 * GetLogicalProcessorInformation (KERNEL32.@)
4270 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
4272 NTSTATUS status;
4274 TRACE("(%p,%p)\n", buffer, pBufLen);
4276 if(!pBufLen)
4278 SetLastError(ERROR_INVALID_PARAMETER);
4279 return FALSE;
4282 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
4284 if (status == STATUS_INFO_LENGTH_MISMATCH)
4286 SetLastError( ERROR_INSUFFICIENT_BUFFER );
4287 return FALSE;
4289 if (status != STATUS_SUCCESS)
4291 SetLastError( RtlNtStatusToDosError( status ) );
4292 return FALSE;
4294 return TRUE;
4297 /***********************************************************************
4298 * GetLogicalProcessorInformationEx (KERNEL32.@)
4300 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
4302 NTSTATUS status;
4304 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
4306 if (!len)
4308 SetLastError( ERROR_INVALID_PARAMETER );
4309 return FALSE;
4312 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
4313 buffer, *len, len );
4314 if (status == STATUS_INFO_LENGTH_MISMATCH)
4316 SetLastError( ERROR_INSUFFICIENT_BUFFER );
4317 return FALSE;
4319 if (status != STATUS_SUCCESS)
4321 SetLastError( RtlNtStatusToDosError( status ) );
4322 return FALSE;
4324 return TRUE;
4327 /***********************************************************************
4328 * CmdBatNotification (KERNEL32.@)
4330 * Notifies the system that a batch file has started or finished.
4332 * PARAMS
4333 * bBatchRunning [I] TRUE if a batch file has started or
4334 * FALSE if a batch file has finished executing.
4336 * RETURNS
4337 * Unknown.
4339 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
4341 FIXME("%d\n", bBatchRunning);
4342 return FALSE;
4345 /***********************************************************************
4346 * RegisterApplicationRestart (KERNEL32.@)
4348 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
4350 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
4352 return S_OK;
4355 /**********************************************************************
4356 * WTSGetActiveConsoleSessionId (KERNEL32.@)
4358 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
4360 static int once;
4361 if (!once++) FIXME("stub\n");
4362 /* Return current session id. */
4363 return NtCurrentTeb()->Peb->SessionId;
4366 /**********************************************************************
4367 * GetSystemDEPPolicy (KERNEL32.@)
4369 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
4371 FIXME("stub\n");
4372 return OptIn;
4375 /**********************************************************************
4376 * SetProcessDEPPolicy (KERNEL32.@)
4378 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
4380 FIXME("(%d): stub\n", newDEP);
4381 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4382 return FALSE;
4385 /**********************************************************************
4386 * ApplicationRecoveryFinished (KERNEL32.@)
4388 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
4390 FIXME(": stub\n");
4391 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4394 /**********************************************************************
4395 * ApplicationRecoveryInProgress (KERNEL32.@)
4397 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
4399 FIXME(":%p stub\n", canceled);
4400 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4401 return E_FAIL;
4404 /**********************************************************************
4405 * RegisterApplicationRecoveryCallback (KERNEL32.@)
4407 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
4409 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
4410 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4411 return E_FAIL;
4414 /***********************************************************************
4415 * GetApplicationRestartSettings (KERNEL32.@)
4417 HRESULT WINAPI GetApplicationRestartSettings(HANDLE process, WCHAR *cmdline, DWORD *size, DWORD *flags)
4419 FIXME("%p, %p, %p, %p)\n", process, cmdline, size, flags);
4420 return E_NOTIMPL;
4423 /**********************************************************************
4424 * GetNumaHighestNodeNumber (KERNEL32.@)
4426 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4428 *highestnode = 0;
4429 FIXME("(%p): semi-stub\n", highestnode);
4430 return TRUE;
4433 /**********************************************************************
4434 * GetNumaNodeProcessorMask (KERNEL32.@)
4436 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4438 FIXME("(%c %p): stub\n", node, mask);
4439 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4440 return FALSE;
4443 /**********************************************************************
4444 * GetNumaNodeProcessorMaskEx (KERNEL32.@)
4446 BOOL WINAPI GetNumaNodeProcessorMaskEx(USHORT node, PGROUP_AFFINITY mask)
4448 FIXME("(%hu %p): stub\n", node, mask);
4449 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4450 return FALSE;
4453 /**********************************************************************
4454 * GetNumaAvailableMemoryNode (KERNEL32.@)
4456 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4458 FIXME("(%c %p): stub\n", node, available_bytes);
4459 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4460 return FALSE;
4463 /**********************************************************************
4464 * GetNumaAvailableMemoryNodeEx (KERNEL32.@)
4466 BOOL WINAPI GetNumaAvailableMemoryNodeEx(USHORT node, PULONGLONG available_bytes)
4468 FIXME("(%hu %p): stub\n", node, available_bytes);
4469 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4470 return FALSE;
4473 /***********************************************************************
4474 * GetNumaProcessorNode (KERNEL32.@)
4476 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4478 SYSTEM_INFO si;
4480 TRACE("(%d, %p)\n", processor, node);
4482 GetSystemInfo( &si );
4483 if (processor < si.dwNumberOfProcessors)
4485 *node = 0;
4486 return TRUE;
4489 *node = 0xFF;
4490 SetLastError(ERROR_INVALID_PARAMETER);
4491 return FALSE;
4494 /***********************************************************************
4495 * GetNumaProcessorNodeEx (KERNEL32.@)
4497 BOOL WINAPI GetNumaProcessorNodeEx(PPROCESSOR_NUMBER processor, PUSHORT node_number)
4499 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4500 return FALSE;
4503 /***********************************************************************
4504 * GetNumaProximityNode (KERNEL32.@)
4506 BOOL WINAPI GetNumaProximityNode(ULONG proximity_id, PUCHAR node_number)
4508 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4509 return FALSE;
4512 /***********************************************************************
4513 * GetNumaProximityNodeEx (KERNEL32.@)
4515 BOOL WINAPI GetNumaProximityNodeEx(ULONG proximity_id, PUSHORT node_number)
4517 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4518 return FALSE;
4521 /**********************************************************************
4522 * GetProcessDEPPolicy (KERNEL32.@)
4524 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4526 NTSTATUS status;
4527 ULONG dep_flags;
4529 TRACE("(%p %p %p)\n", process, flags, permanent);
4531 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4532 &dep_flags, sizeof(dep_flags), NULL );
4533 if (!status)
4536 if (flags)
4538 *flags = 0;
4539 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4540 *flags |= PROCESS_DEP_ENABLE;
4541 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4542 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4545 if (permanent)
4546 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4549 if (status) SetLastError( RtlNtStatusToDosError(status) );
4550 return !status;
4553 /**********************************************************************
4554 * FlushProcessWriteBuffers (KERNEL32.@)
4556 VOID WINAPI FlushProcessWriteBuffers(void)
4558 static int once = 0;
4560 if (!once++)
4561 FIXME(": stub\n");
4564 /***********************************************************************
4565 * UnregisterApplicationRestart (KERNEL32.@)
4567 HRESULT WINAPI UnregisterApplicationRestart(void)
4569 FIXME(": stub\n");
4570 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4571 return S_OK;
4574 struct proc_thread_attr
4576 DWORD_PTR attr;
4577 SIZE_T size;
4578 void *value;
4581 struct _PROC_THREAD_ATTRIBUTE_LIST
4583 DWORD mask; /* bitmask of items in list */
4584 DWORD size; /* max number of items in list */
4585 DWORD count; /* number of items in list */
4586 DWORD pad;
4587 DWORD_PTR unk;
4588 struct proc_thread_attr attrs[1];
4591 /***********************************************************************
4592 * InitializeProcThreadAttributeList (KERNEL32.@)
4594 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4595 DWORD count, DWORD flags, SIZE_T *size)
4597 SIZE_T needed;
4598 BOOL ret = FALSE;
4600 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4602 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4603 if (list && *size >= needed)
4605 list->mask = 0;
4606 list->size = count;
4607 list->count = 0;
4608 list->unk = 0;
4609 ret = TRUE;
4611 else
4612 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4614 *size = needed;
4615 return ret;
4618 /***********************************************************************
4619 * UpdateProcThreadAttribute (KERNEL32.@)
4621 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4622 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4623 void *prev_ret, SIZE_T *size_ret)
4625 DWORD mask;
4626 struct proc_thread_attr *entry;
4628 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4630 if (list->count >= list->size)
4632 SetLastError(ERROR_GEN_FAILURE);
4633 return FALSE;
4636 switch (attr)
4638 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4639 if (size != sizeof(HANDLE))
4641 SetLastError(ERROR_BAD_LENGTH);
4642 return FALSE;
4644 break;
4646 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4647 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4649 SetLastError(ERROR_BAD_LENGTH);
4650 return FALSE;
4652 break;
4654 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4655 if (size != sizeof(PROCESSOR_NUMBER))
4657 SetLastError(ERROR_BAD_LENGTH);
4658 return FALSE;
4660 break;
4662 case PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY:
4663 if (size != sizeof(DWORD) && size != sizeof(DWORD64))
4665 SetLastError(ERROR_BAD_LENGTH);
4666 return FALSE;
4668 break;
4670 case PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY:
4671 if (size != sizeof(DWORD) && size != sizeof(DWORD64) && size != sizeof(DWORD64) * 2)
4673 SetLastError(ERROR_BAD_LENGTH);
4674 return FALSE;
4676 break;
4678 default:
4679 SetLastError(ERROR_NOT_SUPPORTED);
4680 FIXME("Unhandled attribute number %lu\n", attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4681 return FALSE;
4684 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4686 if (list->mask & mask)
4688 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4689 return FALSE;
4692 list->mask |= mask;
4694 entry = list->attrs + list->count;
4695 entry->attr = attr;
4696 entry->size = size;
4697 entry->value = value;
4698 list->count++;
4700 return TRUE;
4703 /***********************************************************************
4704 * CreateUmsCompletionList (KERNEL32.@)
4706 BOOL WINAPI CreateUmsCompletionList(PUMS_COMPLETION_LIST *list)
4708 FIXME( "%p: stub\n", list );
4709 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4710 return FALSE;
4713 /***********************************************************************
4714 * CreateUmsThreadContext (KERNEL32.@)
4716 BOOL WINAPI CreateUmsThreadContext(PUMS_CONTEXT *ctx)
4718 FIXME( "%p: stub\n", ctx );
4719 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4720 return FALSE;
4723 /***********************************************************************
4724 * DeleteProcThreadAttributeList (KERNEL32.@)
4726 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4728 return;
4731 /***********************************************************************
4732 * DeleteUmsCompletionList (KERNEL32.@)
4734 BOOL WINAPI DeleteUmsCompletionList(PUMS_COMPLETION_LIST list)
4736 FIXME( "%p: stub\n", list );
4737 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4738 return FALSE;
4741 /***********************************************************************
4742 * DeleteUmsThreadContext (KERNEL32.@)
4744 BOOL WINAPI DeleteUmsThreadContext(PUMS_CONTEXT ctx)
4746 FIXME( "%p: stub\n", ctx );
4747 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4748 return FALSE;
4751 /***********************************************************************
4752 * DequeueUmsCompletionListItems (KERNEL32.@)
4754 BOOL WINAPI DequeueUmsCompletionListItems(void *list, DWORD timeout, PUMS_CONTEXT *ctx)
4756 FIXME( "%p,%08x,%p: stub\n", list, timeout, ctx );
4757 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4758 return FALSE;
4761 /***********************************************************************
4762 * EnterUmsSchedulingMode (KERNEL32.@)
4764 BOOL WINAPI EnterUmsSchedulingMode(UMS_SCHEDULER_STARTUP_INFO *info)
4766 FIXME( "%p: stub\n", info );
4767 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4768 return FALSE;
4771 /***********************************************************************
4772 * ExecuteUmsThread (KERNEL32.@)
4774 BOOL WINAPI ExecuteUmsThread(PUMS_CONTEXT ctx)
4776 FIXME( "%p: stub\n", ctx );
4777 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4778 return FALSE;
4781 /***********************************************************************
4782 * GetCurrentUmsThread (KERNEL32.@)
4784 PUMS_CONTEXT WINAPI GetCurrentUmsThread(void)
4786 FIXME( "stub\n" );
4787 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4788 return FALSE;
4791 /***********************************************************************
4792 * GetNextUmsListItem (KERNEL32.@)
4794 PUMS_CONTEXT WINAPI GetNextUmsListItem(PUMS_CONTEXT ctx)
4796 FIXME( "%p: stub\n", ctx );
4797 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4798 return NULL;
4801 /***********************************************************************
4802 * GetUmsCompletionListEvent (KERNEL32.@)
4804 BOOL WINAPI GetUmsCompletionListEvent(PUMS_COMPLETION_LIST list, HANDLE *event)
4806 FIXME( "%p,%p: stub\n", list, event );
4807 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4808 return FALSE;
4811 /***********************************************************************
4812 * QueryUmsThreadInformation (KERNEL32.@)
4814 BOOL WINAPI QueryUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4815 void *buf, ULONG length, ULONG *ret_length)
4817 FIXME( "%p,%08x,%p,%08x,%p: stub\n", ctx, class, buf, length, ret_length );
4818 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4819 return FALSE;
4822 /***********************************************************************
4823 * SetUmsThreadInformation (KERNEL32.@)
4825 BOOL WINAPI SetUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4826 void *buf, ULONG length)
4828 FIXME( "%p,%08x,%p,%08x: stub\n", ctx, class, buf, length );
4829 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4830 return FALSE;
4833 /***********************************************************************
4834 * UmsThreadYield (KERNEL32.@)
4836 BOOL WINAPI UmsThreadYield(void *param)
4838 FIXME( "%p: stub\n", param );
4839 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4840 return FALSE;
4843 /**********************************************************************
4844 * BaseFlushAppcompatCache (KERNEL32.@)
4846 BOOL WINAPI BaseFlushAppcompatCache(void)
4848 FIXME(": stub\n");
4849 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4850 return FALSE;
4853 /**********************************************************************
4854 * SetProcessMitigationPolicy (KERNEL32.@)
4856 BOOL WINAPI SetProcessMitigationPolicy(PROCESS_MITIGATION_POLICY policy, void *buffer, SIZE_T length)
4858 FIXME("(%d, %p, %lu): stub\n", policy, buffer, length);
4860 return TRUE;
4863 /**********************************************************************
4864 * GetProcessMitigationPolicy (KERNEL32.@)
4866 BOOL WINAPI GetProcessMitigationPolicy(HANDLE hProcess, PROCESS_MITIGATION_POLICY policy, void *buffer, SIZE_T length)
4868 FIXME("(%p, %u, %p, %lu): stub\n", hProcess, policy, buffer, length);
4870 return TRUE;