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