kernel32: Use the Unicode string length to build the argv array.
[wine.git] / dlls / kernel32 / process.c
blobea483b99e310a597ed3df8fb41fe73bd6ca91bb1
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
42 #endif
43 #include <sys/types.h>
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #ifdef __APPLE__
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <pthread.h>
53 #endif
55 #include "ntstatus.h"
56 #define WIN32_NO_STATUS
57 #include "winternl.h"
58 #include "kernel_private.h"
59 #include "psapi.h"
60 #include "wine/exception.h"
61 #include "wine/library.h"
62 #include "wine/server.h"
63 #include "wine/unicode.h"
64 #include "wine/debug.h"
66 WINE_DEFAULT_DEBUG_CHANNEL(process);
67 WINE_DECLARE_DEBUG_CHANNEL(relay);
69 #ifdef __APPLE__
70 extern char **__wine_get_main_environment(void);
71 #else
72 extern char **__wine_main_environ;
73 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
74 #endif
76 typedef struct
78 LPSTR lpEnvAddress;
79 LPSTR lpCmdLine;
80 LPSTR lpCmdShow;
81 DWORD dwReserved;
82 } LOADPARMS32;
84 static DWORD shutdown_flags = 0;
85 static DWORD shutdown_priority = 0x280;
86 static BOOL is_wow64;
87 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
89 HMODULE kernel32_handle = 0;
90 SYSTEM_BASIC_INFORMATION system_info = { 0 };
92 const WCHAR DIR_Windows[] = {'C',':','\\','w','i','n','d','o','w','s',0};
93 const WCHAR DIR_System[] = {'C',':','\\','w','i','n','d','o','w','s',
94 '\\','s','y','s','t','e','m','3','2',0};
95 const WCHAR *DIR_SysWow64 = NULL;
97 /* Process flags */
98 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
99 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
100 #define PDB32_DOS_PROC 0x0010 /* Dos process */
101 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
102 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
103 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
105 static const WCHAR exeW[] = {'.','e','x','e',0};
106 static const WCHAR comW[] = {'.','c','o','m',0};
107 static const WCHAR batW[] = {'.','b','a','t',0};
108 static const WCHAR cmdW[] = {'.','c','m','d',0};
109 static const WCHAR pifW[] = {'.','p','i','f',0};
110 static WCHAR winevdm[] = {'C',':','\\','w','i','n','d','o','w','s',
111 '\\','s','y','s','t','e','m','3','2',
112 '\\','w','i','n','e','v','d','m','.','e','x','e',0};
114 static const char * const cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
116 static void exec_process( LPCWSTR name );
118 extern void SHELL_LoadRegistry(void);
120 /* return values for get_binary_info */
121 enum binary_type
123 BINARY_UNKNOWN = 0,
124 BINARY_PE,
125 BINARY_WIN16,
126 BINARY_UNIX_EXE,
127 BINARY_UNIX_LIB
131 /***********************************************************************
132 * contains_path
134 static inline BOOL contains_path( LPCWSTR name )
136 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
140 /***********************************************************************
141 * is_special_env_var
143 * Check if an environment variable needs to be handled specially when
144 * passed through the Unix environment (i.e. prefixed with "WINE").
146 static inline BOOL is_special_env_var( const char *var )
148 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
149 !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
150 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
151 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
152 !strncmp( var, "TMP=", sizeof("TMP=")-1 ) ||
153 !strncmp( var, "QT_", sizeof("QT_")-1 ) ||
154 !strncmp( var, "VK_", sizeof("VK_")-1 ));
158 /***********************************************************************
159 * is_path_prefix
161 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
163 unsigned int len = strlenW( prefix );
165 if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
166 while (filename[len] == '\\') len++;
167 return len;
171 /***********************************************************************
172 * is_64bit_arch
174 static inline BOOL is_64bit_arch( cpu_type_t cpu )
176 return (cpu == CPU_x86_64 || cpu == CPU_ARM64);
180 /***********************************************************************
181 * get_pe_info
183 static NTSTATUS get_pe_info( HANDLE handle, pe_image_info_t *info )
185 NTSTATUS status;
186 HANDLE mapping;
188 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY,
189 NULL, NULL, PAGE_READONLY, SEC_IMAGE, handle );
190 if (status) return status;
192 SERVER_START_REQ( get_mapping_info )
194 req->handle = wine_server_obj_handle( mapping );
195 req->access = SECTION_QUERY;
196 wine_server_set_reply( req, info, sizeof(*info) );
197 status = wine_server_call( req );
199 SERVER_END_REQ;
200 CloseHandle( mapping );
201 return status;
205 /***********************************************************************
206 * get_binary_info
208 static enum binary_type get_binary_info( HANDLE hfile, pe_image_info_t *info )
210 union
212 struct
214 unsigned char magic[4];
215 unsigned char class;
216 unsigned char data;
217 unsigned char ignored1[10];
218 unsigned short type;
219 unsigned short machine;
220 unsigned char ignored2[8];
221 unsigned int phoff;
222 unsigned char ignored3[12];
223 unsigned short phnum;
224 } elf;
225 struct
227 unsigned char magic[4];
228 unsigned char class;
229 unsigned char data;
230 unsigned char ignored1[10];
231 unsigned short type;
232 unsigned short machine;
233 unsigned char ignored2[12];
234 unsigned __int64 phoff;
235 unsigned char ignored3[16];
236 unsigned short phnum;
237 } elf64;
238 struct
240 unsigned int magic;
241 unsigned int cputype;
242 unsigned int cpusubtype;
243 unsigned int filetype;
244 } macho;
245 IMAGE_DOS_HEADER mz;
246 } header;
248 DWORD len;
249 NTSTATUS status;
251 memset( info, 0, sizeof(*info) );
253 status = get_pe_info( hfile, info );
254 switch (status)
256 case STATUS_SUCCESS:
257 return BINARY_PE;
258 case STATUS_INVALID_IMAGE_WIN_32:
259 return BINARY_PE;
260 case STATUS_INVALID_IMAGE_WIN_64:
261 return BINARY_PE;
262 case STATUS_INVALID_IMAGE_WIN_16:
263 case STATUS_INVALID_IMAGE_NE_FORMAT:
264 case STATUS_INVALID_IMAGE_PROTECT:
265 return BINARY_WIN16;
268 /* Seek to the start of the file and read the header information. */
269 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return BINARY_UNKNOWN;
270 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
271 return BINARY_UNKNOWN;
273 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
275 #ifdef WORDS_BIGENDIAN
276 BOOL byteswap = (header.elf.data == 1);
277 #else
278 BOOL byteswap = (header.elf.data == 2);
279 #endif
280 if (byteswap)
282 header.elf.type = RtlUshortByteSwap( header.elf.type );
283 header.elf.machine = RtlUshortByteSwap( header.elf.machine );
285 switch(header.elf.machine)
287 case 3: info->cpu = CPU_x86; break;
288 case 20: info->cpu = CPU_POWERPC; break;
289 case 40: info->cpu = CPU_ARM; break;
290 case 62: info->cpu = CPU_x86_64; break;
291 case 183: info->cpu = CPU_ARM64; break;
293 switch(header.elf.type)
295 case 2:
296 return BINARY_UNIX_EXE;
297 case 3:
299 LARGE_INTEGER phoff;
300 unsigned short phnum;
301 unsigned int type;
302 if (header.elf.class == 2)
304 phoff.QuadPart = byteswap ? RtlUlonglongByteSwap( header.elf64.phoff ) : header.elf64.phoff;
305 phnum = byteswap ? RtlUshortByteSwap( header.elf64.phnum ) : header.elf64.phnum;
307 else
309 phoff.QuadPart = byteswap ? RtlUlongByteSwap( header.elf.phoff ) : header.elf.phoff;
310 phnum = byteswap ? RtlUshortByteSwap( header.elf.phnum ) : header.elf.phnum;
312 while (phnum--)
314 if (SetFilePointerEx( hfile, phoff, NULL, FILE_BEGIN ) == -1) return BINARY_UNKNOWN;
315 if (!ReadFile( hfile, &type, sizeof(type), &len, NULL ) || len < sizeof(type))
316 return BINARY_UNKNOWN;
317 if (byteswap) type = RtlUlongByteSwap( type );
318 if (type == 3) return BINARY_UNIX_EXE;
319 phoff.QuadPart += (header.elf.class == 2) ? 56 : 32;
321 return BINARY_UNIX_LIB;
325 /* Mach-o File with Endian set to Big Endian or Little Endian */
326 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe ||
327 header.macho.magic == 0xfeedfacf || header.macho.magic == 0xcffaedfe)
329 if (header.macho.magic == 0xcefaedfe || header.macho.magic == 0xcffaedfe)
331 header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
332 header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
334 switch(header.macho.cputype)
336 case 0x00000007: info->cpu = CPU_x86; break;
337 case 0x01000007: info->cpu = CPU_x86_64; break;
338 case 0x0000000c: info->cpu = CPU_ARM; break;
339 case 0x0100000c: info->cpu = CPU_ARM64; break;
340 case 0x00000012: info->cpu = CPU_POWERPC; break;
342 switch(header.macho.filetype)
344 case 2: return BINARY_UNIX_EXE;
345 case 8: return BINARY_UNIX_LIB;
347 switch(header.macho.filetype)
349 case 2: return BINARY_UNIX_EXE;
350 case 8: return BINARY_UNIX_LIB;
353 return BINARY_UNKNOWN;
357 /***************************************************************************
358 * get_builtin_path
360 * Get the path of a builtin module when the native file does not exist.
362 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
363 UINT size, BOOL *is_64bit )
365 WCHAR *file_part;
366 UINT len;
367 void *redir_disabled = 0;
369 *is_64bit = (sizeof(void*) > sizeof(int));
371 /* builtin names cannot be empty or contain spaces */
372 if (!libname[0] || strchrW( libname, ' ' ) || strchrW( libname, '\t' )) return FALSE;
374 if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
375 Wow64RevertWow64FsRedirection( redir_disabled );
377 if (contains_path( libname ))
379 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
380 filename, &file_part ) > size * sizeof(WCHAR))
381 return FALSE; /* too long */
383 if ((len = is_path_prefix( DIR_System, filename )))
385 if (is_wow64 && redir_disabled) *is_64bit = TRUE;
387 else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
389 *is_64bit = FALSE;
391 else return FALSE;
393 if (filename + len != file_part) return FALSE;
395 else
397 len = strlenW( DIR_System );
398 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
399 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
400 file_part = filename + len;
401 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
402 strcpyW( file_part, libname );
403 if (is_wow64 && redir_disabled) *is_64bit = TRUE;
405 if (ext && !strchrW( file_part, '.' ))
407 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
408 return FALSE; /* too long */
409 strcatW( file_part, ext );
411 return TRUE;
415 /***********************************************************************
416 * open_exe_file
418 * Open a specific exe file, taking load order into account.
419 * Returns the file handle or 0 for a builtin exe.
421 static HANDLE open_exe_file( const WCHAR *name, BOOL *is_64bit )
423 HANDLE handle;
425 TRACE("looking for %s\n", debugstr_w(name) );
427 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
428 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
430 WCHAR buffer[MAX_PATH];
431 /* file doesn't exist, check for builtin */
432 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), is_64bit ))
433 handle = 0;
435 return handle;
439 /***********************************************************************
440 * find_exe_file
442 * Open an exe file, and return the full name and file handle.
443 * Returns FALSE if file could not be found.
445 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
447 TRACE("looking for %s\n", debugstr_w(name) );
449 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
450 /* no builtin found, try native without extension in case it is a Unix app */
451 !SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
453 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
454 *handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
455 NULL, OPEN_EXISTING, 0, 0 );
456 return (*handle != INVALID_HANDLE_VALUE);
460 /***********************************************************************
461 * build_initial_environment
463 * Build the Win32 environment from the Unix environment
465 static BOOL build_initial_environment(void)
467 SIZE_T size = 1;
468 char **e;
469 WCHAR *p, *endptr;
470 void *ptr;
471 char **env = __wine_get_main_environment();
473 /* Compute the total size of the Unix environment */
474 for (e = env; *e; e++)
476 if (is_special_env_var( *e )) continue;
477 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
479 size *= sizeof(WCHAR);
481 /* Now allocate the environment */
482 ptr = NULL;
483 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
484 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
485 return FALSE;
487 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
488 endptr = p + size / sizeof(WCHAR);
490 /* And fill it with the Unix environment */
491 for (e = env; *e; e++)
493 char *str = *e;
495 /* skip Unix special variables and use the Wine variants instead */
496 if (!strncmp( str, "WINE", 4 ))
498 if (is_special_env_var( str + 4 )) str += 4;
499 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
501 else if (is_special_env_var( str )) continue; /* skip it */
503 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
504 p += strlenW(p) + 1;
506 *p = 0;
507 return TRUE;
511 /***********************************************************************
512 * set_registry_variables
514 * Set environment variables by enumerating the values of a key;
515 * helper for set_registry_environment().
516 * Note that Windows happily truncates the value if it's too big.
518 static void set_registry_variables( HANDLE hkey, ULONG type )
520 static const WCHAR pathW[] = {'P','A','T','H'};
521 static const WCHAR sep[] = {';',0};
522 UNICODE_STRING env_name, env_value;
523 NTSTATUS status;
524 DWORD size;
525 int index;
526 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
527 WCHAR tmpbuf[1024];
528 UNICODE_STRING tmp;
529 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
531 tmp.Buffer = tmpbuf;
532 tmp.MaximumLength = sizeof(tmpbuf);
534 for (index = 0; ; index++)
536 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
537 buffer, sizeof(buffer), &size );
538 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
539 break;
540 if (info->Type != type)
541 continue;
542 env_name.Buffer = info->Name;
543 env_name.Length = env_name.MaximumLength = info->NameLength;
544 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
545 env_value.Length = info->DataLength;
546 env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
547 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
548 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
549 if (!env_value.Length) continue;
550 if (info->Type == REG_EXPAND_SZ)
552 status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
553 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
554 RtlCopyUnicodeString( &env_value, &tmp );
556 /* PATH is magic */
557 if (env_name.Length == sizeof(pathW) &&
558 !memicmpW( env_name.Buffer, pathW, ARRAY_SIZE( pathW )) &&
559 !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
561 RtlAppendUnicodeToString( &tmp, sep );
562 if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
563 RtlCopyUnicodeString( &env_value, &tmp );
565 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
570 /***********************************************************************
571 * set_registry_environment
573 * Set the environment variables specified in the registry.
575 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
576 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
577 * on the order in which the variables are processed. But on Windows it
578 * does not really matter since they only use %SystemDrive% and
579 * %SystemRoot% which are predefined. But Wine defines these in the
580 * registry, so we need two passes.
582 static BOOL set_registry_environment( BOOL volatile_only )
584 static const WCHAR env_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
585 'M','a','c','h','i','n','e','\\',
586 'S','y','s','t','e','m','\\',
587 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
588 'C','o','n','t','r','o','l','\\',
589 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
590 'E','n','v','i','r','o','n','m','e','n','t',0};
591 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
592 static const WCHAR volatile_envW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
594 OBJECT_ATTRIBUTES attr;
595 UNICODE_STRING nameW;
596 HANDLE hkey;
597 BOOL ret = FALSE;
599 attr.Length = sizeof(attr);
600 attr.RootDirectory = 0;
601 attr.ObjectName = &nameW;
602 attr.Attributes = 0;
603 attr.SecurityDescriptor = NULL;
604 attr.SecurityQualityOfService = NULL;
606 /* first the system environment variables */
607 RtlInitUnicodeString( &nameW, env_keyW );
608 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
610 set_registry_variables( hkey, REG_SZ );
611 set_registry_variables( hkey, REG_EXPAND_SZ );
612 NtClose( hkey );
613 ret = TRUE;
616 /* then the ones for the current user */
617 if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
618 RtlInitUnicodeString( &nameW, envW );
619 if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
621 set_registry_variables( hkey, REG_SZ );
622 set_registry_variables( hkey, REG_EXPAND_SZ );
623 NtClose( hkey );
626 RtlInitUnicodeString( &nameW, volatile_envW );
627 if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
629 set_registry_variables( hkey, REG_SZ );
630 set_registry_variables( hkey, REG_EXPAND_SZ );
631 NtClose( hkey );
634 NtClose( attr.RootDirectory );
635 return ret;
639 /***********************************************************************
640 * get_reg_value
642 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
644 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
645 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
646 DWORD len, size = sizeof(buffer);
647 WCHAR *ret = NULL;
648 UNICODE_STRING nameW;
650 RtlInitUnicodeString( &nameW, name );
651 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
652 return NULL;
654 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
655 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
657 if (info->Type == REG_EXPAND_SZ)
659 UNICODE_STRING value, expanded;
661 value.MaximumLength = len * sizeof(WCHAR);
662 value.Buffer = (WCHAR *)info->Data;
663 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
664 value.Length = len * sizeof(WCHAR);
665 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
666 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
667 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
668 else RtlFreeUnicodeString( &expanded );
670 else if (info->Type == REG_SZ)
672 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
674 memcpy( ret, info->Data, len * sizeof(WCHAR) );
675 ret[len] = 0;
678 return ret;
682 /***********************************************************************
683 * set_additional_environment
685 * Set some additional environment variables not specified in the registry.
687 static void set_additional_environment(void)
689 static const WCHAR profile_keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
690 'M','a','c','h','i','n','e','\\',
691 'S','o','f','t','w','a','r','e','\\',
692 'M','i','c','r','o','s','o','f','t','\\',
693 'W','i','n','d','o','w','s',' ','N','T','\\',
694 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
695 'P','r','o','f','i','l','e','L','i','s','t',0};
696 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
697 static const WCHAR public_valueW[] = {'P','u','b','l','i','c',0};
698 static const WCHAR computernameW[] = {'C','O','M','P','U','T','E','R','N','A','M','E',0};
699 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
700 static const WCHAR programdataW[] = {'P','r','o','g','r','a','m','D','a','t','a',0};
701 static const WCHAR publicW[] = {'P','U','B','L','I','C',0};
702 OBJECT_ATTRIBUTES attr;
703 UNICODE_STRING nameW;
704 WCHAR *profile_dir = NULL, *program_data_dir = NULL, *public_dir = NULL;
705 WCHAR buf[MAX_COMPUTERNAME_LENGTH+1];
706 HANDLE hkey;
707 DWORD len;
709 /* ComputerName */
710 len = ARRAY_SIZE( buf );
711 if (GetComputerNameW( buf, &len ))
712 SetEnvironmentVariableW( computernameW, buf );
714 /* set the ALLUSERSPROFILE variables */
716 attr.Length = sizeof(attr);
717 attr.RootDirectory = 0;
718 attr.ObjectName = &nameW;
719 attr.Attributes = 0;
720 attr.SecurityDescriptor = NULL;
721 attr.SecurityQualityOfService = NULL;
722 RtlInitUnicodeString( &nameW, profile_keyW );
723 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
725 profile_dir = get_reg_value( hkey, profiles_valueW );
726 program_data_dir = get_reg_value( hkey, programdataW );
727 public_dir = get_reg_value( hkey, public_valueW );
728 NtClose( hkey );
731 if (program_data_dir)
733 SetEnvironmentVariableW( allusersW, program_data_dir );
734 SetEnvironmentVariableW( programdataW, program_data_dir );
737 if (public_dir)
739 SetEnvironmentVariableW( publicW, public_dir );
742 HeapFree( GetProcessHeap(), 0, profile_dir );
743 HeapFree( GetProcessHeap(), 0, program_data_dir );
744 HeapFree( GetProcessHeap(), 0, public_dir );
747 /***********************************************************************
748 * set_wow64_environment
750 * Set the environment variables that change across 32/64/Wow64.
752 static void set_wow64_environment(void)
754 static const WCHAR archW[] = {'P','R','O','C','E','S','S','O','R','_','A','R','C','H','I','T','E','C','T','U','R','E',0};
755 static const WCHAR arch6432W[] = {'P','R','O','C','E','S','S','O','R','_','A','R','C','H','I','T','E','W','6','4','3','2',0};
756 static const WCHAR x86W[] = {'x','8','6',0};
757 static const WCHAR versionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
758 'M','a','c','h','i','n','e','\\',
759 'S','o','f','t','w','a','r','e','\\',
760 'M','i','c','r','o','s','o','f','t','\\',
761 'W','i','n','d','o','w','s','\\',
762 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
763 static const WCHAR progdirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
764 static const WCHAR progdir86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
765 static const WCHAR progfilesW[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
766 static const WCHAR progw6432W[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
767 static const WCHAR commondirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
768 static const WCHAR commondir86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
769 static const WCHAR commonfilesW[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
770 static const WCHAR commonw6432W[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
772 OBJECT_ATTRIBUTES attr;
773 UNICODE_STRING nameW;
774 WCHAR arch[64];
775 WCHAR *value;
776 HANDLE hkey;
778 /* set the PROCESSOR_ARCHITECTURE variable */
780 if (GetEnvironmentVariableW( arch6432W, arch, ARRAY_SIZE( arch )))
782 if (is_win64)
784 SetEnvironmentVariableW( archW, arch );
785 SetEnvironmentVariableW( arch6432W, NULL );
788 else if (GetEnvironmentVariableW( archW, arch, ARRAY_SIZE( arch )))
790 if (is_wow64)
792 SetEnvironmentVariableW( arch6432W, arch );
793 SetEnvironmentVariableW( archW, x86W );
797 attr.Length = sizeof(attr);
798 attr.RootDirectory = 0;
799 attr.ObjectName = &nameW;
800 attr.Attributes = 0;
801 attr.SecurityDescriptor = NULL;
802 attr.SecurityQualityOfService = NULL;
803 RtlInitUnicodeString( &nameW, versionW );
804 if (NtOpenKey( &hkey, KEY_READ | KEY_WOW64_64KEY, &attr )) return;
806 /* set the ProgramFiles variables */
808 if ((value = get_reg_value( hkey, progdirW )))
810 if (is_win64 || is_wow64) SetEnvironmentVariableW( progw6432W, value );
811 if (is_win64 || !is_wow64) SetEnvironmentVariableW( progfilesW, value );
812 HeapFree( GetProcessHeap(), 0, value );
814 if (is_wow64 && (value = get_reg_value( hkey, progdir86W )))
816 SetEnvironmentVariableW( progfilesW, value );
817 HeapFree( GetProcessHeap(), 0, value );
820 /* set the CommonProgramFiles variables */
822 if ((value = get_reg_value( hkey, commondirW )))
824 if (is_win64 || is_wow64) SetEnvironmentVariableW( commonw6432W, value );
825 if (is_win64 || !is_wow64) SetEnvironmentVariableW( commonfilesW, value );
826 HeapFree( GetProcessHeap(), 0, value );
828 if (is_wow64 && (value = get_reg_value( hkey, commondir86W )))
830 SetEnvironmentVariableW( commonfilesW, value );
831 HeapFree( GetProcessHeap(), 0, value );
834 NtClose( hkey );
837 /***********************************************************************
838 * set_library_wargv
840 * Set the Wine library Unicode argv global variables.
842 static void set_library_wargv( char **argv )
844 int argc;
845 char *q;
846 WCHAR *p;
847 WCHAR **wargv;
848 DWORD total = 0;
850 for (argc = 0; argv[argc]; argc++)
851 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
853 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
854 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
855 p = (WCHAR *)(wargv + argc + 1);
856 for (argc = 0; argv[argc]; argc++)
858 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
859 wargv[argc] = p;
860 p += reslen;
861 total -= reslen;
863 wargv[argc] = NULL;
865 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
867 for (argc = 0; wargv[argc]; argc++)
868 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
870 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
871 q = (char *)(argv + argc + 1);
872 for (argc = 0; wargv[argc]; argc++)
874 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
875 argv[argc] = q;
876 q += reslen;
877 total -= reslen;
879 argv[argc] = NULL;
881 __wine_main_argc = argc;
882 __wine_main_argv = argv;
883 __wine_main_wargv = wargv;
887 /***********************************************************************
888 * update_library_argv0
890 * Update the argv[0] global variable with the binary we have found.
892 static void update_library_argv0( const WCHAR *argv0 )
894 DWORD len = strlenW( argv0 );
896 if (len > strlenW( __wine_main_wargv[0] ))
898 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
900 strcpyW( __wine_main_wargv[0], argv0 );
902 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
903 if (len > strlen( __wine_main_argv[0] ) + 1)
905 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
907 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
911 /***********************************************************************
912 * build_command_line
914 * Build the command line of a process from the argv array.
916 * Note that it does NOT necessarily include the file name.
917 * Sometimes we don't even have any command line options at all.
919 * We must quote and escape characters so that the argv array can be rebuilt
920 * from the command line:
921 * - spaces and tabs must be quoted
922 * 'a b' -> '"a b"'
923 * - quotes must be escaped
924 * '"' -> '\"'
925 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
926 * resulting in an odd number of '\' followed by a '"'
927 * '\"' -> '\\\"'
928 * '\\"' -> '\\\\\"'
929 * - '\'s are followed by the closing '"' must be doubled,
930 * resulting in an even number of '\' followed by a '"'
931 * ' \' -> '" \\"'
932 * ' \\' -> '" \\\\"'
933 * - '\'s that are not followed by a '"' can be left as is
934 * 'a\b' == 'a\b'
935 * 'a\\b' == 'a\\b'
937 static BOOL build_command_line( WCHAR **argv )
939 int len;
940 WCHAR **arg;
941 LPWSTR p;
942 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
944 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
946 len = 0;
947 for (arg = argv; *arg; arg++)
949 BOOL has_space;
950 int bcount;
951 WCHAR* a;
953 has_space=FALSE;
954 bcount=0;
955 a=*arg;
956 if( !*a ) has_space=TRUE;
957 while (*a!='\0') {
958 if (*a=='\\') {
959 bcount++;
960 } else {
961 if (*a==' ' || *a=='\t') {
962 has_space=TRUE;
963 } else if (*a=='"') {
964 /* doubling of '\' preceding a '"',
965 * plus escaping of said '"'
967 len+=2*bcount+1;
969 bcount=0;
971 a++;
973 len+=(a-*arg)+1 /* for the separating space */;
974 if (has_space)
975 len+=2+bcount; /* for the quotes and doubling of '\' preceding the closing quote */
978 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
979 return FALSE;
981 p = rupp->CommandLine.Buffer;
982 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
983 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
984 for (arg = argv; *arg; arg++)
986 BOOL has_space,has_quote;
987 WCHAR* a;
988 int bcount;
990 /* Check for quotes and spaces in this argument */
991 has_space=has_quote=FALSE;
992 a=*arg;
993 if( !*a ) has_space=TRUE;
994 while (*a!='\0') {
995 if (*a==' ' || *a=='\t') {
996 has_space=TRUE;
997 if (has_quote)
998 break;
999 } else if (*a=='"') {
1000 has_quote=TRUE;
1001 if (has_space)
1002 break;
1004 a++;
1007 /* Now transfer it to the command line */
1008 if (has_space)
1009 *p++='"';
1010 if (has_quote || has_space) {
1011 bcount=0;
1012 a=*arg;
1013 while (*a!='\0') {
1014 if (*a=='\\') {
1015 *p++=*a;
1016 bcount++;
1017 } else {
1018 if (*a=='"') {
1019 int i;
1021 /* Double all the '\\' preceding this '"', plus one */
1022 for (i=0;i<=bcount;i++)
1023 *p++='\\';
1024 *p++='"';
1025 } else {
1026 *p++=*a;
1028 bcount=0;
1030 a++;
1032 } else {
1033 WCHAR* x = *arg;
1034 while ((*p=*x++)) p++;
1036 if (has_space) {
1037 int i;
1039 /* Double all the '\' preceding the closing quote */
1040 for (i=0;i<bcount;i++)
1041 *p++='\\';
1042 *p++='"';
1044 *p++=' ';
1046 if (p > rupp->CommandLine.Buffer)
1047 p--; /* remove last space */
1048 *p = '\0';
1050 return TRUE;
1054 /***********************************************************************
1055 * init_current_directory
1057 * Initialize the current directory from the Unix cwd or the parent info.
1059 static void init_current_directory( CURDIR *cur_dir )
1061 UNICODE_STRING dir_str;
1062 const char *pwd;
1063 char *cwd;
1064 int size;
1066 /* if we received a cur dir from the parent, try this first */
1068 if (cur_dir->DosPath.Length)
1070 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
1073 /* now try to get it from the Unix cwd */
1075 for (size = 256; ; size *= 2)
1077 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
1078 if (getcwd( cwd, size )) break;
1079 HeapFree( GetProcessHeap(), 0, cwd );
1080 if (errno == ERANGE) continue;
1081 cwd = NULL;
1082 break;
1085 /* try to use PWD if it is valid, so that we don't resolve symlinks */
1087 pwd = getenv( "PWD" );
1088 if (cwd)
1090 struct stat st1, st2;
1092 if (!pwd || stat( pwd, &st1 ) == -1 ||
1093 (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
1094 pwd = cwd;
1097 if (pwd)
1099 ANSI_STRING unix_name;
1100 UNICODE_STRING nt_name;
1101 RtlInitAnsiString( &unix_name, pwd );
1102 if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
1104 UNICODE_STRING dos_path;
1105 /* skip the \??\ prefix, nt_name is 0 terminated */
1106 RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
1107 RtlSetCurrentDirectory_U( &dos_path );
1108 RtlFreeUnicodeString( &nt_name );
1112 if (!cur_dir->DosPath.Length) /* still not initialized */
1114 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
1115 "starting in the Windows directory.\n", cwd ? cwd : "" );
1116 RtlInitUnicodeString( &dir_str, DIR_Windows );
1117 RtlSetCurrentDirectory_U( &dir_str );
1119 HeapFree( GetProcessHeap(), 0, cwd );
1121 done:
1122 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
1126 /***********************************************************************
1127 * init_windows_dirs
1129 * Create the windows and system directories if necessary.
1131 static void init_windows_dirs(void)
1133 static const WCHAR default_syswow64W[] = {'C',':','\\','w','i','n','d','o','w','s',
1134 '\\','s','y','s','w','o','w','6','4',0};
1136 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1137 ERR( "directory %s could not be created, error %u\n",
1138 debugstr_w(DIR_Windows), GetLastError() );
1139 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1140 ERR( "directory %s could not be created, error %u\n",
1141 debugstr_w(DIR_System), GetLastError() );
1143 if (is_win64 || is_wow64) /* SysWow64 is always defined on 64-bit */
1145 DIR_SysWow64 = default_syswow64W;
1146 memcpy( winevdm, default_syswow64W, sizeof(default_syswow64W) - sizeof(WCHAR) );
1147 if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
1148 ERR( "directory %s could not be created, error %u\n",
1149 debugstr_w(DIR_SysWow64), GetLastError() );
1154 /***********************************************************************
1155 * start_wineboot
1157 * Start the wineboot process if necessary. Return the handles to wait on.
1159 static void start_wineboot( HANDLE handles[2] )
1161 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1163 handles[1] = 0;
1164 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
1166 ERR( "failed to create wineboot event, expect trouble\n" );
1167 return;
1169 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
1171 static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1172 static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
1173 STARTUPINFOW si;
1174 PROCESS_INFORMATION pi;
1175 void *redir;
1176 WCHAR app[MAX_PATH];
1177 WCHAR cmdline[MAX_PATH + ARRAY_SIZE( wineboot ) + ARRAY_SIZE( args )];
1179 memset( &si, 0, sizeof(si) );
1180 si.cb = sizeof(si);
1181 si.dwFlags = STARTF_USESTDHANDLES;
1182 si.hStdInput = 0;
1183 si.hStdOutput = 0;
1184 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1186 GetSystemDirectoryW( app, MAX_PATH - ARRAY_SIZE( wineboot ));
1187 lstrcatW( app, wineboot );
1189 Wow64DisableWow64FsRedirection( &redir );
1190 strcpyW( cmdline, app );
1191 strcatW( cmdline, args );
1192 if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
1194 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
1195 CloseHandle( pi.hThread );
1196 handles[1] = pi.hProcess;
1198 else
1200 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1201 CloseHandle( handles[0] );
1202 handles[0] = 0;
1204 Wow64RevertWow64FsRedirection( redir );
1209 #ifdef __i386__
1210 extern DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry );
1211 __ASM_GLOBAL_FUNC( call_process_entry,
1212 "pushl %ebp\n\t"
1213 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1214 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1215 "movl %esp,%ebp\n\t"
1216 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1217 "pushl 4(%ebp)\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1218 "pushl 4(%ebp)\n\t" /* Driller expects readable address at this offset */
1219 "pushl 4(%ebp)\n\t"
1220 "pushl 8(%ebp)\n\t"
1221 "call *12(%ebp)\n\t"
1222 "leave\n\t"
1223 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1224 __ASM_CFI(".cfi_same_value %ebp\n\t")
1225 "ret" )
1227 extern void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb ) DECLSPEC_HIDDEN;
1228 extern void WINAPI start_process_wrapper(void) DECLSPEC_HIDDEN;
1229 __ASM_GLOBAL_FUNC( start_process_wrapper,
1230 "pushl %ebp\n\t"
1231 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1232 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1233 "movl %esp,%ebp\n\t"
1234 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1235 "pushl %ebx\n\t" /* arg */
1236 "pushl %eax\n\t" /* entry */
1237 "call " __ASM_NAME("start_process") )
1238 #else
1239 static inline DWORD call_process_entry( PEB *peb, LPTHREAD_START_ROUTINE entry )
1241 return entry( peb );
1243 static void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb );
1244 #define start_process_wrapper start_process
1245 #endif
1247 /***********************************************************************
1248 * start_process
1250 * Startup routine of a new process. Runs on the new process stack.
1252 void WINAPI start_process( LPTHREAD_START_ROUTINE entry, PEB *peb )
1254 BOOL being_debugged;
1256 if (!entry)
1258 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1259 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1260 ExitThread( 1 );
1263 TRACE_(relay)( "\1Starting process %s (entryproc=%p)\n",
1264 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1266 __TRY
1268 if (!CheckRemoteDebuggerPresent( GetCurrentProcess(), &being_debugged ))
1269 being_debugged = FALSE;
1271 SetLastError( 0 ); /* clear error code */
1272 if (being_debugged) DbgBreakPoint();
1273 ExitThread( call_process_entry( peb, entry ));
1275 __EXCEPT(UnhandledExceptionFilter)
1277 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1279 __ENDTRY
1280 abort(); /* should not be reached */
1284 /***********************************************************************
1285 * set_process_name
1287 * Change the process name in the ps output.
1289 static void set_process_name( int argc, char *argv[] )
1291 BOOL shift_strings;
1292 char *p, *name;
1293 int i;
1295 #ifdef HAVE_SETPROCTITLE
1296 setproctitle("-%s", argv[1]);
1297 shift_strings = FALSE;
1298 #else
1299 p = argv[0];
1301 shift_strings = (argc >= 2);
1302 for (i = 1; i < argc; i++)
1304 p += strlen(p) + 1;
1305 if (p != argv[i])
1307 shift_strings = FALSE;
1308 break;
1311 #endif
1313 if (shift_strings)
1315 int offset = argv[1] - argv[0];
1316 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1317 memmove( argv[0], argv[1], end - argv[1] );
1318 memset( end - offset, 0, offset );
1319 for (i = 1; i < argc; i++)
1320 argv[i-1] = argv[i] - offset;
1321 argv[i-1] = NULL;
1323 else
1325 /* remove argv[0] */
1326 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1329 name = argv[0];
1330 if ((p = strrchr( name, '\\' ))) name = p + 1;
1331 if ((p = strrchr( name, '/' ))) name = p + 1;
1333 #if defined(HAVE_SETPROGNAME)
1334 setprogname( name );
1335 #endif
1337 #ifdef HAVE_PRCTL
1338 #ifndef PR_SET_NAME
1339 # define PR_SET_NAME 15
1340 #endif
1341 prctl( PR_SET_NAME, name );
1342 #endif /* HAVE_PRCTL */
1346 /***********************************************************************
1347 * __wine_kernel_init
1349 * Wine initialisation: load and start the main exe file.
1351 void CDECL __wine_kernel_init(void)
1353 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1354 static const WCHAR dotW[] = {'.',0};
1356 WCHAR *p, main_exe_name[MAX_PATH+1];
1357 PEB *peb = NtCurrentTeb()->Peb;
1358 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1359 HANDLE boot_events[2];
1360 BOOL got_environment = TRUE;
1362 /* Initialize everything */
1364 setbuf(stdout,NULL);
1365 setbuf(stderr,NULL);
1366 kernel32_handle = GetModuleHandleW(kernel32W);
1367 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1368 RtlSetUnhandledExceptionFilter( UnhandledExceptionFilter );
1370 LOCALE_Init();
1372 if (!params->Environment)
1374 /* Copy the parent environment */
1375 if (!build_initial_environment()) exit(1);
1377 /* convert old configuration to new format */
1378 convert_old_config();
1380 got_environment = set_registry_environment( FALSE );
1381 set_additional_environment();
1384 init_windows_dirs();
1385 init_current_directory( &params->CurrentDirectory );
1387 set_process_name( __wine_main_argc, __wine_main_argv );
1388 set_library_wargv( __wine_main_argv );
1389 boot_events[0] = boot_events[1] = 0;
1391 if (peb->ProcessParameters->ImagePathName.Buffer)
1393 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1395 else
1397 BOOL is_64bit;
1399 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1400 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &is_64bit ))
1402 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1403 ExitProcess( GetLastError() );
1405 update_library_argv0( main_exe_name );
1406 if (!build_command_line( __wine_main_wargv )) goto error;
1407 start_wineboot( boot_events );
1410 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1411 p = strrchrW( main_exe_name, '.' );
1412 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1414 TRACE( "starting process name=%s argv[0]=%s\n",
1415 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1417 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1418 MODULE_get_dll_load_path( main_exe_name, -1 ));
1420 if (boot_events[0])
1422 DWORD timeout = 2 * 60 * 1000, count = 1;
1424 if (boot_events[1]) count++;
1425 if (!got_environment) timeout = 5 * 60 * 1000; /* initial prefix creation can take longer */
1426 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1427 ERR( "boot event wait timed out\n" );
1428 CloseHandle( boot_events[0] );
1429 if (boot_events[1]) CloseHandle( boot_events[1] );
1430 /* reload environment now that wineboot has run */
1431 set_registry_environment( got_environment );
1432 set_additional_environment();
1434 set_wow64_environment();
1436 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1438 DWORD_PTR args[1];
1439 WCHAR msgW[1024];
1440 char msg[1024];
1441 DWORD error = GetLastError();
1443 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1444 if (error == ERROR_BAD_EXE_FORMAT ||
1445 error == ERROR_INVALID_ADDRESS ||
1446 error == ERROR_NOT_ENOUGH_MEMORY)
1448 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1449 /* if we get back here, it failed */
1451 else if (error == ERROR_MOD_NOT_FOUND)
1453 if (!strcmpiW( main_exe_name, winevdm ) && __wine_main_argc > 3)
1455 /* args 1 and 2 are --app-name full_path */
1456 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1457 debugstr_w(__wine_main_wargv[3]) );
1458 ExitProcess( ERROR_BAD_EXE_FORMAT );
1460 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name) );
1461 ExitProcess( ERROR_FILE_NOT_FOUND );
1463 args[0] = (DWORD_PTR)main_exe_name;
1464 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1465 NULL, error, 0, msgW, ARRAY_SIZE( msgW ), (__ms_va_list *)args );
1466 WideCharToMultiByte( CP_UNIXCP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1467 MESSAGE( "wine: %s", msg );
1468 ExitProcess( error );
1471 if (!params->CurrentDirectory.Handle) chdir("/"); /* avoid locking removable devices */
1473 LdrInitializeThunk( start_process_wrapper, 0, 0, 0 );
1475 error:
1476 ExitProcess( GetLastError() );
1480 /***********************************************************************
1481 * build_argv
1483 * Build an argv array from a command-line.
1484 * 'reserved' is the number of args to reserve before the first one.
1486 static char **build_argv( const UNICODE_STRING *cmdlineW, int reserved )
1488 int argc;
1489 char** argv;
1490 char *arg,*s,*d,*cmdline;
1491 int in_quotes,bcount,len;
1493 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW->Buffer, cmdlineW->Length / sizeof(WCHAR),
1494 NULL, 0, NULL, NULL );
1495 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1496 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW->Buffer, cmdlineW->Length / sizeof(WCHAR),
1497 cmdline, len, NULL, NULL );
1498 cmdline[len++] = 0;
1500 argc=reserved+1;
1501 bcount=0;
1502 in_quotes=0;
1503 s=cmdline;
1504 while (1) {
1505 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1506 /* space */
1507 argc++;
1508 /* skip the remaining spaces */
1509 while (*s==' ' || *s=='\t') {
1510 s++;
1512 if (*s=='\0')
1513 break;
1514 bcount=0;
1515 continue;
1516 } else if (*s=='\\') {
1517 /* '\', count them */
1518 bcount++;
1519 } else if ((*s=='"') && ((bcount & 1)==0)) {
1520 /* unescaped '"' */
1521 in_quotes=!in_quotes;
1522 bcount=0;
1523 } else {
1524 /* a regular character */
1525 bcount=0;
1527 s++;
1529 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1531 HeapFree( GetProcessHeap(), 0, cmdline );
1532 return NULL;
1535 arg = d = s = (char *)(argv + argc);
1536 memcpy( d, cmdline, len );
1537 bcount=0;
1538 in_quotes=0;
1539 argc=reserved;
1540 while (*s) {
1541 if ((*s==' ' || *s=='\t') && !in_quotes) {
1542 /* Close the argument and copy it */
1543 *d=0;
1544 argv[argc++]=arg;
1546 /* skip the remaining spaces */
1547 do {
1548 s++;
1549 } while (*s==' ' || *s=='\t');
1551 /* Start with a new argument */
1552 arg=d=s;
1553 bcount=0;
1554 } else if (*s=='\\') {
1555 /* '\\' */
1556 *d++=*s++;
1557 bcount++;
1558 } else if (*s=='"') {
1559 /* '"' */
1560 if ((bcount & 1)==0) {
1561 /* Preceded by an even number of '\', this is half that
1562 * number of '\', plus a '"' which we discard.
1564 d-=bcount/2;
1565 s++;
1566 in_quotes=!in_quotes;
1567 } else {
1568 /* Preceded by an odd number of '\', this is half that
1569 * number of '\' followed by a '"'
1571 d=d-bcount/2-1;
1572 *d++='"';
1573 s++;
1575 bcount=0;
1576 } else {
1577 /* a regular character */
1578 *d++=*s++;
1579 bcount=0;
1582 if (*arg) {
1583 *d='\0';
1584 argv[argc++]=arg;
1586 argv[argc]=NULL;
1588 HeapFree( GetProcessHeap(), 0, cmdline );
1589 return argv;
1593 /***********************************************************************
1594 * build_envp
1596 * Build the environment of a new child process.
1598 static char **build_envp( const WCHAR *envW )
1600 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1602 const WCHAR *end;
1603 char **envp;
1604 char *env, *p;
1605 int count = 1, length;
1606 unsigned int i;
1608 for (end = envW; *end; count++) end += strlenW(end) + 1;
1609 end++;
1610 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1611 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1612 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1614 for (p = env; *p; p += strlen(p) + 1)
1615 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1617 for (i = 0; i < ARRAY_SIZE( unix_vars ); i++)
1619 if (!(p = getenv(unix_vars[i]))) continue;
1620 length += strlen(unix_vars[i]) + strlen(p) + 2;
1621 count++;
1624 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1626 char **envptr = envp;
1627 char *dst = (char *)(envp + count);
1629 /* some variables must not be modified, so we get them directly from the unix env */
1630 for (i = 0; i < ARRAY_SIZE( unix_vars ); i++)
1632 if (!(p = getenv(unix_vars[i]))) continue;
1633 *envptr++ = strcpy( dst, unix_vars[i] );
1634 strcat( dst, "=" );
1635 strcat( dst, p );
1636 dst += strlen(dst) + 1;
1639 /* now put the Windows environment strings */
1640 for (p = env; *p; p += strlen(p) + 1)
1642 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1643 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1644 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1645 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1646 if (is_special_env_var( p )) /* prefix it with "WINE" */
1648 *envptr++ = strcpy( dst, "WINE" );
1649 strcat( dst, p );
1651 else
1653 *envptr++ = strcpy( dst, p );
1655 dst += strlen(dst) + 1;
1657 *envptr = 0;
1659 HeapFree( GetProcessHeap(), 0, env );
1660 return envp;
1664 /***********************************************************************
1665 * fork_and_exec
1667 * Fork and exec a new Unix binary, checking for errors.
1669 static int fork_and_exec( const RTL_USER_PROCESS_PARAMETERS *params, const char *newdir )
1671 int fd[2], stdin_fd = -1, stdout_fd = -1, stderr_fd = -1;
1672 int pid, err;
1673 char *filename, **argv, **envp;
1675 if (!(filename = wine_get_unix_file_name( params->ImagePathName.Buffer ))) return -1;
1677 #ifdef HAVE_PIPE2
1678 if (pipe2( fd, O_CLOEXEC ) == -1)
1679 #endif
1681 if (pipe(fd) == -1)
1683 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1684 HeapFree( GetProcessHeap(), 0, filename );
1685 return -1;
1687 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1688 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1691 wine_server_handle_to_fd( params->hStdInput, FILE_READ_DATA, &stdin_fd, NULL );
1692 wine_server_handle_to_fd( params->hStdOutput, FILE_WRITE_DATA, &stdout_fd, NULL );
1693 wine_server_handle_to_fd( params->hStdError, FILE_WRITE_DATA, &stderr_fd, NULL );
1695 argv = build_argv( &params->CommandLine, 0 );
1696 envp = build_envp( params->Environment );
1698 if (!(pid = fork())) /* child */
1700 if (!(pid = fork())) /* grandchild */
1702 close( fd[0] );
1704 if (params->ConsoleFlags || params->ConsoleHandle == KERNEL32_CONSOLE_ALLOC ||
1705 (params->hStdInput == INVALID_HANDLE_VALUE && params->hStdOutput == INVALID_HANDLE_VALUE))
1707 int nullfd = open( "/dev/null", O_RDWR );
1708 setsid();
1709 /* close stdin and stdout */
1710 if (nullfd != -1)
1712 dup2( nullfd, 0 );
1713 dup2( nullfd, 1 );
1714 close( nullfd );
1717 else
1719 if (stdin_fd != -1)
1721 dup2( stdin_fd, 0 );
1722 close( stdin_fd );
1724 if (stdout_fd != -1)
1726 dup2( stdout_fd, 1 );
1727 close( stdout_fd );
1729 if (stderr_fd != -1)
1731 dup2( stderr_fd, 2 );
1732 close( stderr_fd );
1736 /* Reset signals that we previously set to SIG_IGN */
1737 signal( SIGPIPE, SIG_DFL );
1739 if (newdir) chdir(newdir);
1741 if (argv && envp) execve( filename, argv, envp );
1744 if (pid <= 0) /* grandchild if exec failed or child if fork failed */
1746 err = errno;
1747 write( fd[1], &err, sizeof(err) );
1748 _exit(1);
1751 _exit(0); /* child if fork succeeded */
1753 HeapFree( GetProcessHeap(), 0, argv );
1754 HeapFree( GetProcessHeap(), 0, envp );
1755 HeapFree( GetProcessHeap(), 0, filename );
1756 if (stdin_fd != -1) close( stdin_fd );
1757 if (stdout_fd != -1) close( stdout_fd );
1758 if (stderr_fd != -1) close( stderr_fd );
1759 close( fd[1] );
1760 if (pid != -1)
1762 /* reap child */
1763 do {
1764 err = waitpid(pid, NULL, 0);
1765 } while (err < 0 && errno == EINTR);
1767 if (read( fd[0], &err, sizeof(err) ) > 0) /* exec or second fork failed */
1769 errno = err;
1770 pid = -1;
1773 if (pid == -1) FILE_SetDosError();
1774 close( fd[0] );
1775 return pid;
1779 static inline const WCHAR *get_params_string( const RTL_USER_PROCESS_PARAMETERS *params,
1780 const UNICODE_STRING *str )
1782 if (params->Flags & PROCESS_PARAMS_FLAG_NORMALIZED) return str->Buffer;
1783 return (const WCHAR *)((const char *)params + (UINT_PTR)str->Buffer);
1786 static inline DWORD append_string( void **ptr, const RTL_USER_PROCESS_PARAMETERS *params,
1787 const UNICODE_STRING *str )
1789 const WCHAR *buffer = get_params_string( params, str );
1790 memcpy( *ptr, buffer, str->Length );
1791 *ptr = (WCHAR *)*ptr + str->Length / sizeof(WCHAR);
1792 return str->Length;
1795 /***********************************************************************
1796 * create_startup_info
1798 static startup_info_t *create_startup_info( const RTL_USER_PROCESS_PARAMETERS *params, DWORD *info_size )
1800 startup_info_t *info;
1801 DWORD size;
1802 void *ptr;
1804 size = sizeof(*info);
1805 size += params->CurrentDirectory.DosPath.Length;
1806 size += params->DllPath.Length;
1807 size += params->ImagePathName.Length;
1808 size += params->CommandLine.Length;
1809 size += params->WindowTitle.Length;
1810 size += params->Desktop.Length;
1811 size += params->ShellInfo.Length;
1812 size += params->RuntimeInfo.Length;
1813 size = (size + 1) & ~1;
1814 *info_size = size;
1816 if (!(info = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) return NULL;
1818 info->console_flags = params->ConsoleFlags;
1819 info->console = wine_server_obj_handle( params->ConsoleHandle );
1820 info->hstdin = wine_server_obj_handle( params->hStdInput );
1821 info->hstdout = wine_server_obj_handle( params->hStdOutput );
1822 info->hstderr = wine_server_obj_handle( params->hStdError );
1823 info->x = params->dwX;
1824 info->y = params->dwY;
1825 info->xsize = params->dwXSize;
1826 info->ysize = params->dwYSize;
1827 info->xchars = params->dwXCountChars;
1828 info->ychars = params->dwYCountChars;
1829 info->attribute = params->dwFillAttribute;
1830 info->flags = params->dwFlags;
1831 info->show = params->wShowWindow;
1833 ptr = info + 1;
1834 info->curdir_len = append_string( &ptr, params, &params->CurrentDirectory.DosPath );
1835 info->dllpath_len = append_string( &ptr, params, &params->DllPath );
1836 info->imagepath_len = append_string( &ptr, params, &params->ImagePathName );
1837 info->cmdline_len = append_string( &ptr, params, &params->CommandLine );
1838 info->title_len = append_string( &ptr, params, &params->WindowTitle );
1839 info->desktop_len = append_string( &ptr, params, &params->Desktop );
1840 info->shellinfo_len = append_string( &ptr, params, &params->ShellInfo );
1841 info->runtime_len = append_string( &ptr, params, &params->RuntimeInfo );
1842 return info;
1846 /***********************************************************************
1847 * create_process_params
1849 static RTL_USER_PROCESS_PARAMETERS *create_process_params( LPCWSTR filename, LPCWSTR cmdline,
1850 LPCWSTR cur_dir, void *env, DWORD flags,
1851 const STARTUPINFOW *startup )
1853 RTL_USER_PROCESS_PARAMETERS *params;
1854 UNICODE_STRING imageW, curdirW, cmdlineW, titleW, desktopW, runtimeW, newdirW;
1855 WCHAR imagepath[MAX_PATH];
1856 WCHAR *envW = env;
1858 if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1859 lstrcpynW( imagepath, filename, MAX_PATH );
1860 if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1861 lstrcpynW( imagepath, filename, MAX_PATH );
1863 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1865 char *e = env;
1866 DWORD lenW;
1868 while (*e) e += strlen(e) + 1;
1869 e++; /* final null */
1870 lenW = MultiByteToWideChar( CP_ACP, 0, env, e - (char *)env, NULL, 0 );
1871 if ((envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
1872 MultiByteToWideChar( CP_ACP, 0, env, e - (char *)env, envW, lenW );
1875 newdirW.Buffer = NULL;
1876 if (cur_dir)
1878 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdirW, NULL, NULL ))
1879 cur_dir = newdirW.Buffer + 4; /* skip \??\ prefix */
1880 else
1881 cur_dir = NULL;
1883 RtlInitUnicodeString( &imageW, imagepath );
1884 RtlInitUnicodeString( &curdirW, cur_dir );
1885 RtlInitUnicodeString( &cmdlineW, cmdline );
1886 RtlInitUnicodeString( &titleW, startup->lpTitle ? startup->lpTitle : imagepath );
1887 RtlInitUnicodeString( &desktopW, startup->lpDesktop );
1888 runtimeW.Buffer = (WCHAR *)startup->lpReserved2;
1889 runtimeW.Length = runtimeW.MaximumLength = startup->cbReserved2;
1890 if (RtlCreateProcessParametersEx( &params, &imageW, NULL, &curdirW, &cmdlineW, envW, &titleW,
1891 &desktopW, NULL, &runtimeW, PROCESS_PARAMS_FLAG_NORMALIZED ))
1893 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1894 return NULL;
1897 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1898 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = KERNEL32_CONSOLE_ALLOC;
1900 if (startup->dwFlags & STARTF_USESTDHANDLES)
1902 params->hStdInput = startup->hStdInput;
1903 params->hStdOutput = startup->hStdOutput;
1904 params->hStdError = startup->hStdError;
1906 else if (flags & DETACHED_PROCESS)
1908 params->hStdInput = INVALID_HANDLE_VALUE;
1909 params->hStdOutput = INVALID_HANDLE_VALUE;
1910 params->hStdError = INVALID_HANDLE_VALUE;
1912 else
1914 params->hStdInput = NtCurrentTeb()->Peb->ProcessParameters->hStdInput;
1915 params->hStdOutput = NtCurrentTeb()->Peb->ProcessParameters->hStdOutput;
1916 params->hStdError = NtCurrentTeb()->Peb->ProcessParameters->hStdError;
1919 if (flags & CREATE_NEW_CONSOLE)
1921 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1922 if (is_console_handle(params->hStdInput)) params->hStdInput = INVALID_HANDLE_VALUE;
1923 if (is_console_handle(params->hStdOutput)) params->hStdOutput = INVALID_HANDLE_VALUE;
1924 if (is_console_handle(params->hStdError)) params->hStdError = INVALID_HANDLE_VALUE;
1926 else
1928 if (is_console_handle(params->hStdInput)) params->hStdInput = (HANDLE)((UINT_PTR)params->hStdInput & ~3);
1929 if (is_console_handle(params->hStdOutput)) params->hStdOutput = (HANDLE)((UINT_PTR)params->hStdOutput & ~3);
1930 if (is_console_handle(params->hStdError)) params->hStdError = (HANDLE)((UINT_PTR)params->hStdError & ~3);
1933 params->dwX = startup->dwX;
1934 params->dwY = startup->dwY;
1935 params->dwXSize = startup->dwXSize;
1936 params->dwYSize = startup->dwYSize;
1937 params->dwXCountChars = startup->dwXCountChars;
1938 params->dwYCountChars = startup->dwYCountChars;
1939 params->dwFillAttribute = startup->dwFillAttribute;
1940 params->dwFlags = startup->dwFlags;
1941 params->wShowWindow = startup->wShowWindow;
1943 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1944 return params;
1947 /***********************************************************************
1948 * get_alternate_loader
1950 * Get the name of the alternate (32 or 64 bit) Wine loader.
1952 static const char *get_alternate_loader( char **ret_env )
1954 char *env;
1955 const char *loader = NULL;
1956 const char *loader_env = getenv( "WINELOADER" );
1958 *ret_env = NULL;
1960 if (wine_get_build_dir()) loader = is_win64 ? "loader/wine" : "server/../loader/wine64";
1962 if (loader_env)
1964 int len = strlen( loader_env );
1965 if (!is_win64)
1967 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len + 2 ))) return NULL;
1968 strcpy( env, "WINELOADER=" );
1969 strcat( env, loader_env );
1970 strcat( env, "64" );
1972 else
1974 if (!(env = HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len ))) return NULL;
1975 strcpy( env, "WINELOADER=" );
1976 strcat( env, loader_env );
1977 len += sizeof("WINELOADER=") - 1;
1978 if (!strcmp( env + len - 2, "64" )) env[len - 2] = 0;
1980 if (!loader)
1982 if ((loader = strrchr( env, '/' ))) loader++;
1983 else loader = env;
1985 *ret_env = env;
1987 if (!loader) loader = is_win64 ? "wine" : "wine64";
1988 return loader;
1991 #ifdef __APPLE__
1992 /***********************************************************************
1993 * terminate_main_thread
1995 * On some versions of Mac OS X, the execve system call fails with
1996 * ENOTSUP if the process has multiple threads. Wine is always multi-
1997 * threaded on Mac OS X because it specifically reserves the main thread
1998 * for use by the system frameworks (see apple_main_thread() in
1999 * libs/wine/loader.c). So, when we need to exec without first forking,
2000 * we need to terminate the main thread first. We do this by installing
2001 * a custom run loop source onto the main run loop and signaling it.
2002 * The source's "perform" callback is pthread_exit and it will be
2003 * executed on the main thread, terminating it.
2005 * Returns TRUE if there's still hope the main thread has terminated or
2006 * will soon. Return FALSE if we've given up.
2008 static BOOL terminate_main_thread(void)
2010 static int delayms;
2012 if (!delayms)
2014 CFRunLoopSourceContext source_context = { 0 };
2015 CFRunLoopSourceRef source;
2017 source_context.perform = pthread_exit;
2018 if (!(source = CFRunLoopSourceCreate( NULL, 0, &source_context )))
2019 return FALSE;
2021 CFRunLoopAddSource( CFRunLoopGetMain(), source, kCFRunLoopCommonModes );
2022 CFRunLoopSourceSignal( source );
2023 CFRunLoopWakeUp( CFRunLoopGetMain() );
2024 CFRelease( source );
2026 delayms = 20;
2029 if (delayms > 1000)
2030 return FALSE;
2032 usleep(delayms * 1000);
2033 delayms *= 2;
2035 return TRUE;
2037 #endif
2039 /***********************************************************************
2040 * spawn_loader
2042 static pid_t spawn_loader( const RTL_USER_PROCESS_PARAMETERS *params, int socketfd,
2043 const char *unixdir, char *winedebug, const pe_image_info_t *pe_info )
2045 pid_t pid;
2046 int stdin_fd = -1, stdout_fd = -1;
2047 char *wineloader = NULL;
2048 const char *loader = NULL;
2049 char **argv;
2051 argv = build_argv( &params->CommandLine, 1 );
2053 if (!is_win64 ^ !is_64bit_arch( pe_info->cpu ))
2054 loader = get_alternate_loader( &wineloader );
2056 wine_server_handle_to_fd( params->hStdInput, FILE_READ_DATA, &stdin_fd, NULL );
2057 wine_server_handle_to_fd( params->hStdOutput, FILE_WRITE_DATA, &stdout_fd, NULL );
2059 if (!(pid = fork())) /* child */
2061 if (!(pid = fork())) /* grandchild */
2063 char preloader_reserve[64], socket_env[64];
2064 ULONGLONG res_start = pe_info->base;
2065 ULONGLONG res_end = pe_info->base + pe_info->map_size;
2067 if (params->ConsoleFlags || params->ConsoleHandle == KERNEL32_CONSOLE_ALLOC ||
2068 (params->hStdInput == INVALID_HANDLE_VALUE && params->hStdOutput == INVALID_HANDLE_VALUE))
2070 int fd = open( "/dev/null", O_RDWR );
2071 setsid();
2072 /* close stdin and stdout */
2073 if (fd != -1)
2075 dup2( fd, 0 );
2076 dup2( fd, 1 );
2077 close( fd );
2080 else
2082 if (stdin_fd != -1) dup2( stdin_fd, 0 );
2083 if (stdout_fd != -1) dup2( stdout_fd, 1 );
2086 if (stdin_fd != -1) close( stdin_fd );
2087 if (stdout_fd != -1) close( stdout_fd );
2089 /* Reset signals that we previously set to SIG_IGN */
2090 signal( SIGPIPE, SIG_DFL );
2092 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
2093 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
2094 (ULONG)(res_start >> 32), (ULONG)res_start, (ULONG)(res_end >> 32), (ULONG)res_end );
2096 putenv( preloader_reserve );
2097 putenv( socket_env );
2098 if (winedebug) putenv( winedebug );
2099 if (wineloader) putenv( wineloader );
2100 if (unixdir) chdir(unixdir);
2102 if (argv) wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
2103 _exit(1);
2106 _exit(pid == -1);
2109 if (pid != -1)
2111 /* reap child */
2112 pid_t wret;
2113 do {
2114 wret = waitpid(pid, NULL, 0);
2115 } while (wret < 0 && errno == EINTR);
2118 if (stdin_fd != -1) close( stdin_fd );
2119 if (stdout_fd != -1) close( stdout_fd );
2120 HeapFree( GetProcessHeap(), 0, wineloader );
2121 HeapFree( GetProcessHeap(), 0, argv );
2122 return pid;
2125 /***********************************************************************
2126 * exec_loader
2128 static NTSTATUS exec_loader( const RTL_USER_PROCESS_PARAMETERS *params, int socketfd,
2129 const pe_image_info_t *pe_info )
2131 char *wineloader = NULL;
2132 const char *loader = NULL;
2133 char **argv;
2134 char preloader_reserve[64], socket_env[64];
2135 ULONGLONG res_start = pe_info->base;
2136 ULONGLONG res_end = pe_info->base + pe_info->map_size;
2138 if (!(argv = build_argv( &params->CommandLine, 1 ))) return STATUS_NO_MEMORY;
2140 if (!is_win64 ^ !is_64bit_arch( pe_info->cpu ))
2141 loader = get_alternate_loader( &wineloader );
2143 /* Reset signals that we previously set to SIG_IGN */
2144 signal( SIGPIPE, SIG_DFL );
2146 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd );
2147 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%x%08x-%x%08x",
2148 (ULONG)(res_start >> 32), (ULONG)res_start, (ULONG)(res_end >> 32), (ULONG)res_end );
2150 putenv( preloader_reserve );
2151 putenv( socket_env );
2152 if (wineloader) putenv( wineloader );
2156 wine_exec_wine_binary( loader, argv, getenv("WINELOADER") );
2158 #ifdef __APPLE__
2159 while (errno == ENOTSUP && terminate_main_thread());
2160 #else
2161 while (0);
2162 #endif
2164 HeapFree( GetProcessHeap(), 0, wineloader );
2165 HeapFree( GetProcessHeap(), 0, argv );
2166 return STATUS_INVALID_IMAGE_FORMAT;
2169 /* creates a struct security_descriptor and contained information in one contiguous piece of memory */
2170 static NTSTATUS alloc_object_attributes( const SECURITY_ATTRIBUTES *attr, struct object_attributes **ret,
2171 data_size_t *ret_len )
2173 unsigned int len = sizeof(**ret);
2174 PSID owner = NULL, group = NULL;
2175 ACL *dacl, *sacl;
2176 BOOLEAN dacl_present, sacl_present, defaulted;
2177 PSECURITY_DESCRIPTOR sd = NULL;
2178 NTSTATUS status;
2180 *ret = NULL;
2181 *ret_len = 0;
2183 if (attr) sd = attr->lpSecurityDescriptor;
2185 if (sd)
2187 len += sizeof(struct security_descriptor);
2189 if ((status = RtlGetOwnerSecurityDescriptor( sd, &owner, &defaulted ))) return status;
2190 if ((status = RtlGetGroupSecurityDescriptor( sd, &group, &defaulted ))) return status;
2191 if ((status = RtlGetSaclSecurityDescriptor( sd, &sacl_present, &sacl, &defaulted ))) return status;
2192 if ((status = RtlGetDaclSecurityDescriptor( sd, &dacl_present, &dacl, &defaulted ))) return status;
2193 if (owner) len += RtlLengthSid( owner );
2194 if (group) len += RtlLengthSid( group );
2195 if (sacl_present && sacl) len += sacl->AclSize;
2196 if (dacl_present && dacl) len += dacl->AclSize;
2199 len = (len + 3) & ~3; /* DWORD-align the entire structure */
2201 *ret = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, len );
2202 if (!*ret) return STATUS_NO_MEMORY;
2204 (*ret)->attributes = (attr && attr->bInheritHandle) ? OBJ_INHERIT : 0;
2206 if (sd)
2208 struct security_descriptor *descr = (struct security_descriptor *)(*ret + 1);
2209 unsigned char *ptr = (unsigned char *)(descr + 1);
2211 descr->control = ((SECURITY_DESCRIPTOR *)sd)->Control & ~SE_SELF_RELATIVE;
2212 if (owner) descr->owner_len = RtlLengthSid( owner );
2213 if (group) descr->group_len = RtlLengthSid( group );
2214 if (sacl_present && sacl) descr->sacl_len = sacl->AclSize;
2215 if (dacl_present && dacl) descr->dacl_len = dacl->AclSize;
2217 memcpy( ptr, owner, descr->owner_len );
2218 ptr += descr->owner_len;
2219 memcpy( ptr, group, descr->group_len );
2220 ptr += descr->group_len;
2221 memcpy( ptr, sacl, descr->sacl_len );
2222 ptr += descr->sacl_len;
2223 memcpy( ptr, dacl, descr->dacl_len );
2224 (*ret)->sd_len = (sizeof(*descr) + descr->owner_len + descr->group_len + descr->sacl_len +
2225 descr->dacl_len + sizeof(WCHAR) - 1) & ~(sizeof(WCHAR) - 1);
2227 *ret_len = len;
2228 return STATUS_SUCCESS;
2231 /***********************************************************************
2232 * replace_process
2234 * Replace the existing process by exec'ing a new one.
2236 static BOOL replace_process( HANDLE handle, const RTL_USER_PROCESS_PARAMETERS *params,
2237 const pe_image_info_t *pe_info )
2239 NTSTATUS status;
2240 int socketfd[2];
2242 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2244 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2245 return FALSE;
2247 #ifdef SO_PASSCRED
2248 else
2250 int enable = 1;
2251 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2253 #endif
2254 wine_server_send_fd( socketfd[1] );
2255 close( socketfd[1] );
2257 SERVER_START_REQ( exec_process )
2259 req->socket_fd = socketfd[1];
2260 req->exe_file = wine_server_obj_handle( handle );
2261 req->cpu = pe_info->cpu;
2262 status = wine_server_call( req );
2264 SERVER_END_REQ;
2266 switch (status)
2268 case STATUS_INVALID_IMAGE_WIN_64:
2269 ERR( "64-bit application %s not supported in 32-bit prefix\n",
2270 debugstr_w( params->ImagePathName.Buffer ));
2271 break;
2272 case STATUS_INVALID_IMAGE_FORMAT:
2273 ERR( "%s not supported on this installation (%s binary)\n",
2274 debugstr_w( params->ImagePathName.Buffer ), cpu_names[pe_info->cpu] );
2275 break;
2276 case STATUS_SUCCESS:
2277 status = exec_loader( params, socketfd[0], pe_info );
2278 break;
2280 close( socketfd[0] );
2281 SetLastError( RtlNtStatusToDosError( status ));
2282 return FALSE;
2286 /***********************************************************************
2287 * create_process
2289 * Create a new process. If hFile is a valid handle we have an exe
2290 * file, otherwise it is a Winelib app.
2292 static BOOL create_process( HANDLE hFile, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2293 BOOL inherit, DWORD flags, const RTL_USER_PROCESS_PARAMETERS *params,
2294 LPPROCESS_INFORMATION info, LPCSTR unixdir, const pe_image_info_t *pe_info )
2296 NTSTATUS status;
2297 BOOL success = FALSE;
2298 HANDLE process_info, process_handle = 0;
2299 struct object_attributes *objattr;
2300 data_size_t attr_len;
2301 WCHAR *env_end;
2302 char *winedebug = NULL;
2303 startup_info_t *startup_info;
2304 DWORD startup_info_size;
2305 int socketfd[2];
2306 pid_t pid;
2307 int err;
2309 /* create the socket for the new process */
2311 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
2313 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
2314 return FALSE;
2316 #ifdef SO_PASSCRED
2317 else
2319 int enable = 1;
2320 setsockopt( socketfd[0], SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
2322 #endif
2324 if (!(startup_info = create_startup_info( params, &startup_info_size )))
2326 close( socketfd[0] );
2327 close( socketfd[1] );
2328 return FALSE;
2330 env_end = params->Environment;
2331 while (*env_end)
2333 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
2334 if (!winedebug && !strncmpW( env_end, WINEDEBUG, ARRAY_SIZE( WINEDEBUG ) - 1 ))
2336 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
2337 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
2338 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
2340 env_end += strlenW(env_end) + 1;
2342 env_end++;
2344 wine_server_send_fd( socketfd[1] );
2345 close( socketfd[1] );
2347 /* create the process on the server side */
2349 alloc_object_attributes( psa, &objattr, &attr_len );
2350 SERVER_START_REQ( new_process )
2352 req->inherit_all = inherit;
2353 req->create_flags = flags;
2354 req->socket_fd = socketfd[1];
2355 req->exe_file = wine_server_obj_handle( hFile );
2356 req->access = PROCESS_ALL_ACCESS;
2357 req->cpu = pe_info->cpu;
2358 req->info_size = startup_info_size;
2359 wine_server_add_data( req, objattr, attr_len );
2360 wine_server_add_data( req, startup_info, startup_info_size );
2361 wine_server_add_data( req, params->Environment, (env_end - params->Environment) * sizeof(WCHAR) );
2362 if (!(status = wine_server_call( req )))
2364 info->dwProcessId = (DWORD)reply->pid;
2365 process_handle = wine_server_ptr_handle( reply->handle );
2367 process_info = wine_server_ptr_handle( reply->info );
2369 SERVER_END_REQ;
2370 HeapFree( GetProcessHeap(), 0, objattr );
2372 if (!status)
2374 alloc_object_attributes( tsa, &objattr, &attr_len );
2375 SERVER_START_REQ( new_thread )
2377 req->process = wine_server_obj_handle( process_handle );
2378 req->access = THREAD_ALL_ACCESS;
2379 req->suspend = !!(flags & CREATE_SUSPENDED);
2380 req->request_fd = -1;
2381 wine_server_add_data( req, objattr, attr_len );
2382 if (!(status = wine_server_call( req )))
2384 info->hProcess = process_handle;
2385 info->hThread = wine_server_ptr_handle( reply->handle );
2386 info->dwThreadId = reply->tid;
2389 SERVER_END_REQ;
2390 HeapFree( GetProcessHeap(), 0, objattr );
2393 if (status)
2395 switch (status)
2397 case STATUS_INVALID_IMAGE_WIN_64:
2398 ERR( "64-bit application %s not supported in 32-bit prefix\n",
2399 debugstr_w( params->ImagePathName.Buffer ));
2400 break;
2401 case STATUS_INVALID_IMAGE_FORMAT:
2402 ERR( "%s not supported on this installation (%s binary)\n",
2403 debugstr_w( params->ImagePathName.Buffer ), cpu_names[pe_info->cpu] );
2404 break;
2406 close( socketfd[0] );
2407 CloseHandle( process_handle );
2408 HeapFree( GetProcessHeap(), 0, startup_info );
2409 HeapFree( GetProcessHeap(), 0, winedebug );
2410 SetLastError( RtlNtStatusToDosError( status ));
2411 return FALSE;
2414 HeapFree( GetProcessHeap(), 0, startup_info );
2416 /* create the child process */
2418 pid = spawn_loader( params, socketfd[0], unixdir, winedebug, pe_info );
2420 close( socketfd[0] );
2421 HeapFree( GetProcessHeap(), 0, winedebug );
2422 if (pid == -1)
2424 FILE_SetDosError();
2425 goto error;
2428 /* wait for the new process info to be ready */
2430 WaitForSingleObject( process_info, INFINITE );
2431 SERVER_START_REQ( get_new_process_info )
2433 req->info = wine_server_obj_handle( process_info );
2434 wine_server_call( req );
2435 success = reply->success;
2436 err = reply->exit_code;
2438 SERVER_END_REQ;
2440 if (!success)
2442 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
2443 goto error;
2445 CloseHandle( process_info );
2446 return success;
2448 error:
2449 CloseHandle( process_info );
2450 CloseHandle( info->hProcess );
2451 CloseHandle( info->hThread );
2452 info->hProcess = info->hThread = 0;
2453 info->dwProcessId = info->dwThreadId = 0;
2454 return FALSE;
2458 /***********************************************************************
2459 * get_vdm_params
2461 * Build the parameters needed to launch a new VDM process.
2463 static RTL_USER_PROCESS_PARAMETERS *get_vdm_params( const RTL_USER_PROCESS_PARAMETERS *params,
2464 pe_image_info_t *pe_info )
2466 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2468 WCHAR *new_cmd_line;
2469 RTL_USER_PROCESS_PARAMETERS *new_params;
2470 UNICODE_STRING imageW, cmdlineW;
2472 new_cmd_line = HeapAlloc(GetProcessHeap(), 0,
2473 (strlenW(params->ImagePathName.Buffer) +
2474 strlenW(params->CommandLine.Buffer) +
2475 strlenW(winevdm) + 16) * sizeof(WCHAR));
2476 if (!new_cmd_line)
2478 SetLastError( ERROR_OUTOFMEMORY );
2479 return NULL;
2481 sprintfW( new_cmd_line, argsW, winevdm, params->ImagePathName.Buffer, params->CommandLine.Buffer );
2482 RtlInitUnicodeString( &imageW, winevdm );
2483 RtlInitUnicodeString( &cmdlineW, new_cmd_line );
2484 if (RtlCreateProcessParametersEx( &new_params, &imageW, &params->DllPath,
2485 &params->CurrentDirectory.DosPath, &cmdlineW,
2486 params->Environment, &params->WindowTitle, &params->Desktop,
2487 &params->ShellInfo, &params->RuntimeInfo,
2488 PROCESS_PARAMS_FLAG_NORMALIZED ))
2490 HeapFree( GetProcessHeap(), 0, new_cmd_line );
2491 SetLastError( ERROR_OUTOFMEMORY );
2492 return FALSE;
2494 new_params->hStdInput = params->hStdInput;
2495 new_params->hStdOutput = params->hStdOutput;
2496 new_params->hStdError = params->hStdError;
2497 new_params->dwX = params->dwX;
2498 new_params->dwY = params->dwY;
2499 new_params->dwXSize = params->dwXSize;
2500 new_params->dwYSize = params->dwYSize;
2501 new_params->dwXCountChars = params->dwXCountChars;
2502 new_params->dwYCountChars = params->dwYCountChars;
2503 new_params->dwFillAttribute = params->dwFillAttribute;
2504 new_params->dwFlags = params->dwFlags;
2505 new_params->wShowWindow = params->wShowWindow;
2507 memset( pe_info, 0, sizeof(*pe_info) );
2508 pe_info->cpu = CPU_x86;
2509 return new_params;
2513 /***********************************************************************
2514 * create_vdm_process
2516 * Create a new VDM process for a 16-bit or DOS application.
2518 static BOOL create_vdm_process( LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2519 BOOL inherit, DWORD flags, const RTL_USER_PROCESS_PARAMETERS *params,
2520 LPPROCESS_INFORMATION info, LPCSTR unixdir )
2522 BOOL ret;
2523 pe_image_info_t pe_info;
2524 RTL_USER_PROCESS_PARAMETERS *new_params;
2526 if (!(new_params = get_vdm_params( params, &pe_info ))) return FALSE;
2528 ret = create_process( 0, psa, tsa, inherit, flags, new_params, info, unixdir, &pe_info );
2529 RtlDestroyProcessParameters( new_params );
2530 return ret;
2534 /***********************************************************************
2535 * create_cmd_process
2537 * Create a new cmd shell process for a .BAT file.
2539 static BOOL create_cmd_process( LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
2540 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
2541 const RTL_USER_PROCESS_PARAMETERS *params,
2542 LPPROCESS_INFORMATION info )
2545 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
2546 static const WCHAR cmdW[] = {'\\','c','m','d','.','e','x','e',0};
2547 static const WCHAR slashscW[] = {' ','/','s','/','c',' ',0};
2548 static const WCHAR quotW[] = {'"',0};
2549 WCHAR comspec[MAX_PATH];
2550 WCHAR *newcmdline, *cur_dir = NULL;
2551 BOOL ret;
2553 if (!GetEnvironmentVariableW( comspecW, comspec, ARRAY_SIZE( comspec )))
2555 GetSystemDirectoryW( comspec, (sizeof(comspec) - sizeof(cmdW))/sizeof(WCHAR) );
2556 strcatW( comspec, cmdW );
2558 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
2559 (strlenW(comspec) + 7 +
2560 strlenW(params->CommandLine.Buffer) + 2) * sizeof(WCHAR))))
2561 return FALSE;
2563 strcpyW( newcmdline, comspec );
2564 strcatW( newcmdline, slashscW );
2565 strcatW( newcmdline, quotW );
2566 strcatW( newcmdline, params->CommandLine.Buffer );
2567 strcatW( newcmdline, quotW );
2568 if (params->CurrentDirectory.DosPath.Length) cur_dir = params->CurrentDirectory.DosPath.Buffer;
2569 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
2570 flags | CREATE_UNICODE_ENVIRONMENT, params->Environment, cur_dir,
2571 startup, info );
2572 HeapFree( GetProcessHeap(), 0, newcmdline );
2573 return ret;
2577 /*************************************************************************
2578 * get_file_name
2580 * Helper for CreateProcess: retrieve the file name to load from the
2581 * app name and command line. Store the file name in buffer, and
2582 * return a possibly modified command line.
2583 * Also returns a handle to the opened file if it's a Windows binary.
2585 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
2586 int buflen, HANDLE *handle, BOOL *is_64bit )
2588 static const WCHAR quotesW[] = {'"','%','s','"',0};
2590 WCHAR *name, *pos, *first_space, *ret = NULL;
2591 const WCHAR *p;
2593 /* if we have an app name, everything is easy */
2595 if (appname)
2597 /* use the unmodified app name as file name */
2598 lstrcpynW( buffer, appname, buflen );
2599 *handle = open_exe_file( buffer, is_64bit );
2600 if (!(ret = cmdline) || !cmdline[0])
2602 /* no command-line, create one */
2603 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
2604 sprintfW( ret, quotesW, appname );
2606 return ret;
2609 /* first check for a quoted file name */
2611 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
2613 int len = p - cmdline - 1;
2614 /* extract the quoted portion as file name */
2615 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
2616 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
2617 name[len] = 0;
2619 if (!find_exe_file( name, buffer, buflen, handle )) goto done;
2620 ret = cmdline; /* no change necessary */
2621 goto done;
2624 /* now try the command-line word by word */
2626 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
2627 return NULL;
2628 pos = name;
2629 p = cmdline;
2630 first_space = NULL;
2632 for (;;)
2634 while (*p && *p != ' ' && *p != '\t') *pos++ = *p++;
2635 *pos = 0;
2636 if (find_exe_file( name, buffer, buflen, handle ))
2638 ret = cmdline;
2639 break;
2641 if (!first_space) first_space = pos;
2642 if (!(*pos++ = *p++)) break;
2645 if (!ret)
2647 SetLastError( ERROR_FILE_NOT_FOUND );
2649 else if (first_space) /* build a new command-line with quotes */
2651 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
2652 goto done;
2653 sprintfW( ret, quotesW, name );
2654 strcatW( ret, p );
2657 done:
2658 HeapFree( GetProcessHeap(), 0, name );
2659 return ret;
2663 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2664 static BOOL create_process_impl( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2665 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2666 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2667 LPPROCESS_INFORMATION info )
2669 BOOL retv = FALSE;
2670 HANDLE hFile = 0;
2671 char *unixdir = NULL;
2672 WCHAR name[MAX_PATH];
2673 WCHAR *tidy_cmdline, *p;
2674 RTL_USER_PROCESS_PARAMETERS *params = NULL;
2675 pe_image_info_t pe_info;
2676 enum binary_type type;
2677 BOOL is_64bit;
2679 /* Process the AppName and/or CmdLine to get module name and path */
2681 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2683 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, ARRAY_SIZE( name ), &hFile, &is_64bit )))
2684 return FALSE;
2685 if (hFile == INVALID_HANDLE_VALUE) goto done;
2687 /* Warn if unsupported features are used */
2689 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2690 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2691 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2692 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2693 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2695 if (cur_dir)
2697 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2699 SetLastError(ERROR_DIRECTORY);
2700 goto done;
2703 else
2705 WCHAR buf[MAX_PATH];
2706 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2709 info->hThread = info->hProcess = 0;
2710 info->dwProcessId = info->dwThreadId = 0;
2712 if (!(params = create_process_params( name, tidy_cmdline, cur_dir, env, flags, startup_info )))
2714 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2715 goto done;
2718 if (!hFile)
2720 memset( &pe_info, 0, sizeof(pe_info) );
2721 type = BINARY_UNIX_LIB;
2722 /* assume current arch */
2723 #if defined(__i386__) || defined(__x86_64__)
2724 pe_info.cpu = is_64bit ? CPU_x86_64 : CPU_x86;
2725 #elif defined(__powerpc__)
2726 pe_info.cpu = CPU_POWERPC;
2727 #elif defined(__arm__)
2728 pe_info.cpu = CPU_ARM;
2729 #elif defined(__aarch64__)
2730 pe_info.cpu = CPU_ARM64;
2731 #endif
2733 else type = get_binary_info( hFile, &pe_info );
2735 switch (type)
2737 case BINARY_PE:
2738 if (pe_info.image_charact & IMAGE_FILE_DLL)
2740 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2741 SetLastError( ERROR_BAD_EXE_FORMAT );
2742 break;
2744 TRACE( "starting %s as Win%d binary (%s-%s, %s)\n",
2745 debugstr_w(name), is_64bit_arch(pe_info.cpu) ? 64 : 32,
2746 wine_dbgstr_longlong(pe_info.base), wine_dbgstr_longlong(pe_info.base + pe_info.map_size),
2747 cpu_names[pe_info.cpu] );
2748 retv = create_process( hFile, process_attr, thread_attr,
2749 inherit, flags, params, info, unixdir, &pe_info );
2750 break;
2751 case BINARY_WIN16:
2752 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2753 retv = create_vdm_process( process_attr, thread_attr, inherit, flags, params, info, unixdir );
2754 break;
2755 case BINARY_UNIX_LIB:
2756 TRACE( "starting %s as %d-bit Winelib app\n",
2757 debugstr_w(name), is_64bit_arch(pe_info.cpu) ? 64 : 32 );
2758 retv = create_process( hFile, process_attr, thread_attr,
2759 inherit, flags, params, info, unixdir, &pe_info );
2760 break;
2761 case BINARY_UNKNOWN:
2762 /* check for .com or .bat extension */
2763 if ((p = strrchrW( name, '.' )))
2765 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2767 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2768 retv = create_vdm_process( process_attr, thread_attr,
2769 inherit, flags, params, info, unixdir );
2770 break;
2772 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2774 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2775 retv = create_cmd_process( process_attr, thread_attr,
2776 inherit, flags, startup_info, params, info );
2777 break;
2780 /* fall through */
2781 case BINARY_UNIX_EXE:
2782 /* unknown file, try as unix executable */
2783 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2784 retv = (fork_and_exec( params, unixdir ) != -1);
2785 break;
2787 if (hFile) CloseHandle( hFile );
2789 done:
2790 RtlDestroyProcessParameters( params );
2791 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2792 HeapFree( GetProcessHeap(), 0, unixdir );
2793 if (retv)
2794 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2795 return retv;
2799 /**********************************************************************
2800 * CreateProcessA (KERNEL32.@)
2802 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2803 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
2804 DWORD flags, LPVOID env, LPCSTR cur_dir,
2805 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
2807 BOOL ret = FALSE;
2808 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
2809 UNICODE_STRING desktopW, titleW;
2810 STARTUPINFOW infoW;
2812 desktopW.Buffer = NULL;
2813 titleW.Buffer = NULL;
2814 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
2815 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
2816 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
2818 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
2819 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
2821 memcpy( &infoW, startup_info, sizeof(infoW) );
2822 infoW.lpDesktop = desktopW.Buffer;
2823 infoW.lpTitle = titleW.Buffer;
2825 if (startup_info->lpReserved)
2826 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2827 debugstr_a(startup_info->lpReserved));
2829 ret = create_process_impl( app_nameW, cmd_lineW, process_attr, thread_attr,
2830 inherit, flags, env, cur_dirW, &infoW, info );
2831 done:
2832 HeapFree( GetProcessHeap(), 0, app_nameW );
2833 HeapFree( GetProcessHeap(), 0, cmd_lineW );
2834 HeapFree( GetProcessHeap(), 0, cur_dirW );
2835 RtlFreeUnicodeString( &desktopW );
2836 RtlFreeUnicodeString( &titleW );
2837 return ret;
2841 /**********************************************************************
2842 * CreateProcessW (KERNEL32.@)
2844 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2845 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2846 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2847 LPPROCESS_INFORMATION info )
2849 return create_process_impl( app_name, cmd_line, process_attr, thread_attr,
2850 inherit, flags, env, cur_dir, startup_info, info);
2854 /**********************************************************************
2855 * exec_process
2857 static void exec_process( LPCWSTR name )
2859 HANDLE hFile;
2860 WCHAR *p;
2861 STARTUPINFOW startup_info = { sizeof(startup_info) };
2862 RTL_USER_PROCESS_PARAMETERS *params, *new_params;
2863 pe_image_info_t pe_info;
2864 BOOL is_64bit;
2866 hFile = open_exe_file( name, &is_64bit );
2867 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2869 if (!(params = create_process_params( name, GetCommandLineW(), NULL, NULL, 0, &startup_info )))
2870 return;
2872 /* Determine executable type */
2874 switch (get_binary_info( hFile, &pe_info ))
2876 case BINARY_PE:
2877 if (pe_info.image_charact & IMAGE_FILE_DLL) break;
2878 TRACE( "starting %s as Win%d binary (%s-%s, %s)\n",
2879 debugstr_w(name), is_64bit_arch(pe_info.cpu) ? 64 : 32,
2880 wine_dbgstr_longlong(pe_info.base), wine_dbgstr_longlong(pe_info.base + pe_info.map_size),
2881 cpu_names[pe_info.cpu] );
2882 replace_process( hFile, params, &pe_info );
2883 break;
2884 case BINARY_UNIX_LIB:
2885 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2886 replace_process( hFile, params, &pe_info );
2887 break;
2888 case BINARY_UNKNOWN:
2889 /* check for .com or .pif extension */
2890 if (!(p = strrchrW( name, '.' ))) break;
2891 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2892 /* fall through */
2893 case BINARY_WIN16:
2894 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2895 if (!(new_params = get_vdm_params( params, &pe_info ))) break;
2896 replace_process( 0, new_params, &pe_info );
2897 RtlDestroyProcessParameters( new_params );
2898 break;
2899 default:
2900 break;
2902 CloseHandle( hFile );
2903 RtlDestroyProcessParameters( params );
2907 /***********************************************************************
2908 * wait_input_idle
2910 * Wrapper to call WaitForInputIdle USER function
2912 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2914 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2916 HMODULE mod = GetModuleHandleA( "user32.dll" );
2917 if (mod)
2919 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2920 if (ptr) return ptr( process, timeout );
2922 return 0;
2926 /***********************************************************************
2927 * WinExec (KERNEL32.@)
2929 UINT WINAPI DECLSPEC_HOTPATCH WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2931 PROCESS_INFORMATION info;
2932 STARTUPINFOA startup;
2933 char *cmdline;
2934 UINT ret;
2936 memset( &startup, 0, sizeof(startup) );
2937 startup.cb = sizeof(startup);
2938 startup.dwFlags = STARTF_USESHOWWINDOW;
2939 startup.wShowWindow = nCmdShow;
2941 /* cmdline needs to be writable for CreateProcess */
2942 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2943 strcpy( cmdline, lpCmdLine );
2945 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2946 0, NULL, NULL, &startup, &info ))
2948 /* Give 30 seconds to the app to come up */
2949 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2950 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2951 ret = 33;
2952 /* Close off the handles */
2953 CloseHandle( info.hThread );
2954 CloseHandle( info.hProcess );
2956 else if ((ret = GetLastError()) >= 32)
2958 FIXME("Strange error set by CreateProcess: %d\n", ret );
2959 ret = 11;
2961 HeapFree( GetProcessHeap(), 0, cmdline );
2962 return ret;
2966 /**********************************************************************
2967 * LoadModule (KERNEL32.@)
2969 DWORD WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2971 LOADPARMS32 *params = paramBlock;
2972 PROCESS_INFORMATION info;
2973 STARTUPINFOA startup;
2974 DWORD ret;
2975 LPSTR cmdline, p;
2976 char filename[MAX_PATH];
2977 BYTE len;
2979 if (!name) return ERROR_FILE_NOT_FOUND;
2981 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2982 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2983 return GetLastError();
2985 len = (BYTE)params->lpCmdLine[0];
2986 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2987 return ERROR_NOT_ENOUGH_MEMORY;
2989 strcpy( cmdline, filename );
2990 p = cmdline + strlen(cmdline);
2991 *p++ = ' ';
2992 memcpy( p, params->lpCmdLine + 1, len );
2993 p[len] = 0;
2995 memset( &startup, 0, sizeof(startup) );
2996 startup.cb = sizeof(startup);
2997 if (params->lpCmdShow)
2999 startup.dwFlags = STARTF_USESHOWWINDOW;
3000 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
3003 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
3004 params->lpEnvAddress, NULL, &startup, &info ))
3006 /* Give 30 seconds to the app to come up */
3007 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
3008 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
3009 ret = 33;
3010 /* Close off the handles */
3011 CloseHandle( info.hThread );
3012 CloseHandle( info.hProcess );
3014 else if ((ret = GetLastError()) >= 32)
3016 FIXME("Strange error set by CreateProcess: %u\n", ret );
3017 ret = 11;
3020 HeapFree( GetProcessHeap(), 0, cmdline );
3021 return ret;
3025 /******************************************************************************
3026 * TerminateProcess (KERNEL32.@)
3028 * Terminates a process.
3030 * PARAMS
3031 * handle [I] Process to terminate.
3032 * exit_code [I] Exit code.
3034 * RETURNS
3035 * Success: TRUE.
3036 * Failure: FALSE, check GetLastError().
3038 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
3040 NTSTATUS status;
3042 if (!handle)
3044 SetLastError( ERROR_INVALID_HANDLE );
3045 return FALSE;
3048 status = NtTerminateProcess( handle, exit_code );
3049 if (status) SetLastError( RtlNtStatusToDosError(status) );
3050 return !status;
3053 /***********************************************************************
3054 * ExitProcess (KERNEL32.@)
3056 * Exits the current process.
3058 * PARAMS
3059 * status [I] Status code to exit with.
3061 * RETURNS
3062 * Nothing.
3064 #ifdef __i386__
3065 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
3066 "pushl %ebp\n\t"
3067 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
3068 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
3069 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
3070 "pushl 8(%ebp)\n\t"
3071 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
3072 "leave\n\t"
3073 "ret $4" )
3074 #else
3076 void WINAPI ExitProcess( DWORD status )
3078 RtlExitUserProcess( status );
3081 #endif
3083 /***********************************************************************
3084 * GetExitCodeProcess [KERNEL32.@]
3086 * Gets termination status of specified process.
3088 * PARAMS
3089 * hProcess [in] Handle to the process.
3090 * lpExitCode [out] Address to receive termination status.
3092 * RETURNS
3093 * Success: TRUE
3094 * Failure: FALSE
3096 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
3098 NTSTATUS status;
3099 PROCESS_BASIC_INFORMATION pbi;
3101 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3102 sizeof(pbi), NULL);
3103 if (status == STATUS_SUCCESS)
3105 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
3106 return TRUE;
3108 SetLastError( RtlNtStatusToDosError(status) );
3109 return FALSE;
3113 /***********************************************************************
3114 * SetErrorMode (KERNEL32.@)
3116 UINT WINAPI SetErrorMode( UINT mode )
3118 UINT old;
3120 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
3121 &old, sizeof(old), NULL );
3122 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
3123 &mode, sizeof(mode) );
3124 return old;
3127 /***********************************************************************
3128 * GetErrorMode (KERNEL32.@)
3130 UINT WINAPI GetErrorMode( void )
3132 UINT mode;
3134 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode,
3135 &mode, sizeof(mode), NULL );
3136 return mode;
3139 /**********************************************************************
3140 * TlsAlloc [KERNEL32.@]
3142 * Allocates a thread local storage index.
3144 * RETURNS
3145 * Success: TLS index.
3146 * Failure: 0xFFFFFFFF
3148 DWORD WINAPI TlsAlloc( void )
3150 DWORD index;
3151 PEB * const peb = NtCurrentTeb()->Peb;
3153 RtlAcquirePebLock();
3154 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 1 );
3155 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
3156 else
3158 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
3159 if (index != ~0U)
3161 if (!NtCurrentTeb()->TlsExpansionSlots &&
3162 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
3163 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
3165 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
3166 index = ~0U;
3167 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3169 else
3171 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
3172 index += TLS_MINIMUM_AVAILABLE;
3175 else SetLastError( ERROR_NO_MORE_ITEMS );
3177 RtlReleasePebLock();
3178 return index;
3182 /**********************************************************************
3183 * TlsFree [KERNEL32.@]
3185 * Releases a thread local storage index, making it available for reuse.
3187 * PARAMS
3188 * index [in] TLS index to free.
3190 * RETURNS
3191 * Success: TRUE
3192 * Failure: FALSE
3194 BOOL WINAPI TlsFree( DWORD index )
3196 BOOL ret;
3198 RtlAcquirePebLock();
3199 if (index >= TLS_MINIMUM_AVAILABLE)
3201 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
3202 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
3204 else
3206 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
3207 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
3209 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
3210 else SetLastError( ERROR_INVALID_PARAMETER );
3211 RtlReleasePebLock();
3212 return ret;
3216 /**********************************************************************
3217 * TlsGetValue [KERNEL32.@]
3219 * Gets value in a thread's TLS slot.
3221 * PARAMS
3222 * index [in] TLS index to retrieve value for.
3224 * RETURNS
3225 * Success: Value stored in calling thread's TLS slot for index.
3226 * Failure: 0 and GetLastError() returns NO_ERROR.
3228 LPVOID WINAPI TlsGetValue( DWORD index )
3230 LPVOID ret;
3232 if (index < TLS_MINIMUM_AVAILABLE)
3234 ret = NtCurrentTeb()->TlsSlots[index];
3236 else
3238 index -= TLS_MINIMUM_AVAILABLE;
3239 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
3241 SetLastError( ERROR_INVALID_PARAMETER );
3242 return NULL;
3244 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
3245 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
3247 SetLastError( ERROR_SUCCESS );
3248 return ret;
3252 /**********************************************************************
3253 * TlsSetValue [KERNEL32.@]
3255 * Stores a value in the thread's TLS slot.
3257 * PARAMS
3258 * index [in] TLS index to set value for.
3259 * value [in] Value to be stored.
3261 * RETURNS
3262 * Success: TRUE
3263 * Failure: FALSE
3265 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
3267 if (index < TLS_MINIMUM_AVAILABLE)
3269 NtCurrentTeb()->TlsSlots[index] = value;
3271 else
3273 index -= TLS_MINIMUM_AVAILABLE;
3274 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
3276 SetLastError( ERROR_INVALID_PARAMETER );
3277 return FALSE;
3279 if (!NtCurrentTeb()->TlsExpansionSlots &&
3280 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
3281 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
3283 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3284 return FALSE;
3286 NtCurrentTeb()->TlsExpansionSlots[index] = value;
3288 return TRUE;
3292 /***********************************************************************
3293 * GetProcessFlags (KERNEL32.@)
3295 DWORD WINAPI GetProcessFlags( DWORD processid )
3297 IMAGE_NT_HEADERS *nt;
3298 DWORD flags = 0;
3300 if (processid && processid != GetCurrentProcessId()) return 0;
3302 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3304 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
3305 flags |= PDB32_CONSOLE_PROC;
3307 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
3308 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
3309 return flags;
3313 /*********************************************************************
3314 * OpenProcess (KERNEL32.@)
3316 * Opens a handle to a process.
3318 * PARAMS
3319 * access [I] Desired access rights assigned to the returned handle.
3320 * inherit [I] Determines whether or not child processes will inherit the handle.
3321 * id [I] Process identifier of the process to get a handle to.
3323 * RETURNS
3324 * Success: Valid handle to the specified process.
3325 * Failure: NULL, check GetLastError().
3327 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
3329 NTSTATUS status;
3330 HANDLE handle;
3331 OBJECT_ATTRIBUTES attr;
3332 CLIENT_ID cid;
3334 cid.UniqueProcess = ULongToHandle(id);
3335 cid.UniqueThread = 0; /* FIXME ? */
3337 attr.Length = sizeof(OBJECT_ATTRIBUTES);
3338 attr.RootDirectory = NULL;
3339 attr.Attributes = inherit ? OBJ_INHERIT : 0;
3340 attr.SecurityDescriptor = NULL;
3341 attr.SecurityQualityOfService = NULL;
3342 attr.ObjectName = NULL;
3344 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
3346 status = NtOpenProcess(&handle, access, &attr, &cid);
3347 if (status != STATUS_SUCCESS)
3349 SetLastError( RtlNtStatusToDosError(status) );
3350 return NULL;
3352 return handle;
3356 /*********************************************************************
3357 * GetProcessId (KERNEL32.@)
3359 * Gets the a unique identifier of a process.
3361 * PARAMS
3362 * hProcess [I] Handle to the process.
3364 * RETURNS
3365 * Success: TRUE.
3366 * Failure: FALSE, check GetLastError().
3368 * NOTES
3370 * The identifier is unique only on the machine and only until the process
3371 * exits (including system shutdown).
3373 DWORD WINAPI GetProcessId( HANDLE hProcess )
3375 NTSTATUS status;
3376 PROCESS_BASIC_INFORMATION pbi;
3378 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3379 sizeof(pbi), NULL);
3380 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
3381 SetLastError( RtlNtStatusToDosError(status) );
3382 return 0;
3386 /*********************************************************************
3387 * CloseHandle (KERNEL32.@)
3389 * Closes a handle.
3391 * PARAMS
3392 * handle [I] Handle to close.
3394 * RETURNS
3395 * Success: TRUE.
3396 * Failure: FALSE, check GetLastError().
3398 BOOL WINAPI CloseHandle( HANDLE handle )
3400 NTSTATUS status;
3402 /* stdio handles need special treatment */
3403 if (handle == (HANDLE)STD_INPUT_HANDLE)
3404 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdInput, 0 );
3405 else if (handle == (HANDLE)STD_OUTPUT_HANDLE)
3406 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdOutput, 0 );
3407 else if (handle == (HANDLE)STD_ERROR_HANDLE)
3408 handle = InterlockedExchangePointer( &NtCurrentTeb()->Peb->ProcessParameters->hStdError, 0 );
3410 if (is_console_handle(handle))
3411 return CloseConsoleHandle(handle);
3413 status = NtClose( handle );
3414 if (status) SetLastError( RtlNtStatusToDosError(status) );
3415 return !status;
3419 /*********************************************************************
3420 * GetHandleInformation (KERNEL32.@)
3422 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
3424 OBJECT_DATA_INFORMATION info;
3425 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
3427 if (status) SetLastError( RtlNtStatusToDosError(status) );
3428 else if (flags)
3430 *flags = 0;
3431 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
3432 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
3434 return !status;
3438 /*********************************************************************
3439 * SetHandleInformation (KERNEL32.@)
3441 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
3443 OBJECT_DATA_INFORMATION info;
3444 NTSTATUS status;
3446 /* if not setting both fields, retrieve current value first */
3447 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
3448 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
3450 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
3452 SetLastError( RtlNtStatusToDosError(status) );
3453 return FALSE;
3456 if (mask & HANDLE_FLAG_INHERIT)
3457 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
3458 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
3459 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
3461 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
3462 if (status) SetLastError( RtlNtStatusToDosError(status) );
3463 return !status;
3467 /*********************************************************************
3468 * DuplicateHandle (KERNEL32.@)
3470 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
3471 HANDLE dest_process, HANDLE *dest,
3472 DWORD access, BOOL inherit, DWORD options )
3474 NTSTATUS status;
3476 if (is_console_handle(source))
3478 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3479 if (source_process != dest_process ||
3480 source_process != GetCurrentProcess())
3482 SetLastError(ERROR_INVALID_PARAMETER);
3483 return FALSE;
3485 *dest = DuplicateConsoleHandle( source, access, inherit, options );
3486 return (*dest != INVALID_HANDLE_VALUE);
3488 status = NtDuplicateObject( source_process, source, dest_process, dest,
3489 access, inherit ? OBJ_INHERIT : 0, options );
3490 if (status) SetLastError( RtlNtStatusToDosError(status) );
3491 return !status;
3495 /***********************************************************************
3496 * ConvertToGlobalHandle (KERNEL32.@)
3498 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
3500 HANDLE ret = INVALID_HANDLE_VALUE;
3501 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
3502 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
3503 return ret;
3507 /***********************************************************************
3508 * SetHandleContext (KERNEL32.@)
3510 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
3512 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3513 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
3514 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3515 return FALSE;
3519 /***********************************************************************
3520 * GetHandleContext (KERNEL32.@)
3522 DWORD WINAPI GetHandleContext(HANDLE hnd)
3524 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3525 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
3526 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3527 return 0;
3531 /***********************************************************************
3532 * CreateSocketHandle (KERNEL32.@)
3534 HANDLE WINAPI CreateSocketHandle(void)
3536 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3537 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3538 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3539 return INVALID_HANDLE_VALUE;
3543 /***********************************************************************
3544 * SetPriorityClass (KERNEL32.@)
3546 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
3548 NTSTATUS status;
3549 PROCESS_PRIORITY_CLASS ppc;
3551 ppc.Foreground = FALSE;
3552 switch (priorityclass)
3554 case IDLE_PRIORITY_CLASS:
3555 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
3556 case BELOW_NORMAL_PRIORITY_CLASS:
3557 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
3558 case NORMAL_PRIORITY_CLASS:
3559 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
3560 case ABOVE_NORMAL_PRIORITY_CLASS:
3561 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
3562 case HIGH_PRIORITY_CLASS:
3563 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
3564 case REALTIME_PRIORITY_CLASS:
3565 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
3566 default:
3567 SetLastError(ERROR_INVALID_PARAMETER);
3568 return FALSE;
3571 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
3572 &ppc, sizeof(ppc));
3574 if (status != STATUS_SUCCESS)
3576 SetLastError( RtlNtStatusToDosError(status) );
3577 return FALSE;
3579 return TRUE;
3583 /***********************************************************************
3584 * GetPriorityClass (KERNEL32.@)
3586 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
3588 NTSTATUS status;
3589 PROCESS_BASIC_INFORMATION pbi;
3591 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
3592 sizeof(pbi), NULL);
3593 if (status != STATUS_SUCCESS)
3595 SetLastError( RtlNtStatusToDosError(status) );
3596 return 0;
3598 switch (pbi.BasePriority)
3600 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
3601 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
3602 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
3603 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
3604 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
3605 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
3607 SetLastError( ERROR_INVALID_PARAMETER );
3608 return 0;
3612 /***********************************************************************
3613 * SetProcessAffinityMask (KERNEL32.@)
3615 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
3617 NTSTATUS status;
3619 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
3620 &affmask, sizeof(DWORD_PTR));
3621 if (status)
3623 SetLastError( RtlNtStatusToDosError(status) );
3624 return FALSE;
3626 return TRUE;
3630 /**********************************************************************
3631 * GetProcessAffinityMask (KERNEL32.@)
3633 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess, PDWORD_PTR process_mask, PDWORD_PTR system_mask )
3635 NTSTATUS status = STATUS_SUCCESS;
3637 if (process_mask)
3639 if ((status = NtQueryInformationProcess( hProcess, ProcessAffinityMask,
3640 process_mask, sizeof(*process_mask), NULL )))
3641 SetLastError( RtlNtStatusToDosError(status) );
3643 if (system_mask && status == STATUS_SUCCESS)
3645 SYSTEM_BASIC_INFORMATION info;
3647 if ((status = NtQuerySystemInformation( SystemBasicInformation, &info, sizeof(info), NULL )))
3648 SetLastError( RtlNtStatusToDosError(status) );
3649 else
3650 *system_mask = info.ActiveProcessorsAffinityMask;
3652 return !status;
3656 /***********************************************************************
3657 * SetProcessAffinityUpdateMode (KERNEL32.@)
3659 BOOL WINAPI SetProcessAffinityUpdateMode( HANDLE process, DWORD flags )
3661 FIXME("(%p,0x%08x): stub\n", process, flags);
3662 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3663 return FALSE;
3667 /***********************************************************************
3668 * GetProcessVersion (KERNEL32.@)
3670 DWORD WINAPI GetProcessVersion( DWORD pid )
3672 HANDLE process;
3673 NTSTATUS status;
3674 PROCESS_BASIC_INFORMATION pbi;
3675 SIZE_T count;
3676 PEB peb;
3677 IMAGE_DOS_HEADER dos;
3678 IMAGE_NT_HEADERS nt;
3679 DWORD ver = 0;
3681 if (!pid || pid == GetCurrentProcessId())
3683 IMAGE_NT_HEADERS *pnt;
3685 if ((pnt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3686 return ((pnt->OptionalHeader.MajorSubsystemVersion << 16) |
3687 pnt->OptionalHeader.MinorSubsystemVersion);
3688 return 0;
3691 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3692 if (!process) return 0;
3694 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3695 if (status) goto err;
3697 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3698 if (status || count != sizeof(peb)) goto err;
3700 memset(&dos, 0, sizeof(dos));
3701 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3702 if (status || count != sizeof(dos)) goto err;
3703 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3705 memset(&nt, 0, sizeof(nt));
3706 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3707 if (status || count != sizeof(nt)) goto err;
3708 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3710 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3712 err:
3713 CloseHandle(process);
3715 if (status != STATUS_SUCCESS)
3716 SetLastError(RtlNtStatusToDosError(status));
3718 return ver;
3722 /***********************************************************************
3723 * SetProcessWorkingSetSizeEx [KERNEL32.@]
3724 * Sets the min/max working set sizes for a specified process.
3726 * PARAMS
3727 * process [I] Handle to the process of interest
3728 * minset [I] Specifies minimum working set size
3729 * maxset [I] Specifies maximum working set size
3730 * flags [I] Flags to enforce working set sizes
3732 * RETURNS
3733 * Success: TRUE
3734 * Failure: FALSE
3736 BOOL WINAPI SetProcessWorkingSetSizeEx(HANDLE process, SIZE_T minset, SIZE_T maxset, DWORD flags)
3738 WARN("(%p,%ld,%ld,%x): stub - harmless\n", process, minset, maxset, flags);
3739 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3740 /* Trim the working set to zero */
3741 /* Swap the process out of physical RAM */
3743 return TRUE;
3746 /***********************************************************************
3747 * SetProcessWorkingSetSize [KERNEL32.@]
3748 * Sets the min/max working set sizes for a specified process.
3750 * PARAMS
3751 * process [I] Handle to the process of interest
3752 * minset [I] Specifies minimum working set size
3753 * maxset [I] Specifies maximum working set size
3755 * RETURNS
3756 * Success: TRUE
3757 * Failure: FALSE
3759 BOOL WINAPI SetProcessWorkingSetSize(HANDLE process, SIZE_T minset, SIZE_T maxset)
3761 return SetProcessWorkingSetSizeEx(process, minset, maxset, 0);
3764 /***********************************************************************
3765 * K32EmptyWorkingSet (KERNEL32.@)
3767 BOOL WINAPI K32EmptyWorkingSet(HANDLE hProcess)
3769 return SetProcessWorkingSetSize(hProcess, (SIZE_T)-1, (SIZE_T)-1);
3773 /***********************************************************************
3774 * GetProcessWorkingSetSizeEx (KERNEL32.@)
3776 BOOL WINAPI GetProcessWorkingSetSizeEx(HANDLE process, SIZE_T *minset,
3777 SIZE_T *maxset, DWORD *flags)
3779 FIXME("(%p,%p,%p,%p): stub\n", process, minset, maxset, flags);
3780 /* 32 MB working set size */
3781 if (minset) *minset = 32*1024*1024;
3782 if (maxset) *maxset = 32*1024*1024;
3783 if (flags) *flags = QUOTA_LIMITS_HARDWS_MIN_DISABLE |
3784 QUOTA_LIMITS_HARDWS_MAX_DISABLE;
3785 return TRUE;
3789 /***********************************************************************
3790 * GetProcessWorkingSetSize (KERNEL32.@)
3792 BOOL WINAPI GetProcessWorkingSetSize(HANDLE process, SIZE_T *minset, SIZE_T *maxset)
3794 return GetProcessWorkingSetSizeEx(process, minset, maxset, NULL);
3798 /***********************************************************************
3799 * SetProcessShutdownParameters (KERNEL32.@)
3801 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3803 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3804 shutdown_flags = flags;
3805 shutdown_priority = level;
3806 return TRUE;
3810 /***********************************************************************
3811 * GetProcessShutdownParameters (KERNEL32.@)
3814 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3816 *lpdwLevel = shutdown_priority;
3817 *lpdwFlags = shutdown_flags;
3818 return TRUE;
3822 /***********************************************************************
3823 * GetProcessPriorityBoost (KERNEL32.@)
3825 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3827 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3829 /* Report that no boost is present.. */
3830 *pDisablePriorityBoost = FALSE;
3832 return TRUE;
3835 /***********************************************************************
3836 * SetProcessPriorityBoost (KERNEL32.@)
3838 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3840 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3841 /* Say we can do it. I doubt the program will notice that we don't. */
3842 return TRUE;
3846 /***********************************************************************
3847 * ReadProcessMemory (KERNEL32.@)
3849 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3850 SIZE_T *bytes_read )
3852 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3853 if (status) SetLastError( RtlNtStatusToDosError(status) );
3854 return !status;
3858 /***********************************************************************
3859 * WriteProcessMemory (KERNEL32.@)
3861 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3862 SIZE_T *bytes_written )
3864 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3865 if (status) SetLastError( RtlNtStatusToDosError(status) );
3866 return !status;
3870 /****************************************************************************
3871 * FlushInstructionCache (KERNEL32.@)
3873 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3875 NTSTATUS status;
3876 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3877 if (status) SetLastError( RtlNtStatusToDosError(status) );
3878 return !status;
3882 /******************************************************************
3883 * GetProcessIoCounters (KERNEL32.@)
3885 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3887 NTSTATUS status;
3889 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3890 ioc, sizeof(*ioc), NULL);
3891 if (status) SetLastError( RtlNtStatusToDosError(status) );
3892 return !status;
3895 /******************************************************************
3896 * GetProcessHandleCount (KERNEL32.@)
3898 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3900 NTSTATUS status;
3902 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3903 cnt, sizeof(*cnt), NULL);
3904 if (status) SetLastError( RtlNtStatusToDosError(status) );
3905 return !status;
3908 /******************************************************************
3909 * QueryFullProcessImageNameA (KERNEL32.@)
3911 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3913 BOOL retval;
3914 DWORD pdwSizeW = *pdwSize;
3915 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3917 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3919 if(retval)
3920 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3921 lpExeName, *pdwSize, NULL, NULL));
3922 if(retval)
3923 *pdwSize = strlen(lpExeName);
3925 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3926 return retval;
3929 /******************************************************************
3930 * QueryFullProcessImageNameW (KERNEL32.@)
3932 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3934 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3935 UNICODE_STRING *dynamic_buffer = NULL;
3936 UNICODE_STRING *result = NULL;
3937 NTSTATUS status;
3938 DWORD needed;
3940 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3941 * is a DOS path and we depend on this. */
3942 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3943 sizeof(buffer) - sizeof(WCHAR), &needed);
3944 if (status == STATUS_INFO_LENGTH_MISMATCH)
3946 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3947 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3948 result = dynamic_buffer;
3950 else
3951 result = (PUNICODE_STRING)buffer;
3953 if (status) goto cleanup;
3955 if (dwFlags & PROCESS_NAME_NATIVE)
3957 WCHAR drive[3];
3958 WCHAR device[1024];
3959 DWORD ntlen, devlen;
3961 if (result->Buffer[1] != ':' || result->Buffer[0] < 'A' || result->Buffer[0] > 'Z')
3963 /* We cannot convert it to an NT device path so fail */
3964 status = STATUS_NO_SUCH_DEVICE;
3965 goto cleanup;
3968 /* Find this drive's NT device path */
3969 drive[0] = result->Buffer[0];
3970 drive[1] = ':';
3971 drive[2] = 0;
3972 if (!QueryDosDeviceW(drive, device, ARRAY_SIZE(device)))
3974 status = STATUS_NO_SUCH_DEVICE;
3975 goto cleanup;
3978 devlen = lstrlenW(device);
3979 ntlen = devlen + (result->Length/sizeof(WCHAR) - 2);
3980 if (ntlen + 1 > *pdwSize)
3982 status = STATUS_BUFFER_TOO_SMALL;
3983 goto cleanup;
3985 *pdwSize = ntlen;
3987 memcpy(lpExeName, device, devlen * sizeof(*device));
3988 memcpy(lpExeName + devlen, result->Buffer + 2, result->Length - 2 * sizeof(WCHAR));
3989 lpExeName[*pdwSize] = 0;
3990 TRACE("NT path: %s\n", debugstr_w(lpExeName));
3992 else
3994 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3996 status = STATUS_BUFFER_TOO_SMALL;
3997 goto cleanup;
4000 *pdwSize = result->Length/sizeof(WCHAR);
4001 memcpy( lpExeName, result->Buffer, result->Length );
4002 lpExeName[*pdwSize] = 0;
4005 cleanup:
4006 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
4007 if (status) SetLastError( RtlNtStatusToDosError(status) );
4008 return !status;
4011 /***********************************************************************
4012 * K32GetProcessImageFileNameA (KERNEL32.@)
4014 DWORD WINAPI K32GetProcessImageFileNameA( HANDLE process, LPSTR file, DWORD size )
4016 return QueryFullProcessImageNameA(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
4019 /***********************************************************************
4020 * K32GetProcessImageFileNameW (KERNEL32.@)
4022 DWORD WINAPI K32GetProcessImageFileNameW( HANDLE process, LPWSTR file, DWORD size )
4024 return QueryFullProcessImageNameW(process, PROCESS_NAME_NATIVE, file, &size) ? size : 0;
4027 /***********************************************************************
4028 * K32EnumProcesses (KERNEL32.@)
4030 BOOL WINAPI K32EnumProcesses(DWORD *lpdwProcessIDs, DWORD cb, DWORD *lpcbUsed)
4032 SYSTEM_PROCESS_INFORMATION *spi;
4033 ULONG size = 0x4000;
4034 void *buf = NULL;
4035 NTSTATUS status;
4037 do {
4038 size *= 2;
4039 HeapFree(GetProcessHeap(), 0, buf);
4040 buf = HeapAlloc(GetProcessHeap(), 0, size);
4041 if (!buf)
4042 return FALSE;
4044 status = NtQuerySystemInformation(SystemProcessInformation, buf, size, NULL);
4045 } while(status == STATUS_INFO_LENGTH_MISMATCH);
4047 if (status != STATUS_SUCCESS)
4049 HeapFree(GetProcessHeap(), 0, buf);
4050 SetLastError(RtlNtStatusToDosError(status));
4051 return FALSE;
4054 spi = buf;
4056 for (*lpcbUsed = 0; cb >= sizeof(DWORD); cb -= sizeof(DWORD))
4058 *lpdwProcessIDs++ = HandleToUlong(spi->UniqueProcessId);
4059 *lpcbUsed += sizeof(DWORD);
4061 if (spi->NextEntryOffset == 0)
4062 break;
4064 spi = (SYSTEM_PROCESS_INFORMATION *)(((PCHAR)spi) + spi->NextEntryOffset);
4067 HeapFree(GetProcessHeap(), 0, buf);
4068 return TRUE;
4071 /***********************************************************************
4072 * K32QueryWorkingSet (KERNEL32.@)
4074 BOOL WINAPI K32QueryWorkingSet( HANDLE process, LPVOID buffer, DWORD size )
4076 NTSTATUS status;
4078 TRACE( "(%p, %p, %d)\n", process, buffer, size );
4080 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
4082 if (status)
4084 SetLastError( RtlNtStatusToDosError( status ) );
4085 return FALSE;
4087 return TRUE;
4090 /***********************************************************************
4091 * K32QueryWorkingSetEx (KERNEL32.@)
4093 BOOL WINAPI K32QueryWorkingSetEx( HANDLE process, LPVOID buffer, DWORD size )
4095 NTSTATUS status;
4097 TRACE( "(%p, %p, %d)\n", process, buffer, size );
4099 status = NtQueryVirtualMemory( process, NULL, MemoryWorkingSetList, buffer, size, NULL );
4101 if (status)
4103 SetLastError( RtlNtStatusToDosError( status ) );
4104 return FALSE;
4106 return TRUE;
4109 /***********************************************************************
4110 * K32GetProcessMemoryInfo (KERNEL32.@)
4112 * Retrieve memory usage information for a given process
4115 BOOL WINAPI K32GetProcessMemoryInfo(HANDLE process,
4116 PPROCESS_MEMORY_COUNTERS pmc, DWORD cb)
4118 NTSTATUS status;
4119 VM_COUNTERS vmc;
4121 if (cb < sizeof(PROCESS_MEMORY_COUNTERS))
4123 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4124 return FALSE;
4127 status = NtQueryInformationProcess(process, ProcessVmCounters,
4128 &vmc, sizeof(vmc), NULL);
4130 if (status)
4132 SetLastError(RtlNtStatusToDosError(status));
4133 return FALSE;
4136 pmc->cb = sizeof(PROCESS_MEMORY_COUNTERS);
4137 pmc->PageFaultCount = vmc.PageFaultCount;
4138 pmc->PeakWorkingSetSize = vmc.PeakWorkingSetSize;
4139 pmc->WorkingSetSize = vmc.WorkingSetSize;
4140 pmc->QuotaPeakPagedPoolUsage = vmc.QuotaPeakPagedPoolUsage;
4141 pmc->QuotaPagedPoolUsage = vmc.QuotaPagedPoolUsage;
4142 pmc->QuotaPeakNonPagedPoolUsage = vmc.QuotaPeakNonPagedPoolUsage;
4143 pmc->QuotaNonPagedPoolUsage = vmc.QuotaNonPagedPoolUsage;
4144 pmc->PagefileUsage = vmc.PagefileUsage;
4145 pmc->PeakPagefileUsage = vmc.PeakPagefileUsage;
4147 return TRUE;
4150 /***********************************************************************
4151 * ProcessIdToSessionId (KERNEL32.@)
4152 * This function is available on Terminal Server 4SP4 and Windows 2000
4154 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
4156 if (procid != GetCurrentProcessId())
4157 FIXME("Unsupported for other processes.\n");
4159 *sessionid_ptr = NtCurrentTeb()->Peb->SessionId;
4160 return TRUE;
4164 /***********************************************************************
4165 * RegisterServiceProcess (KERNEL32.@)
4167 * A service process calls this function to ensure that it continues to run
4168 * even after a user logged off.
4170 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
4172 /* I don't think that Wine needs to do anything in this function */
4173 return 1; /* success */
4177 /**********************************************************************
4178 * IsWow64Process (KERNEL32.@)
4180 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
4182 ULONG_PTR pbi;
4183 NTSTATUS status;
4185 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
4187 if (status != STATUS_SUCCESS)
4189 SetLastError( RtlNtStatusToDosError( status ) );
4190 return FALSE;
4192 *Wow64Process = (pbi != 0);
4193 return TRUE;
4197 /***********************************************************************
4198 * GetCurrentProcess (KERNEL32.@)
4200 * Get a handle to the current process.
4202 * PARAMS
4203 * None.
4205 * RETURNS
4206 * A handle representing the current process.
4208 #undef GetCurrentProcess
4209 HANDLE WINAPI GetCurrentProcess(void)
4211 return (HANDLE)~(ULONG_PTR)0;
4214 /***********************************************************************
4215 * GetLogicalProcessorInformation (KERNEL32.@)
4217 BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer, PDWORD pBufLen)
4219 NTSTATUS status;
4221 TRACE("(%p,%p)\n", buffer, pBufLen);
4223 if(!pBufLen)
4225 SetLastError(ERROR_INVALID_PARAMETER);
4226 return FALSE;
4229 status = NtQuerySystemInformation( SystemLogicalProcessorInformation, buffer, *pBufLen, pBufLen);
4231 if (status == STATUS_INFO_LENGTH_MISMATCH)
4233 SetLastError( ERROR_INSUFFICIENT_BUFFER );
4234 return FALSE;
4236 if (status != STATUS_SUCCESS)
4238 SetLastError( RtlNtStatusToDosError( status ) );
4239 return FALSE;
4241 return TRUE;
4244 /***********************************************************************
4245 * GetLogicalProcessorInformationEx (KERNEL32.@)
4247 BOOL WINAPI GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, DWORD *len)
4249 NTSTATUS status;
4251 TRACE("(%u,%p,%p)\n", relationship, buffer, len);
4253 if (!len)
4255 SetLastError( ERROR_INVALID_PARAMETER );
4256 return FALSE;
4259 status = NtQuerySystemInformationEx( SystemLogicalProcessorInformationEx, &relationship, sizeof(relationship),
4260 buffer, *len, len );
4261 if (status == STATUS_INFO_LENGTH_MISMATCH)
4263 SetLastError( ERROR_INSUFFICIENT_BUFFER );
4264 return FALSE;
4266 if (status != STATUS_SUCCESS)
4268 SetLastError( RtlNtStatusToDosError( status ) );
4269 return FALSE;
4271 return TRUE;
4274 /***********************************************************************
4275 * CmdBatNotification (KERNEL32.@)
4277 * Notifies the system that a batch file has started or finished.
4279 * PARAMS
4280 * bBatchRunning [I] TRUE if a batch file has started or
4281 * FALSE if a batch file has finished executing.
4283 * RETURNS
4284 * Unknown.
4286 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
4288 FIXME("%d\n", bBatchRunning);
4289 return FALSE;
4292 /***********************************************************************
4293 * RegisterApplicationRestart (KERNEL32.@)
4295 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
4297 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
4299 return S_OK;
4302 /**********************************************************************
4303 * WTSGetActiveConsoleSessionId (KERNEL32.@)
4305 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
4307 static int once;
4308 if (!once++) FIXME("stub\n");
4309 /* Return current session id. */
4310 return NtCurrentTeb()->Peb->SessionId;
4313 /**********************************************************************
4314 * GetSystemDEPPolicy (KERNEL32.@)
4316 DEP_SYSTEM_POLICY_TYPE WINAPI GetSystemDEPPolicy(void)
4318 FIXME("stub\n");
4319 return OptIn;
4322 /**********************************************************************
4323 * SetProcessDEPPolicy (KERNEL32.@)
4325 BOOL WINAPI SetProcessDEPPolicy(DWORD newDEP)
4327 FIXME("(%d): stub\n", newDEP);
4328 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4329 return FALSE;
4332 /**********************************************************************
4333 * ApplicationRecoveryFinished (KERNEL32.@)
4335 VOID WINAPI ApplicationRecoveryFinished(BOOL success)
4337 FIXME(": stub\n");
4338 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4341 /**********************************************************************
4342 * ApplicationRecoveryInProgress (KERNEL32.@)
4344 HRESULT WINAPI ApplicationRecoveryInProgress(PBOOL canceled)
4346 FIXME(":%p stub\n", canceled);
4347 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4348 return E_FAIL;
4351 /**********************************************************************
4352 * RegisterApplicationRecoveryCallback (KERNEL32.@)
4354 HRESULT WINAPI RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback, PVOID param, DWORD pingint, DWORD flags)
4356 FIXME("%p, %p, %d, %d: stub\n", callback, param, pingint, flags);
4357 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4358 return E_FAIL;
4361 /***********************************************************************
4362 * GetApplicationRestartSettings (KERNEL32.@)
4364 HRESULT WINAPI GetApplicationRestartSettings(HANDLE process, WCHAR *cmdline, DWORD *size, DWORD *flags)
4366 FIXME("%p, %p, %p, %p)\n", process, cmdline, size, flags);
4367 return E_NOTIMPL;
4370 /**********************************************************************
4371 * GetNumaHighestNodeNumber (KERNEL32.@)
4373 BOOL WINAPI GetNumaHighestNodeNumber(PULONG highestnode)
4375 *highestnode = 0;
4376 FIXME("(%p): semi-stub\n", highestnode);
4377 return TRUE;
4380 /**********************************************************************
4381 * GetNumaNodeProcessorMask (KERNEL32.@)
4383 BOOL WINAPI GetNumaNodeProcessorMask(UCHAR node, PULONGLONG mask)
4385 FIXME("(%c %p): stub\n", node, mask);
4386 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4387 return FALSE;
4390 /**********************************************************************
4391 * GetNumaNodeProcessorMaskEx (KERNEL32.@)
4393 BOOL WINAPI GetNumaNodeProcessorMaskEx(USHORT node, PGROUP_AFFINITY mask)
4395 FIXME("(%hu %p): stub\n", node, mask);
4396 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4397 return FALSE;
4400 /**********************************************************************
4401 * GetNumaAvailableMemoryNode (KERNEL32.@)
4403 BOOL WINAPI GetNumaAvailableMemoryNode(UCHAR node, PULONGLONG available_bytes)
4405 FIXME("(%c %p): stub\n", node, available_bytes);
4406 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4407 return FALSE;
4410 /***********************************************************************
4411 * GetNumaProcessorNode (KERNEL32.@)
4413 BOOL WINAPI GetNumaProcessorNode(UCHAR processor, PUCHAR node)
4415 SYSTEM_INFO si;
4417 TRACE("(%d, %p)\n", processor, node);
4419 GetSystemInfo( &si );
4420 if (processor < si.dwNumberOfProcessors)
4422 *node = 0;
4423 return TRUE;
4426 *node = 0xFF;
4427 SetLastError(ERROR_INVALID_PARAMETER);
4428 return FALSE;
4431 /**********************************************************************
4432 * GetProcessDEPPolicy (KERNEL32.@)
4434 BOOL WINAPI GetProcessDEPPolicy(HANDLE process, LPDWORD flags, PBOOL permanent)
4436 NTSTATUS status;
4437 ULONG dep_flags;
4439 TRACE("(%p %p %p)\n", process, flags, permanent);
4441 status = NtQueryInformationProcess( GetCurrentProcess(), ProcessExecuteFlags,
4442 &dep_flags, sizeof(dep_flags), NULL );
4443 if (!status)
4446 if (flags)
4448 *flags = 0;
4449 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE)
4450 *flags |= PROCESS_DEP_ENABLE;
4451 if (dep_flags & MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION)
4452 *flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
4455 if (permanent)
4456 *permanent = (dep_flags & MEM_EXECUTE_OPTION_PERMANENT) != 0;
4459 if (status) SetLastError( RtlNtStatusToDosError(status) );
4460 return !status;
4463 /**********************************************************************
4464 * FlushProcessWriteBuffers (KERNEL32.@)
4466 VOID WINAPI FlushProcessWriteBuffers(void)
4468 static int once = 0;
4470 if (!once++)
4471 FIXME(": stub\n");
4474 /***********************************************************************
4475 * UnregisterApplicationRestart (KERNEL32.@)
4477 HRESULT WINAPI UnregisterApplicationRestart(void)
4479 FIXME(": stub\n");
4480 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4481 return S_OK;
4484 struct proc_thread_attr
4486 DWORD_PTR attr;
4487 SIZE_T size;
4488 void *value;
4491 struct _PROC_THREAD_ATTRIBUTE_LIST
4493 DWORD mask; /* bitmask of items in list */
4494 DWORD size; /* max number of items in list */
4495 DWORD count; /* number of items in list */
4496 DWORD pad;
4497 DWORD_PTR unk;
4498 struct proc_thread_attr attrs[1];
4501 /***********************************************************************
4502 * InitializeProcThreadAttributeList (KERNEL32.@)
4504 BOOL WINAPI InitializeProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4505 DWORD count, DWORD flags, SIZE_T *size)
4507 SIZE_T needed;
4508 BOOL ret = FALSE;
4510 TRACE("(%p %d %x %p)\n", list, count, flags, size);
4512 needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[count]);
4513 if (list && *size >= needed)
4515 list->mask = 0;
4516 list->size = count;
4517 list->count = 0;
4518 list->unk = 0;
4519 ret = TRUE;
4521 else
4522 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4524 *size = needed;
4525 return ret;
4528 /***********************************************************************
4529 * UpdateProcThreadAttribute (KERNEL32.@)
4531 BOOL WINAPI UpdateProcThreadAttribute(struct _PROC_THREAD_ATTRIBUTE_LIST *list,
4532 DWORD flags, DWORD_PTR attr, void *value, SIZE_T size,
4533 void *prev_ret, SIZE_T *size_ret)
4535 DWORD mask;
4536 struct proc_thread_attr *entry;
4538 TRACE("(%p %x %08lx %p %ld %p %p)\n", list, flags, attr, value, size, prev_ret, size_ret);
4540 if (list->count >= list->size)
4542 SetLastError(ERROR_GEN_FAILURE);
4543 return FALSE;
4546 switch (attr)
4548 case PROC_THREAD_ATTRIBUTE_PARENT_PROCESS:
4549 if (size != sizeof(HANDLE))
4551 SetLastError(ERROR_BAD_LENGTH);
4552 return FALSE;
4554 break;
4556 case PROC_THREAD_ATTRIBUTE_HANDLE_LIST:
4557 if ((size / sizeof(HANDLE)) * sizeof(HANDLE) != size)
4559 SetLastError(ERROR_BAD_LENGTH);
4560 return FALSE;
4562 break;
4564 case PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR:
4565 if (size != sizeof(PROCESSOR_NUMBER))
4567 SetLastError(ERROR_BAD_LENGTH);
4568 return FALSE;
4570 break;
4572 case PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY:
4573 if (size != sizeof(DWORD) && size != sizeof(DWORD64))
4575 SetLastError(ERROR_BAD_LENGTH);
4576 return FALSE;
4578 break;
4580 case PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY:
4581 if (size != sizeof(DWORD) && size != sizeof(DWORD64) && size != sizeof(DWORD64) * 2)
4583 SetLastError(ERROR_BAD_LENGTH);
4584 return FALSE;
4586 break;
4588 default:
4589 SetLastError(ERROR_NOT_SUPPORTED);
4590 FIXME("Unhandled attribute number %lu\n", attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4591 return FALSE;
4594 mask = 1 << (attr & PROC_THREAD_ATTRIBUTE_NUMBER);
4596 if (list->mask & mask)
4598 SetLastError(ERROR_OBJECT_NAME_EXISTS);
4599 return FALSE;
4602 list->mask |= mask;
4604 entry = list->attrs + list->count;
4605 entry->attr = attr;
4606 entry->size = size;
4607 entry->value = value;
4608 list->count++;
4610 return TRUE;
4613 /***********************************************************************
4614 * CreateUmsCompletionList (KERNEL32.@)
4616 BOOL WINAPI CreateUmsCompletionList(PUMS_COMPLETION_LIST *list)
4618 FIXME( "%p: stub\n", list );
4619 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4620 return FALSE;
4623 /***********************************************************************
4624 * CreateUmsThreadContext (KERNEL32.@)
4626 BOOL WINAPI CreateUmsThreadContext(PUMS_CONTEXT *ctx)
4628 FIXME( "%p: stub\n", ctx );
4629 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4630 return FALSE;
4633 /***********************************************************************
4634 * DeleteProcThreadAttributeList (KERNEL32.@)
4636 void WINAPI DeleteProcThreadAttributeList(struct _PROC_THREAD_ATTRIBUTE_LIST *list)
4638 return;
4641 /***********************************************************************
4642 * DeleteUmsCompletionList (KERNEL32.@)
4644 BOOL WINAPI DeleteUmsCompletionList(PUMS_COMPLETION_LIST list)
4646 FIXME( "%p: stub\n", list );
4647 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4648 return FALSE;
4651 /***********************************************************************
4652 * DeleteUmsThreadContext (KERNEL32.@)
4654 BOOL WINAPI DeleteUmsThreadContext(PUMS_CONTEXT ctx)
4656 FIXME( "%p: stub\n", ctx );
4657 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4658 return FALSE;
4661 /***********************************************************************
4662 * DequeueUmsCompletionListItems (KERNEL32.@)
4664 BOOL WINAPI DequeueUmsCompletionListItems(void *list, DWORD timeout, PUMS_CONTEXT *ctx)
4666 FIXME( "%p,%08x,%p: stub\n", list, timeout, ctx );
4667 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4668 return FALSE;
4671 /***********************************************************************
4672 * EnterUmsSchedulingMode (KERNEL32.@)
4674 BOOL WINAPI EnterUmsSchedulingMode(UMS_SCHEDULER_STARTUP_INFO *info)
4676 FIXME( "%p: stub\n", info );
4677 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4678 return FALSE;
4681 /***********************************************************************
4682 * ExecuteUmsThread (KERNEL32.@)
4684 BOOL WINAPI ExecuteUmsThread(PUMS_CONTEXT ctx)
4686 FIXME( "%p: stub\n", ctx );
4687 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4688 return FALSE;
4691 /***********************************************************************
4692 * GetCurrentUmsThread (KERNEL32.@)
4694 PUMS_CONTEXT WINAPI GetCurrentUmsThread(void)
4696 FIXME( "stub\n" );
4697 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4698 return FALSE;
4701 /***********************************************************************
4702 * GetNextUmsListItem (KERNEL32.@)
4704 PUMS_CONTEXT WINAPI GetNextUmsListItem(PUMS_CONTEXT ctx)
4706 FIXME( "%p: stub\n", ctx );
4707 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4708 return NULL;
4711 /***********************************************************************
4712 * GetUmsCompletionListEvent (KERNEL32.@)
4714 BOOL WINAPI GetUmsCompletionListEvent(PUMS_COMPLETION_LIST list, HANDLE *event)
4716 FIXME( "%p,%p: stub\n", list, event );
4717 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4718 return FALSE;
4721 /***********************************************************************
4722 * QueryUmsThreadInformation (KERNEL32.@)
4724 BOOL WINAPI QueryUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4725 void *buf, ULONG length, ULONG *ret_length)
4727 FIXME( "%p,%08x,%p,%08x,%p: stub\n", ctx, class, buf, length, ret_length );
4728 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4729 return FALSE;
4732 /***********************************************************************
4733 * SetUmsThreadInformation (KERNEL32.@)
4735 BOOL WINAPI SetUmsThreadInformation(PUMS_CONTEXT ctx, UMS_THREAD_INFO_CLASS class,
4736 void *buf, ULONG length)
4738 FIXME( "%p,%08x,%p,%08x: stub\n", ctx, class, buf, length );
4739 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4740 return FALSE;
4743 /***********************************************************************
4744 * UmsThreadYield (KERNEL32.@)
4746 BOOL WINAPI UmsThreadYield(void *param)
4748 FIXME( "%p: stub\n", param );
4749 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
4750 return FALSE;
4753 /**********************************************************************
4754 * BaseFlushAppcompatCache (KERNEL32.@)
4756 BOOL WINAPI BaseFlushAppcompatCache(void)
4758 FIXME(": stub\n");
4759 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4760 return FALSE;
4763 /**********************************************************************
4764 * SetProcessMitigationPolicy (KERNEL32.@)
4766 BOOL WINAPI SetProcessMitigationPolicy(PROCESS_MITIGATION_POLICY policy, void *buffer, SIZE_T length)
4768 FIXME("(%d, %p, %lu): stub\n", policy, buffer, length);
4770 return TRUE;
4773 /**********************************************************************
4774 * GetProcessMitigationPolicy (KERNEL32.@)
4776 BOOL WINAPI GetProcessMitigationPolicy(HANDLE hProcess, PROCESS_MITIGATION_POLICY policy, void *buffer, SIZE_T length)
4778 FIXME("(%p, %u, %p, %lu): stub\n", hProcess, policy, buffer, length);
4780 return TRUE;