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/library.h"
61 #include "wine/server.h"
62 #include "wine/unicode.h"
63 #include "wine/debug.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(process
);
66 WINE_DECLARE_DEBUG_CHANNEL(file
);
67 WINE_DECLARE_DEBUG_CHANNEL(relay
);
70 extern char **__wine_get_main_environment(void);
72 extern char **__wine_main_environ
;
73 static char **__wine_get_main_environment(void) { return __wine_main_environ
; }
84 static DWORD shutdown_flags
= 0;
85 static DWORD shutdown_priority
= 0x280;
87 static const BOOL is_win64
= (sizeof(void *) > sizeof(int));
89 HMODULE kernel32_handle
= 0;
90 SYSTEM_BASIC_INFORMATION system_info
= { 0 };
92 const WCHAR
*DIR_Windows
= NULL
;
93 const WCHAR
*DIR_System
= NULL
;
94 const WCHAR
*DIR_SysWow64
= NULL
;
97 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
98 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
99 #define PDB32_DOS_PROC 0x0010 /* Dos process */
100 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
101 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
102 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
104 static const WCHAR exeW
[] = {'.','e','x','e',0};
105 static const WCHAR comW
[] = {'.','c','o','m',0};
106 static const WCHAR batW
[] = {'.','b','a','t',0};
107 static const WCHAR cmdW
[] = {'.','c','m','d',0};
108 static const WCHAR pifW
[] = {'.','p','i','f',0};
109 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
111 static void exec_process( LPCWSTR name
);
113 extern void SHELL_LoadRegistry(void);
116 /***********************************************************************
119 static inline BOOL
contains_path( LPCWSTR name
)
121 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
125 /***********************************************************************
128 * Check if an environment variable needs to be handled specially when
129 * passed through the Unix environment (i.e. prefixed with "WINE").
131 static inline BOOL
is_special_env_var( const char *var
)
133 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
134 !strncmp( var
, "PWD=", sizeof("PWD=")-1 ) ||
135 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
136 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
137 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
141 /***********************************************************************
144 static inline unsigned int is_path_prefix( const WCHAR
*prefix
, const WCHAR
*filename
)
146 unsigned int len
= strlenW( prefix
);
148 if (strncmpiW( filename
, prefix
, len
) || filename
[len
] != '\\') return 0;
149 while (filename
[len
] == '\\') len
++;
154 /***************************************************************************
157 * Get the path of a builtin module when the native file does not exist.
159 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
,
160 UINT size
, struct binary_info
*binary_info
)
164 void *redir_disabled
= 0;
165 unsigned int flags
= (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT
: 0);
167 /* builtin names cannot be empty or contain spaces */
168 if (!libname
[0] || strchrW( libname
, ' ' ) || strchrW( libname
, '\t' )) return FALSE
;
170 if (is_wow64
&& Wow64DisableWow64FsRedirection( &redir_disabled
))
171 Wow64RevertWow64FsRedirection( redir_disabled
);
173 if (contains_path( libname
))
175 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
176 filename
, &file_part
) > size
* sizeof(WCHAR
))
177 return FALSE
; /* too long */
179 if ((len
= is_path_prefix( DIR_System
, filename
)))
181 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
183 else if (DIR_SysWow64
&& (len
= is_path_prefix( DIR_SysWow64
, filename
)))
189 if (filename
+ len
!= file_part
) return FALSE
;
193 len
= strlenW( DIR_System
);
194 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
195 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
196 file_part
= filename
+ len
;
197 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
198 strcpyW( file_part
, libname
);
199 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
201 if (ext
&& !strchrW( file_part
, '.' ))
203 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
204 return FALSE
; /* too long */
205 strcatW( file_part
, ext
);
207 binary_info
->type
= BINARY_UNIX_LIB
;
208 binary_info
->flags
= flags
;
209 binary_info
->res_start
= NULL
;
210 binary_info
->res_end
= NULL
;
211 /* assume current arch */
212 #if defined(__i386__) || defined(__x86_64__)
213 binary_info
->arch
= (flags
& BINARY_FLAG_64BIT
) ? IMAGE_FILE_MACHINE_AMD64
: IMAGE_FILE_MACHINE_I386
;
214 #elif defined(__powerpc__)
215 binary_info
->arch
= IMAGE_FILE_MACHINE_POWERPC
;
216 #elif defined(__arm__) && !defined(__ARMEB__)
217 binary_info
->arch
= IMAGE_FILE_MACHINE_ARMNT
;
218 #elif defined(__aarch64__)
219 binary_info
->arch
= IMAGE_FILE_MACHINE_ARM64
;
221 binary_info
->arch
= IMAGE_FILE_MACHINE_UNKNOWN
;
227 /***********************************************************************
230 * Open a specific exe file, taking load order into account.
231 * Returns the file handle or 0 for a builtin exe.
233 static HANDLE
open_exe_file( const WCHAR
*name
, struct binary_info
*binary_info
)
237 TRACE("looking for %s\n", debugstr_w(name
) );
239 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
240 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
242 WCHAR buffer
[MAX_PATH
];
243 /* file doesn't exist, check for builtin */
244 if (contains_path( name
) && get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
), binary_info
))
247 else MODULE_get_binary_info( handle
, binary_info
);
253 /***********************************************************************
256 * Open an exe file, and return the full name and file handle.
257 * Returns FALSE if file could not be found.
259 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
,
260 HANDLE
*handle
, struct binary_info
*binary_info
)
262 TRACE("looking for %s\n", debugstr_w(name
) );
264 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
) &&
265 /* no builtin found, try native without extension in case it is a Unix app */
266 !SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
)) return FALSE
;
268 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
269 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
270 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
272 MODULE_get_binary_info( *handle
, binary_info
);
279 /***********************************************************************
280 * build_initial_environment
282 * Build the Win32 environment from the Unix environment
284 static BOOL
build_initial_environment(void)
290 char **env
= __wine_get_main_environment();
292 /* Compute the total size of the Unix environment */
293 for (e
= env
; *e
; e
++)
295 if (is_special_env_var( *e
)) continue;
296 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
298 size
*= sizeof(WCHAR
);
300 /* Now allocate the environment */
302 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
303 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
306 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
307 endptr
= p
+ size
/ sizeof(WCHAR
);
309 /* And fill it with the Unix environment */
310 for (e
= env
; *e
; e
++)
314 /* skip Unix special variables and use the Wine variants instead */
315 if (!strncmp( str
, "WINE", 4 ))
317 if (is_special_env_var( str
+ 4 )) str
+= 4;
318 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
320 else if (is_special_env_var( str
)) continue; /* skip it */
322 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
330 /***********************************************************************
331 * set_registry_variables
333 * Set environment variables by enumerating the values of a key;
334 * helper for set_registry_environment().
335 * Note that Windows happily truncates the value if it's too big.
337 static void set_registry_variables( HANDLE hkey
, ULONG type
)
339 static const WCHAR pathW
[] = {'P','A','T','H'};
340 static const WCHAR sep
[] = {';',0};
341 UNICODE_STRING env_name
, env_value
;
345 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
348 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
351 tmp
.MaximumLength
= sizeof(tmpbuf
);
353 for (index
= 0; ; index
++)
355 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
356 buffer
, sizeof(buffer
), &size
);
357 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
359 if (info
->Type
!= type
)
361 env_name
.Buffer
= info
->Name
;
362 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
363 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
364 env_value
.Length
= info
->DataLength
;
365 env_value
.MaximumLength
= sizeof(buffer
) - info
->DataOffset
;
366 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
367 env_value
.Length
-= sizeof(WCHAR
); /* don't count terminating null if any */
368 if (!env_value
.Length
) continue;
369 if (info
->Type
== REG_EXPAND_SZ
)
371 status
= RtlExpandEnvironmentStrings_U( NULL
, &env_value
, &tmp
, NULL
);
372 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
) continue;
373 RtlCopyUnicodeString( &env_value
, &tmp
);
376 if (env_name
.Length
== sizeof(pathW
) &&
377 !memicmpW( env_name
.Buffer
, pathW
, sizeof(pathW
)/sizeof(WCHAR
) ) &&
378 !RtlQueryEnvironmentVariable_U( NULL
, &env_name
, &tmp
))
380 RtlAppendUnicodeToString( &tmp
, sep
);
381 if (RtlAppendUnicodeStringToString( &tmp
, &env_value
)) continue;
382 RtlCopyUnicodeString( &env_value
, &tmp
);
384 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
389 /***********************************************************************
390 * set_registry_environment
392 * Set the environment variables specified in the registry.
394 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
395 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
396 * on the order in which the variables are processed. But on Windows it
397 * does not really matter since they only use %SystemDrive% and
398 * %SystemRoot% which are predefined. But Wine defines these in the
399 * registry, so we need two passes.
401 static BOOL
set_registry_environment( BOOL volatile_only
)
403 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
404 'S','y','s','t','e','m','\\',
405 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
406 'C','o','n','t','r','o','l','\\',
407 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
408 'E','n','v','i','r','o','n','m','e','n','t',0};
409 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
410 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};
412 OBJECT_ATTRIBUTES attr
;
413 UNICODE_STRING nameW
;
417 attr
.Length
= sizeof(attr
);
418 attr
.RootDirectory
= 0;
419 attr
.ObjectName
= &nameW
;
421 attr
.SecurityDescriptor
= NULL
;
422 attr
.SecurityQualityOfService
= NULL
;
424 /* first the system environment variables */
425 RtlInitUnicodeString( &nameW
, env_keyW
);
426 if (!volatile_only
&& NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
428 set_registry_variables( hkey
, REG_SZ
);
429 set_registry_variables( hkey
, REG_EXPAND_SZ
);
434 /* then the ones for the current user */
435 if (RtlOpenCurrentUser( KEY_READ
, &attr
.RootDirectory
) != STATUS_SUCCESS
) return ret
;
436 RtlInitUnicodeString( &nameW
, envW
);
437 if (!volatile_only
&& NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
439 set_registry_variables( hkey
, REG_SZ
);
440 set_registry_variables( hkey
, REG_EXPAND_SZ
);
444 RtlInitUnicodeString( &nameW
, volatile_envW
);
445 if (NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
447 set_registry_variables( hkey
, REG_SZ
);
448 set_registry_variables( hkey
, REG_EXPAND_SZ
);
452 NtClose( attr
.RootDirectory
);
457 /***********************************************************************
460 static WCHAR
*get_reg_value( HKEY hkey
, const WCHAR
*name
)
462 char buffer
[1024 * sizeof(WCHAR
) + sizeof(KEY_VALUE_PARTIAL_INFORMATION
)];
463 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
464 DWORD len
, size
= sizeof(buffer
);
466 UNICODE_STRING nameW
;
468 RtlInitUnicodeString( &nameW
, name
);
469 if (NtQueryValueKey( hkey
, &nameW
, KeyValuePartialInformation
, buffer
, size
, &size
))
472 if (size
<= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) return NULL
;
473 len
= (size
- FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) / sizeof(WCHAR
);
475 if (info
->Type
== REG_EXPAND_SZ
)
477 UNICODE_STRING value
, expanded
;
479 value
.MaximumLength
= len
* sizeof(WCHAR
);
480 value
.Buffer
= (WCHAR
*)info
->Data
;
481 if (!value
.Buffer
[len
- 1]) len
--; /* don't count terminating null if any */
482 value
.Length
= len
* sizeof(WCHAR
);
483 expanded
.Length
= expanded
.MaximumLength
= 1024 * sizeof(WCHAR
);
484 if (!(expanded
.Buffer
= HeapAlloc( GetProcessHeap(), 0, expanded
.MaximumLength
))) return NULL
;
485 if (!RtlExpandEnvironmentStrings_U( NULL
, &value
, &expanded
, NULL
)) ret
= expanded
.Buffer
;
486 else RtlFreeUnicodeString( &expanded
);
488 else if (info
->Type
== REG_SZ
)
490 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
492 memcpy( ret
, info
->Data
, len
* sizeof(WCHAR
) );
500 /***********************************************************************
501 * set_additional_environment
503 * Set some additional environment variables not specified in the registry.
505 static void set_additional_environment(void)
507 static const WCHAR profile_keyW
[] = {'M','a','c','h','i','n','e','\\',
508 'S','o','f','t','w','a','r','e','\\',
509 'M','i','c','r','o','s','o','f','t','\\',
510 'W','i','n','d','o','w','s',' ','N','T','\\',
511 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
512 'P','r','o','f','i','l','e','L','i','s','t',0};
513 static const WCHAR profiles_valueW
[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
514 static const WCHAR all_users_valueW
[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
515 static const WCHAR allusersW
[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
516 OBJECT_ATTRIBUTES attr
;
517 UNICODE_STRING nameW
;
518 WCHAR
*profile_dir
= NULL
, *all_users_dir
= NULL
;
522 /* set the ALLUSERSPROFILE variables */
524 attr
.Length
= sizeof(attr
);
525 attr
.RootDirectory
= 0;
526 attr
.ObjectName
= &nameW
;
528 attr
.SecurityDescriptor
= NULL
;
529 attr
.SecurityQualityOfService
= NULL
;
530 RtlInitUnicodeString( &nameW
, profile_keyW
);
531 if (!NtOpenKey( &hkey
, KEY_READ
, &attr
))
533 profile_dir
= get_reg_value( hkey
, profiles_valueW
);
534 all_users_dir
= get_reg_value( hkey
, all_users_valueW
);
538 if (profile_dir
&& all_users_dir
)
542 len
= strlenW(profile_dir
) + strlenW(all_users_dir
) + 2;
543 value
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
544 strcpyW( value
, profile_dir
);
545 p
= value
+ strlenW(value
);
546 if (p
> value
&& p
[-1] != '\\') *p
++ = '\\';
547 strcpyW( p
, all_users_dir
);
548 SetEnvironmentVariableW( allusersW
, value
);
549 HeapFree( GetProcessHeap(), 0, value
);
552 HeapFree( GetProcessHeap(), 0, all_users_dir
);
553 HeapFree( GetProcessHeap(), 0, profile_dir
);
556 /***********************************************************************
557 * set_wow64_environment
559 * Set the environment variables that change across 32/64/Wow64.
561 static void set_wow64_environment(void)
563 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};
564 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};
565 static const WCHAR x86W
[] = {'x','8','6',0};
566 static const WCHAR versionW
[] = {'M','a','c','h','i','n','e','\\',
567 'S','o','f','t','w','a','r','e','\\',
568 'M','i','c','r','o','s','o','f','t','\\',
569 'W','i','n','d','o','w','s','\\',
570 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
571 static const WCHAR progdirW
[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
572 static const WCHAR progdir86W
[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
573 static const WCHAR progfilesW
[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
574 static const WCHAR progw6432W
[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
575 static const WCHAR commondirW
[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
576 static const WCHAR commondir86W
[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
577 static const WCHAR commonfilesW
[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
578 static const WCHAR commonw6432W
[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
580 OBJECT_ATTRIBUTES attr
;
581 UNICODE_STRING nameW
;
586 /* set the PROCESSOR_ARCHITECTURE variable */
588 if (GetEnvironmentVariableW( arch6432W
, arch
, sizeof(arch
)/sizeof(WCHAR
) ))
592 SetEnvironmentVariableW( archW
, arch
);
593 SetEnvironmentVariableW( arch6432W
, NULL
);
596 else if (GetEnvironmentVariableW( archW
, arch
, sizeof(arch
)/sizeof(WCHAR
) ))
600 SetEnvironmentVariableW( arch6432W
, arch
);
601 SetEnvironmentVariableW( archW
, x86W
);
605 attr
.Length
= sizeof(attr
);
606 attr
.RootDirectory
= 0;
607 attr
.ObjectName
= &nameW
;
609 attr
.SecurityDescriptor
= NULL
;
610 attr
.SecurityQualityOfService
= NULL
;
611 RtlInitUnicodeString( &nameW
, versionW
);
612 if (NtOpenKey( &hkey
, KEY_READ
| KEY_WOW64_64KEY
, &attr
)) return;
614 /* set the ProgramFiles variables */
616 if ((value
= get_reg_value( hkey
, progdirW
)))
618 if (is_win64
|| is_wow64
) SetEnvironmentVariableW( progw6432W
, value
);
619 if (is_win64
|| !is_wow64
) SetEnvironmentVariableW( progfilesW
, value
);
620 HeapFree( GetProcessHeap(), 0, value
);
622 if (is_wow64
&& (value
= get_reg_value( hkey
, progdir86W
)))
624 SetEnvironmentVariableW( progfilesW
, value
);
625 HeapFree( GetProcessHeap(), 0, value
);
628 /* set the CommonProgramFiles variables */
630 if ((value
= get_reg_value( hkey
, commondirW
)))
632 if (is_win64
|| is_wow64
) SetEnvironmentVariableW( commonw6432W
, value
);
633 if (is_win64
|| !is_wow64
) SetEnvironmentVariableW( commonfilesW
, value
);
634 HeapFree( GetProcessHeap(), 0, value
);
636 if (is_wow64
&& (value
= get_reg_value( hkey
, commondir86W
)))
638 SetEnvironmentVariableW( commonfilesW
, value
);
639 HeapFree( GetProcessHeap(), 0, value
);
645 /***********************************************************************
648 * Set the Wine library Unicode argv global variables.
650 static void set_library_wargv( char **argv
)
658 for (argc
= 0; argv
[argc
]; argc
++)
659 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
661 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
662 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
663 p
= (WCHAR
*)(wargv
+ argc
+ 1);
664 for (argc
= 0; argv
[argc
]; argc
++)
666 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
673 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
675 for (argc
= 0; wargv
[argc
]; argc
++)
676 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
678 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
679 q
= (char *)(argv
+ argc
+ 1);
680 for (argc
= 0; wargv
[argc
]; argc
++)
682 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
689 __wine_main_argc
= argc
;
690 __wine_main_argv
= argv
;
691 __wine_main_wargv
= wargv
;
695 /***********************************************************************
696 * update_library_argv0
698 * Update the argv[0] global variable with the binary we have found.
700 static void update_library_argv0( const WCHAR
*argv0
)
702 DWORD len
= strlenW( argv0
);
704 if (len
> strlenW( __wine_main_wargv
[0] ))
706 __wine_main_wargv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
708 strcpyW( __wine_main_wargv
[0], argv0
);
710 len
= WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, NULL
, 0, NULL
, NULL
);
711 if (len
> strlen( __wine_main_argv
[0] ) + 1)
713 __wine_main_argv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, len
);
715 WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, __wine_main_argv
[0], len
, NULL
, NULL
);
719 /***********************************************************************
722 * Build the command line of a process from the argv array.
724 * Note that it does NOT necessarily include the file name.
725 * Sometimes we don't even have any command line options at all.
727 * We must quote and escape characters so that the argv array can be rebuilt
728 * from the command line:
729 * - spaces and tabs must be quoted
731 * - quotes must be escaped
733 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
734 * resulting in an odd number of '\' followed by a '"'
737 * - '\'s that are not followed by a '"' can be left as is
741 static BOOL
build_command_line( WCHAR
**argv
)
746 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
748 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
751 for (arg
= argv
; *arg
; arg
++)
760 if( !*a
) has_space
=TRUE
;
765 if (*a
==' ' || *a
=='\t') {
767 } else if (*a
=='"') {
768 /* doubling of '\' preceding a '"',
769 * plus escaping of said '"'
777 len
+=(a
-*arg
)+1 /* for the separating space */;
779 len
+=2; /* for the quotes */
782 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
785 p
= rupp
->CommandLine
.Buffer
;
786 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
787 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
788 for (arg
= argv
; *arg
; arg
++)
790 BOOL has_space
,has_quote
;
793 /* Check for quotes and spaces in this argument */
794 has_space
=has_quote
=FALSE
;
796 if( !*a
) has_space
=TRUE
;
798 if (*a
==' ' || *a
=='\t') {
802 } else if (*a
=='"') {
810 /* Now transfer it to the command line */
826 /* Double all the '\\' preceding this '"', plus one */
827 for (i
=0;i
<=bcount
;i
++)
839 while ((*p
=*x
++)) p
++;
845 if (p
> rupp
->CommandLine
.Buffer
)
846 p
--; /* remove last space */
853 /***********************************************************************
854 * init_current_directory
856 * Initialize the current directory from the Unix cwd or the parent info.
858 static void init_current_directory( CURDIR
*cur_dir
)
860 UNICODE_STRING dir_str
;
865 /* if we received a cur dir from the parent, try this first */
867 if (cur_dir
->DosPath
.Length
)
869 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
872 /* now try to get it from the Unix cwd */
874 for (size
= 256; ; size
*= 2)
876 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
877 if (getcwd( cwd
, size
)) break;
878 HeapFree( GetProcessHeap(), 0, cwd
);
879 if (errno
== ERANGE
) continue;
884 /* try to use PWD if it is valid, so that we don't resolve symlinks */
886 pwd
= getenv( "PWD" );
889 struct stat st1
, st2
;
891 if (!pwd
|| stat( pwd
, &st1
) == -1 ||
892 (!stat( cwd
, &st2
) && (st1
.st_dev
!= st2
.st_dev
|| st1
.st_ino
!= st2
.st_ino
)))
898 ANSI_STRING unix_name
;
899 UNICODE_STRING nt_name
;
900 RtlInitAnsiString( &unix_name
, pwd
);
901 if (!wine_unix_to_nt_file_name( &unix_name
, &nt_name
))
903 UNICODE_STRING dos_path
;
904 /* skip the \??\ prefix, nt_name is 0 terminated */
905 RtlInitUnicodeString( &dos_path
, nt_name
.Buffer
+ 4 );
906 RtlSetCurrentDirectory_U( &dos_path
);
907 RtlFreeUnicodeString( &nt_name
);
911 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
913 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
914 "starting in the Windows directory.\n", cwd
? cwd
: "" );
915 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
916 RtlSetCurrentDirectory_U( &dir_str
);
918 HeapFree( GetProcessHeap(), 0, cwd
);
921 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
925 /***********************************************************************
928 * Initialize the windows and system directories from the environment.
930 static void init_windows_dirs(void)
932 extern void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
934 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
935 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
936 static const WCHAR default_windirW
[] = {'C',':','\\','w','i','n','d','o','w','s',0};
937 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m','3','2',0};
938 static const WCHAR default_syswow64W
[] = {'\\','s','y','s','w','o','w','6','4',0};
943 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
945 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
946 GetEnvironmentVariableW( windirW
, buffer
, len
);
947 DIR_Windows
= buffer
;
949 else DIR_Windows
= default_windirW
;
951 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
953 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
954 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
959 len
= strlenW( DIR_Windows
);
960 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
961 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
962 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
966 if (!CreateDirectoryW( DIR_Windows
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
967 ERR( "directory %s could not be created, error %u\n",
968 debugstr_w(DIR_Windows
), GetLastError() );
969 if (!CreateDirectoryW( DIR_System
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
970 ERR( "directory %s could not be created, error %u\n",
971 debugstr_w(DIR_System
), GetLastError() );
973 if (is_win64
|| is_wow64
) /* SysWow64 is always defined on 64-bit */
975 len
= strlenW( DIR_Windows
);
976 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_syswow64W
) );
977 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
978 memcpy( buffer
+ len
, default_syswow64W
, sizeof(default_syswow64W
) );
979 DIR_SysWow64
= buffer
;
980 if (!CreateDirectoryW( DIR_SysWow64
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
981 ERR( "directory %s could not be created, error %u\n",
982 debugstr_w(DIR_SysWow64
), GetLastError() );
985 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
986 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
988 /* set the directories in ntdll too */
989 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
993 /***********************************************************************
996 * Start the wineboot process if necessary. Return the handles to wait on.
998 static void start_wineboot( HANDLE handles
[2] )
1000 static const WCHAR wineboot_eventW
[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
1003 if (!(handles
[0] = CreateEventW( NULL
, TRUE
, FALSE
, wineboot_eventW
)))
1005 ERR( "failed to create wineboot event, expect trouble\n" );
1008 if (GetLastError() != ERROR_ALREADY_EXISTS
) /* we created it */
1010 static const WCHAR wineboot
[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1011 static const WCHAR args
[] = {' ','-','-','i','n','i','t',0};
1013 PROCESS_INFORMATION pi
;
1015 WCHAR app
[MAX_PATH
];
1016 WCHAR cmdline
[MAX_PATH
+ (sizeof(wineboot
) + sizeof(args
)) / sizeof(WCHAR
)];
1018 memset( &si
, 0, sizeof(si
) );
1020 si
.dwFlags
= STARTF_USESTDHANDLES
;
1023 si
.hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
1025 GetSystemDirectoryW( app
, MAX_PATH
- sizeof(wineboot
)/sizeof(WCHAR
) );
1026 lstrcatW( app
, wineboot
);
1028 Wow64DisableWow64FsRedirection( &redir
);
1029 strcpyW( cmdline
, app
);
1030 strcatW( cmdline
, args
);
1031 if (CreateProcessW( app
, cmdline
, NULL
, NULL
, FALSE
, DETACHED_PROCESS
, NULL
, NULL
, &si
, &pi
))
1033 TRACE( "started wineboot pid %04x tid %04x\n", pi
.dwProcessId
, pi
.dwThreadId
);
1034 CloseHandle( pi
.hThread
);
1035 handles
[1] = pi
.hProcess
;
1039 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1040 CloseHandle( handles
[0] );
1043 Wow64RevertWow64FsRedirection( redir
);
1049 extern DWORD
call_process_entry( PEB
*peb
, LPTHREAD_START_ROUTINE entry
);
1050 __ASM_GLOBAL_FUNC( call_process_entry
,
1052 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1053 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1054 "movl %esp,%ebp\n\t"
1055 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1056 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1058 "call *12(%ebp)\n\t"
1060 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1061 __ASM_CFI(".cfi_same_value %ebp\n\t")
1064 static inline DWORD
call_process_entry( PEB
*peb
, LPTHREAD_START_ROUTINE entry
)
1066 return entry( peb
);
1070 /***********************************************************************
1073 * Startup routine of a new process. Runs on the new process stack.
1075 static DWORD WINAPI
start_process( PEB
*peb
)
1077 IMAGE_NT_HEADERS
*nt
;
1078 LPTHREAD_START_ROUTINE entry
;
1080 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1081 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
1082 nt
->OptionalHeader
.AddressOfEntryPoint
);
1084 if (!nt
->OptionalHeader
.AddressOfEntryPoint
)
1086 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1087 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
) );
1091 if (TRACE_ON(relay
))
1092 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1093 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
1095 SetLastError( 0 ); /* clear error code */
1096 if (peb
->BeingDebugged
) DbgBreakPoint();
1097 return call_process_entry( peb
, entry
);
1101 /***********************************************************************
1104 * Change the process name in the ps output.
1106 static void set_process_name( int argc
, char *argv
[] )
1108 #ifdef HAVE_SETPROCTITLE
1109 setproctitle("-%s", argv
[1]);
1114 char *p
, *prctl_name
= argv
[1];
1115 char *end
= argv
[argc
-1] + strlen(argv
[argc
-1]) + 1;
1118 # define PR_SET_NAME 15
1121 if ((p
= strrchr( prctl_name
, '\\' ))) prctl_name
= p
+ 1;
1122 if ((p
= strrchr( prctl_name
, '/' ))) prctl_name
= p
+ 1;
1124 if (prctl( PR_SET_NAME
, prctl_name
) != -1)
1126 offset
= argv
[1] - argv
[0];
1127 memmove( argv
[1] - offset
, argv
[1], end
- argv
[1] );
1128 memset( end
- offset
, 0, offset
);
1129 for (i
= 1; i
< argc
; i
++) argv
[i
-1] = argv
[i
] - offset
;
1133 #endif /* HAVE_PRCTL */
1135 /* remove argv[0] */
1136 memmove( argv
, argv
+ 1, argc
* sizeof(argv
[0]) );
1141 /***********************************************************************
1142 * __wine_kernel_init
1144 * Wine initialisation: load and start the main exe file.
1146 void CDECL
__wine_kernel_init(void)
1148 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
1149 static const WCHAR dotW
[] = {'.',0};
1151 WCHAR
*p
, main_exe_name
[MAX_PATH
+1];
1152 PEB
*peb
= NtCurrentTeb()->Peb
;
1153 RTL_USER_PROCESS_PARAMETERS
*params
= peb
->ProcessParameters
;
1154 HANDLE boot_events
[2];
1155 BOOL got_environment
= TRUE
;
1157 /* Initialize everything */
1159 setbuf(stdout
,NULL
);
1160 setbuf(stderr
,NULL
);
1161 kernel32_handle
= GetModuleHandleW(kernel32W
);
1162 IsWow64Process( GetCurrentProcess(), &is_wow64
);
1166 if (!params
->Environment
)
1168 /* Copy the parent environment */
1169 if (!build_initial_environment()) exit(1);
1171 /* convert old configuration to new format */
1172 convert_old_config();
1174 got_environment
= set_registry_environment( FALSE
);
1175 set_additional_environment();
1178 init_windows_dirs();
1179 init_current_directory( ¶ms
->CurrentDirectory
);
1181 set_process_name( __wine_main_argc
, __wine_main_argv
);
1182 set_library_wargv( __wine_main_argv
);
1183 boot_events
[0] = boot_events
[1] = 0;
1185 if (peb
->ProcessParameters
->ImagePathName
.Buffer
)
1187 strcpyW( main_exe_name
, peb
->ProcessParameters
->ImagePathName
.Buffer
);
1191 struct binary_info binary_info
;
1193 if (!SearchPathW( NULL
, __wine_main_wargv
[0], exeW
, MAX_PATH
, main_exe_name
, NULL
) &&
1194 !get_builtin_path( __wine_main_wargv
[0], exeW
, main_exe_name
, MAX_PATH
, &binary_info
))
1196 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1197 ExitProcess( GetLastError() );
1199 update_library_argv0( main_exe_name
);
1200 if (!build_command_line( __wine_main_wargv
)) goto error
;
1201 start_wineboot( boot_events
);
1204 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1205 p
= strrchrW( main_exe_name
, '.' );
1206 if (!p
|| strchrW( p
, '/' ) || strchrW( p
, '\\' )) strcatW( main_exe_name
, dotW
);
1208 TRACE( "starting process name=%s argv[0]=%s\n",
1209 debugstr_w(main_exe_name
), debugstr_w(__wine_main_wargv
[0]) );
1211 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1212 MODULE_get_dll_load_path(main_exe_name
) );
1216 DWORD timeout
= 2 * 60 * 1000, count
= 1;
1218 if (boot_events
[1]) count
++;
1219 if (!got_environment
) timeout
= 5 * 60 * 1000; /* initial prefix creation can take longer */
1220 if (WaitForMultipleObjects( count
, boot_events
, FALSE
, timeout
) == WAIT_TIMEOUT
)
1221 ERR( "boot event wait timed out\n" );
1222 CloseHandle( boot_events
[0] );
1223 if (boot_events
[1]) CloseHandle( boot_events
[1] );
1224 /* reload environment now that wineboot has run */
1225 set_registry_environment( got_environment
);
1226 set_additional_environment();
1228 set_wow64_environment();
1230 if (!(peb
->ImageBaseAddress
= LoadLibraryExW( main_exe_name
, 0, DONT_RESOLVE_DLL_REFERENCES
)))
1235 DWORD error
= GetLastError();
1237 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1238 if (error
== ERROR_BAD_EXE_FORMAT
||
1239 error
== ERROR_INVALID_ADDRESS
||
1240 error
== ERROR_NOT_ENOUGH_MEMORY
)
1242 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name
);
1243 /* if we get back here, it failed */
1245 else if (error
== ERROR_MOD_NOT_FOUND
)
1247 if ((p
= strrchrW( main_exe_name
, '\\' ))) p
++;
1248 else p
= main_exe_name
;
1249 if (!strcmpiW( p
, winevdmW
) && __wine_main_argc
> 3)
1251 /* args 1 and 2 are --app-name full_path */
1252 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1253 debugstr_w(__wine_main_wargv
[3]) );
1254 ExitProcess( ERROR_BAD_EXE_FORMAT
);
1256 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name
) );
1257 ExitProcess( ERROR_FILE_NOT_FOUND
);
1259 args
[0] = (DWORD_PTR
)main_exe_name
;
1260 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ARGUMENT_ARRAY
,
1261 NULL
, error
, 0, msgW
, sizeof(msgW
)/sizeof(WCHAR
), (__ms_va_list
*)args
);
1262 WideCharToMultiByte( CP_UNIXCP
, 0, msgW
, -1, msg
, sizeof(msg
), NULL
, NULL
);
1263 MESSAGE( "wine: %s", msg
);
1264 ExitProcess( error
);
1267 if (!params
->CurrentDirectory
.Handle
) chdir("/"); /* avoid locking removable devices */
1269 LdrInitializeThunk( start_process
, 0, 0, 0 );
1272 ExitProcess( GetLastError() );
1276 /***********************************************************************
1279 * Build an argv array from a command-line.
1280 * 'reserved' is the number of args to reserve before the first one.
1282 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1286 char *arg
,*s
,*d
,*cmdline
;
1287 int in_quotes
,bcount
,len
;
1289 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1290 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, len
))) return NULL
;
1291 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1298 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1301 /* skip the remaining spaces */
1302 while (*s
==' ' || *s
=='\t') {
1309 } else if (*s
=='\\') {
1310 /* '\', count them */
1312 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1314 in_quotes
=!in_quotes
;
1317 /* a regular character */
1322 if (!(argv
= HeapAlloc( GetProcessHeap(), 0, argc
*sizeof(*argv
) + len
)))
1324 HeapFree( GetProcessHeap(), 0, cmdline
);
1328 arg
= d
= s
= (char *)(argv
+ argc
);
1329 memcpy( d
, cmdline
, len
);
1334 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1335 /* Close the argument and copy it */
1339 /* skip the remaining spaces */
1342 } while (*s
==' ' || *s
=='\t');
1344 /* Start with a new argument */
1347 } else if (*s
=='\\') {
1351 } else if (*s
=='"') {
1353 if ((bcount
& 1)==0) {
1354 /* Preceded by an even number of '\', this is half that
1355 * number of '\', plus a '"' which we discard.
1359 in_quotes
=!in_quotes
;
1361 /* Preceded by an odd number of '\', this is half that
1362 * number of '\' followed by a '"'
1370 /* a regular character */
1381 HeapFree( GetProcessHeap(), 0, cmdline
);
1386 /***********************************************************************
1389 * Build the environment of a new child process.
1391 static char **build_envp( const WCHAR
*envW
)
1393 static const char * const unix_vars
[] = { "PATH", "TEMP", "TMP", "HOME" };
1398 int count
= 1, length
;
1401 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1403 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1404 if (!(env
= HeapAlloc( GetProcessHeap(), 0, length
))) return NULL
;
1405 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1407 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1408 if (is_special_env_var( p
)) length
+= 4; /* prefix it with "WINE" */
1410 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1412 if (!(p
= getenv(unix_vars
[i
]))) continue;
1413 length
+= strlen(unix_vars
[i
]) + strlen(p
) + 2;
1417 if ((envp
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*envp
) + length
)))
1419 char **envptr
= envp
;
1420 char *dst
= (char *)(envp
+ count
);
1422 /* some variables must not be modified, so we get them directly from the unix env */
1423 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1425 if (!(p
= getenv(unix_vars
[i
]))) continue;
1426 *envptr
++ = strcpy( dst
, unix_vars
[i
] );
1429 dst
+= strlen(dst
) + 1;
1432 /* now put the Windows environment strings */
1433 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1435 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1436 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1437 if (!strncmp( p
, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1438 if (!strncmp( p
, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1439 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1441 *envptr
++ = strcpy( dst
, "WINE" );
1446 *envptr
++ = strcpy( dst
, p
);
1448 dst
+= strlen(dst
) + 1;
1452 HeapFree( GetProcessHeap(), 0, env
);
1457 /***********************************************************************
1460 * Fork and exec a new Unix binary, checking for errors.
1462 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
, const WCHAR
*env
,
1463 const char *newdir
, DWORD flags
, STARTUPINFOW
*startup
)
1465 int fd
[2], stdin_fd
= -1, stdout_fd
= -1, stderr_fd
= -1;
1467 char **argv
, **envp
;
1469 if (!env
) env
= GetEnvironmentStringsW();
1472 if (pipe2( fd
, O_CLOEXEC
) == -1)
1477 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1480 fcntl( fd
[0], F_SETFD
, FD_CLOEXEC
);
1481 fcntl( fd
[1], F_SETFD
, FD_CLOEXEC
);
1484 if (!(flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1486 HANDLE hstdin
, hstdout
, hstderr
;
1488 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1490 hstdin
= startup
->hStdInput
;
1491 hstdout
= startup
->hStdOutput
;
1492 hstderr
= startup
->hStdError
;
1496 hstdin
= GetStdHandle(STD_INPUT_HANDLE
);
1497 hstdout
= GetStdHandle(STD_OUTPUT_HANDLE
);
1498 hstderr
= GetStdHandle(STD_ERROR_HANDLE
);
1501 if (is_console_handle( hstdin
))
1502 hstdin
= wine_server_ptr_handle( console_handle_unmap( hstdin
));
1503 if (is_console_handle( hstdout
))
1504 hstdout
= wine_server_ptr_handle( console_handle_unmap( hstdout
));
1505 if (is_console_handle( hstderr
))
1506 hstderr
= wine_server_ptr_handle( console_handle_unmap( hstderr
));
1507 wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1508 wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1509 wine_server_handle_to_fd( hstderr
, FILE_WRITE_DATA
, &stderr_fd
, NULL
);
1512 argv
= build_argv( cmdline
, 0 );
1513 envp
= build_envp( env
);
1515 if (!(pid
= fork())) /* child */
1517 if (!(pid
= fork())) /* grandchild */
1521 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1523 int nullfd
= open( "/dev/null", O_RDWR
);
1525 /* close stdin and stdout */
1537 dup2( stdin_fd
, 0 );
1540 if (stdout_fd
!= -1)
1542 dup2( stdout_fd
, 1 );
1545 if (stderr_fd
!= -1)
1547 dup2( stderr_fd
, 2 );
1552 /* Reset signals that we previously set to SIG_IGN */
1553 signal( SIGPIPE
, SIG_DFL
);
1555 if (newdir
) chdir(newdir
);
1557 if (argv
&& envp
) execve( filename
, argv
, envp
);
1560 if (pid
<= 0) /* grandchild if exec failed or child if fork failed */
1563 write( fd
[1], &err
, sizeof(err
) );
1567 _exit(0); /* child if fork succeeded */
1569 HeapFree( GetProcessHeap(), 0, argv
);
1570 HeapFree( GetProcessHeap(), 0, envp
);
1571 if (stdin_fd
!= -1) close( stdin_fd
);
1572 if (stdout_fd
!= -1) close( stdout_fd
);
1573 if (stderr_fd
!= -1) close( stderr_fd
);
1579 err
= waitpid(pid
, NULL
, 0);
1580 } while (err
< 0 && errno
== EINTR
);
1582 if (read( fd
[0], &err
, sizeof(err
) ) > 0) /* exec or second fork failed */
1588 if (pid
== -1) FILE_SetDosError();
1594 static inline DWORD
append_string( void **ptr
, const WCHAR
*str
)
1596 DWORD len
= strlenW( str
);
1597 memcpy( *ptr
, str
, len
* sizeof(WCHAR
) );
1598 *ptr
= (WCHAR
*)*ptr
+ len
;
1599 return len
* sizeof(WCHAR
);
1602 /***********************************************************************
1603 * create_startup_info
1605 static startup_info_t
*create_startup_info( LPCWSTR filename
, LPCWSTR cmdline
,
1606 LPCWSTR cur_dir
, LPWSTR env
, DWORD flags
,
1607 const STARTUPINFOW
*startup
, DWORD
*info_size
)
1609 const RTL_USER_PROCESS_PARAMETERS
*cur_params
;
1611 startup_info_t
*info
;
1614 UNICODE_STRING newdir
;
1615 WCHAR imagepath
[MAX_PATH
];
1616 HANDLE hstdin
, hstdout
, hstderr
;
1618 if(!GetLongPathNameW( filename
, imagepath
, MAX_PATH
))
1619 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1620 if(!GetFullPathNameW( imagepath
, MAX_PATH
, imagepath
, NULL
))
1621 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1623 cur_params
= NtCurrentTeb()->Peb
->ProcessParameters
;
1625 newdir
.Buffer
= NULL
;
1628 if (RtlDosPathNameToNtPathName_U( cur_dir
, &newdir
, NULL
, NULL
))
1629 cur_dir
= newdir
.Buffer
+ 4; /* skip \??\ prefix */
1635 if (NtCurrentTeb()->Tib
.SubSystemTib
) /* FIXME: hack */
1636 cur_dir
= ((WIN16_SUBSYSTEM_TIB
*)NtCurrentTeb()->Tib
.SubSystemTib
)->curdir
.DosPath
.Buffer
;
1638 cur_dir
= cur_params
->CurrentDirectory
.DosPath
.Buffer
;
1640 title
= startup
->lpTitle
? startup
->lpTitle
: imagepath
;
1642 size
= sizeof(*info
);
1643 size
+= strlenW( cur_dir
) * sizeof(WCHAR
);
1644 size
+= cur_params
->DllPath
.Length
;
1645 size
+= strlenW( imagepath
) * sizeof(WCHAR
);
1646 size
+= strlenW( cmdline
) * sizeof(WCHAR
);
1647 size
+= strlenW( title
) * sizeof(WCHAR
);
1648 if (startup
->lpDesktop
) size
+= strlenW( startup
->lpDesktop
) * sizeof(WCHAR
);
1649 /* FIXME: shellinfo */
1650 if (startup
->lpReserved2
&& startup
->cbReserved2
) size
+= startup
->cbReserved2
;
1651 size
= (size
+ 1) & ~1;
1654 if (!(info
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, size
))) goto done
;
1656 info
->console_flags
= cur_params
->ConsoleFlags
;
1657 if (flags
& CREATE_NEW_PROCESS_GROUP
) info
->console_flags
= 1;
1658 if (flags
& CREATE_NEW_CONSOLE
) info
->console
= wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC
);
1660 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1662 hstdin
= startup
->hStdInput
;
1663 hstdout
= startup
->hStdOutput
;
1664 hstderr
= startup
->hStdError
;
1668 hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1669 hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1670 hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1672 info
->hstdin
= wine_server_obj_handle( hstdin
);
1673 info
->hstdout
= wine_server_obj_handle( hstdout
);
1674 info
->hstderr
= wine_server_obj_handle( hstderr
);
1675 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1677 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1678 if (is_console_handle(hstdin
)) info
->hstdin
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1679 if (is_console_handle(hstdout
)) info
->hstdout
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1680 if (is_console_handle(hstderr
)) info
->hstderr
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1684 if (is_console_handle(hstdin
)) info
->hstdin
= console_handle_unmap(hstdin
);
1685 if (is_console_handle(hstdout
)) info
->hstdout
= console_handle_unmap(hstdout
);
1686 if (is_console_handle(hstderr
)) info
->hstderr
= console_handle_unmap(hstderr
);
1689 info
->x
= startup
->dwX
;
1690 info
->y
= startup
->dwY
;
1691 info
->xsize
= startup
->dwXSize
;
1692 info
->ysize
= startup
->dwYSize
;
1693 info
->xchars
= startup
->dwXCountChars
;
1694 info
->ychars
= startup
->dwYCountChars
;
1695 info
->attribute
= startup
->dwFillAttribute
;
1696 info
->flags
= startup
->dwFlags
;
1697 info
->show
= startup
->wShowWindow
;
1700 info
->curdir_len
= append_string( &ptr
, cur_dir
);
1701 info
->dllpath_len
= cur_params
->DllPath
.Length
;
1702 memcpy( ptr
, cur_params
->DllPath
.Buffer
, cur_params
->DllPath
.Length
);
1703 ptr
= (char *)ptr
+ cur_params
->DllPath
.Length
;
1704 info
->imagepath_len
= append_string( &ptr
, imagepath
);
1705 info
->cmdline_len
= append_string( &ptr
, cmdline
);
1706 info
->title_len
= append_string( &ptr
, title
);
1707 if (startup
->lpDesktop
) info
->desktop_len
= append_string( &ptr
, startup
->lpDesktop
);
1708 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1710 info
->runtime_len
= startup
->cbReserved2
;
1711 memcpy( ptr
, startup
->lpReserved2
, startup
->cbReserved2
);
1715 RtlFreeUnicodeString( &newdir
);
1719 /***********************************************************************
1720 * get_alternate_loader
1722 * Get the name of the alternate (32 or 64 bit) Wine loader.
1724 static const char *get_alternate_loader( char **ret_env
)
1727 const char *loader
= NULL
;
1728 const char *loader_env
= getenv( "WINELOADER" );
1732 if (wine_get_build_dir()) loader
= is_win64
? "loader/wine" : "server/../loader/wine64";
1736 int len
= strlen( loader_env
);
1739 if (!(env
= HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len
+ 2 ))) return NULL
;
1740 strcpy( env
, "WINELOADER=" );
1741 strcat( env
, loader_env
);
1742 strcat( env
, "64" );
1746 if (!(env
= HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len
))) return NULL
;
1747 strcpy( env
, "WINELOADER=" );
1748 strcat( env
, loader_env
);
1749 len
+= sizeof("WINELOADER=") - 1;
1750 if (!strcmp( env
+ len
- 2, "64" )) env
[len
- 2] = 0;
1754 if ((loader
= strrchr( env
, '/' ))) loader
++;
1759 if (!loader
) loader
= is_win64
? "wine" : "wine64";
1764 /***********************************************************************
1765 * terminate_main_thread
1767 * On some versions of Mac OS X, the execve system call fails with
1768 * ENOTSUP if the process has multiple threads. Wine is always multi-
1769 * threaded on Mac OS X because it specifically reserves the main thread
1770 * for use by the system frameworks (see apple_main_thread() in
1771 * libs/wine/loader.c). So, when we need to exec without first forking,
1772 * we need to terminate the main thread first. We do this by installing
1773 * a custom run loop source onto the main run loop and signaling it.
1774 * The source's "perform" callback is pthread_exit and it will be
1775 * executed on the main thread, terminating it.
1777 * Returns TRUE if there's still hope the main thread has terminated or
1778 * will soon. Return FALSE if we've given up.
1780 static BOOL
terminate_main_thread(void)
1786 CFRunLoopSourceContext source_context
= { 0 };
1787 CFRunLoopSourceRef source
;
1789 source_context
.perform
= pthread_exit
;
1790 if (!(source
= CFRunLoopSourceCreate( NULL
, 0, &source_context
)))
1793 CFRunLoopAddSource( CFRunLoopGetMain(), source
, kCFRunLoopCommonModes
);
1794 CFRunLoopSourceSignal( source
);
1795 CFRunLoopWakeUp( CFRunLoopGetMain() );
1796 CFRelease( source
);
1804 usleep(delayms
* 1000);
1811 /***********************************************************************
1814 static int get_process_cpu( const WCHAR
*filename
, const struct binary_info
*binary_info
)
1816 switch (binary_info
->arch
)
1818 case IMAGE_FILE_MACHINE_I386
: return CPU_x86
;
1819 case IMAGE_FILE_MACHINE_AMD64
: return CPU_x86_64
;
1820 case IMAGE_FILE_MACHINE_POWERPC
: return CPU_POWERPC
;
1821 case IMAGE_FILE_MACHINE_ARM
:
1822 case IMAGE_FILE_MACHINE_THUMB
:
1823 case IMAGE_FILE_MACHINE_ARMNT
: return CPU_ARM
;
1824 case IMAGE_FILE_MACHINE_ARM64
: return CPU_ARM64
;
1826 ERR( "%s uses unsupported architecture (%04x)\n", debugstr_w(filename
), binary_info
->arch
);
1830 /***********************************************************************
1833 static pid_t
exec_loader( LPCWSTR cmd_line
, unsigned int flags
, int socketfd
,
1834 int stdin_fd
, int stdout_fd
, const char *unixdir
, char *winedebug
,
1835 const struct binary_info
*binary_info
, int exec_only
)
1838 char *wineloader
= NULL
;
1839 const char *loader
= NULL
;
1842 argv
= build_argv( cmd_line
, 1 );
1844 if (!is_win64
^ !(binary_info
->flags
& BINARY_FLAG_64BIT
))
1845 loader
= get_alternate_loader( &wineloader
);
1847 if (exec_only
|| !(pid
= fork())) /* child */
1849 if (exec_only
|| !(pid
= fork())) /* grandchild */
1851 char preloader_reserve
[64], socket_env
[64];
1853 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1855 int fd
= open( "/dev/null", O_RDWR
);
1857 /* close stdin and stdout */
1867 if (stdin_fd
!= -1) dup2( stdin_fd
, 0 );
1868 if (stdout_fd
!= -1) dup2( stdout_fd
, 1 );
1871 if (stdin_fd
!= -1) close( stdin_fd
);
1872 if (stdout_fd
!= -1) close( stdout_fd
);
1874 /* Reset signals that we previously set to SIG_IGN */
1875 signal( SIGPIPE
, SIG_DFL
);
1877 sprintf( socket_env
, "WINESERVERSOCKET=%u", socketfd
);
1878 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx",
1879 (unsigned long)binary_info
->res_start
, (unsigned long)binary_info
->res_end
);
1881 putenv( preloader_reserve
);
1882 putenv( socket_env
);
1883 if (winedebug
) putenv( winedebug
);
1884 if (wineloader
) putenv( wineloader
);
1885 if (unixdir
) chdir(unixdir
);
1891 wine_exec_wine_binary( loader
, argv
, getenv("WINELOADER") );
1894 while (errno
== ENOTSUP
&& exec_only
&& terminate_main_thread());
1910 wret
= waitpid(pid
, NULL
, 0);
1911 } while (wret
< 0 && errno
== EINTR
);
1914 HeapFree( GetProcessHeap(), 0, wineloader
);
1915 HeapFree( GetProcessHeap(), 0, argv
);
1919 /***********************************************************************
1922 * Create a new process. If hFile is a valid handle we have an exe
1923 * file, otherwise it is a Winelib app.
1925 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1926 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1927 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1928 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1929 const struct binary_info
*binary_info
, int exec_only
)
1931 static const char *cpu_names
[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1933 BOOL success
= FALSE
;
1934 HANDLE process_info
;
1936 char *winedebug
= NULL
;
1937 startup_info_t
*startup_info
;
1938 DWORD startup_info_size
;
1939 int socketfd
[2], stdin_fd
= -1, stdout_fd
= -1;
1943 if ((cpu
= get_process_cpu( filename
, binary_info
)) == -1)
1945 SetLastError( ERROR_BAD_EXE_FORMAT
);
1949 /* create the socket for the new process */
1951 if (socketpair( PF_UNIX
, SOCK_STREAM
, 0, socketfd
) == -1)
1953 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1960 setsockopt( socketfd
[0], SOL_SOCKET
, SO_PASSCRED
, &enable
, sizeof(enable
) );
1964 if (exec_only
) /* things are much simpler in this case */
1966 wine_server_send_fd( socketfd
[1] );
1967 close( socketfd
[1] );
1968 SERVER_START_REQ( new_process
)
1970 req
->create_flags
= flags
;
1971 req
->socket_fd
= socketfd
[1];
1972 req
->exe_file
= wine_server_obj_handle( hFile
);
1974 status
= wine_server_call( req
);
1980 case STATUS_INVALID_IMAGE_WIN_64
:
1981 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename
) );
1983 case STATUS_INVALID_IMAGE_FORMAT
:
1984 ERR( "%s not supported on this installation (%s binary)\n",
1985 debugstr_w(filename
), cpu_names
[cpu
] );
1987 case STATUS_SUCCESS
:
1988 exec_loader( cmd_line
, flags
, socketfd
[0], stdin_fd
, stdout_fd
, unixdir
,
1989 winedebug
, binary_info
, TRUE
);
1991 close( socketfd
[0] );
1992 SetLastError( RtlNtStatusToDosError( status
));
1996 RtlAcquirePebLock();
1998 if (!(startup_info
= create_startup_info( filename
, cmd_line
, cur_dir
, env
, flags
, startup
,
1999 &startup_info_size
)))
2001 RtlReleasePebLock();
2002 close( socketfd
[0] );
2003 close( socketfd
[1] );
2006 if (!env
) env
= NtCurrentTeb()->Peb
->ProcessParameters
->Environment
;
2010 static const WCHAR WINEDEBUG
[] = {'W','I','N','E','D','E','B','U','G','=',0};
2011 if (!winedebug
&& !strncmpW( env_end
, WINEDEBUG
, sizeof(WINEDEBUG
)/sizeof(WCHAR
) - 1 ))
2013 DWORD len
= WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, NULL
, 0, NULL
, NULL
);
2014 if ((winedebug
= HeapAlloc( GetProcessHeap(), 0, len
)))
2015 WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, winedebug
, len
, NULL
, NULL
);
2017 env_end
+= strlenW(env_end
) + 1;
2021 wine_server_send_fd( socketfd
[1] );
2022 close( socketfd
[1] );
2024 /* create the process on the server side */
2026 SERVER_START_REQ( new_process
)
2028 req
->inherit_all
= inherit
;
2029 req
->create_flags
= flags
;
2030 req
->socket_fd
= socketfd
[1];
2031 req
->exe_file
= wine_server_obj_handle( hFile
);
2032 req
->process_access
= PROCESS_ALL_ACCESS
;
2033 req
->process_attr
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
2034 req
->thread_access
= THREAD_ALL_ACCESS
;
2035 req
->thread_attr
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
2037 req
->info_size
= startup_info_size
;
2039 wine_server_add_data( req
, startup_info
, startup_info_size
);
2040 wine_server_add_data( req
, env
, (env_end
- env
) * sizeof(WCHAR
) );
2041 if (!(status
= wine_server_call( req
)))
2043 info
->dwProcessId
= (DWORD
)reply
->pid
;
2044 info
->dwThreadId
= (DWORD
)reply
->tid
;
2045 info
->hProcess
= wine_server_ptr_handle( reply
->phandle
);
2046 info
->hThread
= wine_server_ptr_handle( reply
->thandle
);
2048 process_info
= wine_server_ptr_handle( reply
->info
);
2052 RtlReleasePebLock();
2057 case STATUS_INVALID_IMAGE_WIN_64
:
2058 ERR( "64-bit application %s not supported in 32-bit prefix\n", debugstr_w(filename
) );
2060 case STATUS_INVALID_IMAGE_FORMAT
:
2061 ERR( "%s not supported on this installation (%s binary)\n",
2062 debugstr_w(filename
), cpu_names
[cpu
] );
2065 close( socketfd
[0] );
2066 HeapFree( GetProcessHeap(), 0, startup_info
);
2067 HeapFree( GetProcessHeap(), 0, winedebug
);
2068 SetLastError( RtlNtStatusToDosError( status
));
2072 if (!(flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
2074 if (startup_info
->hstdin
)
2075 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdin
),
2076 FILE_READ_DATA
, &stdin_fd
, NULL
);
2077 if (startup_info
->hstdout
)
2078 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdout
),
2079 FILE_WRITE_DATA
, &stdout_fd
, NULL
);
2081 HeapFree( GetProcessHeap(), 0, startup_info
);
2083 /* create the child process */
2085 pid
= exec_loader( cmd_line
, flags
, socketfd
[0], stdin_fd
, stdout_fd
, unixdir
,
2086 winedebug
, binary_info
, FALSE
);
2088 if (stdin_fd
!= -1) close( stdin_fd
);
2089 if (stdout_fd
!= -1) close( stdout_fd
);
2090 close( socketfd
[0] );
2091 HeapFree( GetProcessHeap(), 0, winedebug
);
2098 /* wait for the new process info to be ready */
2100 WaitForSingleObject( process_info
, INFINITE
);
2101 SERVER_START_REQ( get_new_process_info
)
2103 req
->info
= wine_server_obj_handle( process_info
);
2104 wine_server_call( req
);
2105 success
= reply
->success
;
2106 err
= reply
->exit_code
;
2112 SetLastError( err
? err
: ERROR_INTERNAL_ERROR
);
2115 CloseHandle( process_info
);
2119 CloseHandle( process_info
);
2120 CloseHandle( info
->hProcess
);
2121 CloseHandle( info
->hThread
);
2122 info
->hProcess
= info
->hThread
= 0;
2123 info
->dwProcessId
= info
->dwThreadId
= 0;
2128 /***********************************************************************
2129 * create_vdm_process
2131 * Create a new VDM process for a 16-bit or DOS application.
2133 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
2134 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
2135 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
2136 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
2137 const struct binary_info
*binary_info
, int exec_only
)
2139 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2142 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
2143 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
2147 SetLastError( ERROR_OUTOFMEMORY
);
2150 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
2151 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
2152 flags
, startup
, info
, unixdir
, binary_info
, exec_only
);
2153 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
2158 /***********************************************************************
2159 * create_cmd_process
2161 * Create a new cmd shell process for a .BAT file.
2163 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
2164 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
2165 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
2166 LPPROCESS_INFORMATION info
)
2169 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
2170 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
2171 WCHAR comspec
[MAX_PATH
];
2175 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
2177 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
2178 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
2181 strcpyW( newcmdline
, comspec
);
2182 strcatW( newcmdline
, slashcW
);
2183 strcatW( newcmdline
, cmd_line
);
2184 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
2185 flags
, env
, cur_dir
, startup
, info
);
2186 HeapFree( GetProcessHeap(), 0, newcmdline
);
2191 /*************************************************************************
2194 * Helper for CreateProcess: retrieve the file name to load from the
2195 * app name and command line. Store the file name in buffer, and
2196 * return a possibly modified command line.
2197 * Also returns a handle to the opened file if it's a Windows binary.
2199 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
2200 int buflen
, HANDLE
*handle
, struct binary_info
*binary_info
)
2202 static const WCHAR quotesW
[] = {'"','%','s','"',0};
2204 WCHAR
*name
, *pos
, *first_space
, *ret
= NULL
;
2207 /* if we have an app name, everything is easy */
2211 /* use the unmodified app name as file name */
2212 lstrcpynW( buffer
, appname
, buflen
);
2213 *handle
= open_exe_file( buffer
, binary_info
);
2214 if (!(ret
= cmdline
) || !cmdline
[0])
2216 /* no command-line, create one */
2217 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
2218 sprintfW( ret
, quotesW
, appname
);
2223 /* first check for a quoted file name */
2225 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
2227 int len
= p
- cmdline
- 1;
2228 /* extract the quoted portion as file name */
2229 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
2230 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
2233 if (!find_exe_file( name
, buffer
, buflen
, handle
, binary_info
)) goto done
;
2234 ret
= cmdline
; /* no change necessary */
2238 /* now try the command-line word by word */
2240 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
2248 while (*p
&& *p
!= ' ' && *p
!= '\t') *pos
++ = *p
++;
2250 if (find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
2255 if (!first_space
) first_space
= pos
;
2256 if (!(*pos
++ = *p
++)) break;
2261 SetLastError( ERROR_FILE_NOT_FOUND
);
2263 else if (first_space
) /* build a new command-line with quotes */
2265 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
2267 sprintfW( ret
, quotesW
, name
);
2272 HeapFree( GetProcessHeap(), 0, name
);
2277 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2278 static BOOL
create_process_impl( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2279 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
2280 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
2281 LPPROCESS_INFORMATION info
)
2285 char *unixdir
= NULL
;
2286 WCHAR name
[MAX_PATH
];
2287 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
2288 struct binary_info binary_info
;
2290 /* Process the AppName and/or CmdLine to get module name and path */
2292 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
2294 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
)/sizeof(WCHAR
),
2295 &hFile
, &binary_info
)))
2297 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
2299 /* Warn if unsupported features are used */
2301 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
2302 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
2303 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
2304 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
2305 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name
), flags
);
2309 if (!(unixdir
= wine_get_unix_file_name( cur_dir
)))
2311 SetLastError(ERROR_DIRECTORY
);
2317 WCHAR buf
[MAX_PATH
];
2318 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
2321 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
2326 while (*e
) e
+= strlen(e
) + 1;
2327 e
++; /* final null */
2328 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, e
- (char*)env
, NULL
, 0 );
2329 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
2330 MultiByteToWideChar( CP_ACP
, 0, env
, e
- (char*)env
, envW
, lenW
);
2331 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2334 info
->hThread
= info
->hProcess
= 0;
2335 info
->dwProcessId
= info
->dwThreadId
= 0;
2337 if (binary_info
.flags
& BINARY_FLAG_DLL
)
2339 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
2340 SetLastError( ERROR_BAD_EXE_FORMAT
);
2342 else switch (binary_info
.type
)
2345 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2346 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32,
2347 binary_info
.res_start
, binary_info
.res_end
, binary_info
.arch
);
2348 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2349 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2354 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2355 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2356 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2358 case BINARY_UNIX_LIB
:
2359 TRACE( "starting %s as %d-bit Winelib app\n",
2360 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32 );
2361 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2362 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2364 case BINARY_UNKNOWN
:
2365 /* check for .com or .bat extension */
2366 if ((p
= strrchrW( name
, '.' )))
2368 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
2370 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
2371 binary_info
.type
= BINARY_DOS
;
2372 binary_info
.arch
= IMAGE_FILE_MACHINE_I386
;
2373 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2374 inherit
, flags
, startup_info
, info
, unixdir
,
2375 &binary_info
, FALSE
);
2378 if (!strcmpiW( p
, batW
) || !strcmpiW( p
, cmdW
) )
2380 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
2381 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2382 inherit
, flags
, startup_info
, info
);
2387 case BINARY_UNIX_EXE
:
2389 /* unknown file, try as unix executable */
2392 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
2394 if ((unix_name
= wine_get_unix_file_name( name
)))
2396 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
, flags
, startup_info
) != -1);
2397 HeapFree( GetProcessHeap(), 0, unix_name
);
2402 if (hFile
) CloseHandle( hFile
);
2405 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
2406 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
2407 HeapFree( GetProcessHeap(), 0, unixdir
);
2409 TRACE( "started process pid %04x tid %04x\n", info
->dwProcessId
, info
->dwThreadId
);
2414 /**********************************************************************
2415 * CreateProcessA (KERNEL32.@)
2417 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2418 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
2419 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
2420 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
2423 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
2424 UNICODE_STRING desktopW
, titleW
;
2427 desktopW
.Buffer
= NULL
;
2428 titleW
.Buffer
= NULL
;
2429 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
2430 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
2431 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
2433 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
2434 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
2436 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
2437 infoW
.lpDesktop
= desktopW
.Buffer
;
2438 infoW
.lpTitle
= titleW
.Buffer
;
2440 if (startup_info
->lpReserved
)
2441 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2442 debugstr_a(startup_info
->lpReserved
));
2444 ret
= create_process_impl( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
2445 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
2447 HeapFree( GetProcessHeap(), 0, app_nameW
);
2448 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
2449 HeapFree( GetProcessHeap(), 0, cur_dirW
);
2450 RtlFreeUnicodeString( &desktopW
);
2451 RtlFreeUnicodeString( &titleW
);
2456 /**********************************************************************
2457 * CreateProcessW (KERNEL32.@)
2459 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2460 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
2461 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
2462 LPPROCESS_INFORMATION info
)
2464 return create_process_impl( app_name
, cmd_line
, process_attr
, thread_attr
,
2465 inherit
, flags
, env
, cur_dir
, startup_info
, info
);
2469 /**********************************************************************
2472 static void exec_process( LPCWSTR name
)
2476 STARTUPINFOW startup_info
;
2477 PROCESS_INFORMATION info
;
2478 struct binary_info binary_info
;
2480 hFile
= open_exe_file( name
, &binary_info
);
2481 if (!hFile
|| hFile
== INVALID_HANDLE_VALUE
) return;
2483 memset( &startup_info
, 0, sizeof(startup_info
) );
2484 startup_info
.cb
= sizeof(startup_info
);
2486 /* Determine executable type */
2488 if (binary_info
.flags
& BINARY_FLAG_DLL
) return;
2489 switch (binary_info
.type
)
2492 TRACE( "starting %s as Win%d binary (%p-%p, arch %04x)\n",
2493 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32,
2494 binary_info
.res_start
, binary_info
.res_end
, binary_info
.arch
);
2495 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2496 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2498 case BINARY_UNIX_LIB
:
2499 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
2500 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2501 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2503 case BINARY_UNKNOWN
:
2504 /* check for .com or .pif extension */
2505 if (!(p
= strrchrW( name
, '.' ))) break;
2506 if (strcmpiW( p
, comW
) && strcmpiW( p
, pifW
)) break;
2507 binary_info
.type
= BINARY_DOS
;
2508 binary_info
.arch
= IMAGE_FILE_MACHINE_I386
;
2513 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2514 create_vdm_process( name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2515 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2520 CloseHandle( hFile
);
2524 /***********************************************************************
2527 * Wrapper to call WaitForInputIdle USER function
2529 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2531 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2533 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2536 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2537 if (ptr
) return ptr( process
, timeout
);
2543 /***********************************************************************
2544 * WinExec (KERNEL32.@)
2546 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2548 PROCESS_INFORMATION info
;
2549 STARTUPINFOA startup
;
2553 memset( &startup
, 0, sizeof(startup
) );
2554 startup
.cb
= sizeof(startup
);
2555 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2556 startup
.wShowWindow
= nCmdShow
;
2558 /* cmdline needs to be writable for CreateProcess */
2559 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2560 strcpy( cmdline
, lpCmdLine
);
2562 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2563 0, NULL
, NULL
, &startup
, &info
))
2565 /* Give 30 seconds to the app to come up */
2566 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2567 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2569 /* Close off the handles */
2570 CloseHandle( info
.hThread
);
2571 CloseHandle( info
.hProcess
);
2573 else if ((ret
= GetLastError()) >= 32)
2575 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2578 HeapFree( GetProcessHeap(), 0, cmdline
);
2583 /**********************************************************************
2584 * LoadModule (KERNEL32.@)
2586 DWORD WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2588 LOADPARMS32
*params
= paramBlock
;
2589 PROCESS_INFORMATION info
;
2590 STARTUPINFOA startup
;
2593 char filename
[MAX_PATH
];
2596 if (!name
) return ERROR_FILE_NOT_FOUND
;
2598 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2599 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2600 return GetLastError();
2602 len
= (BYTE
)params
->lpCmdLine
[0];
2603 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2604 return ERROR_NOT_ENOUGH_MEMORY
;
2606 strcpy( cmdline
, filename
);
2607 p
= cmdline
+ strlen(cmdline
);
2609 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2612 memset( &startup
, 0, sizeof(startup
) );
2613 startup
.cb
= sizeof(startup
);
2614 if (params
->lpCmdShow
)
2616 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2617 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2620 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2621 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2623 /* Give 30 seconds to the app to come up */
2624 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2625 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2627 /* Close off the handles */
2628 CloseHandle( info
.hThread
);
2629 CloseHandle( info
.hProcess
);
2631 else if ((ret
= GetLastError()) >= 32)
2633 FIXME("Strange error set by CreateProcess: %u\n", ret
);
2637 HeapFree( GetProcessHeap(), 0, cmdline
);
2642 /******************************************************************************
2643 * TerminateProcess (KERNEL32.@)
2645 * Terminates a process.
2648 * handle [I] Process to terminate.
2649 * exit_code [I] Exit code.
2653 * Failure: FALSE, check GetLastError().
2655 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2661 SetLastError( ERROR_INVALID_HANDLE
);
2665 status
= NtTerminateProcess( handle
, exit_code
);
2666 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2670 /***********************************************************************
2671 * ExitProcess (KERNEL32.@)
2673 * Exits the current process.
2676 * status [I] Status code to exit with.
2682 __ASM_STDCALL_FUNC( ExitProcess
, 4, /* Shrinker depend on this particular ExitProcess implementation */
2684 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2685 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2686 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2688 "call " __ASM_NAME("RtlExitUserProcess") __ASM_STDCALL(4) "\n\t"
2693 void WINAPI
ExitProcess( DWORD status
)
2695 RtlExitUserProcess( status
);
2700 /***********************************************************************
2701 * GetExitCodeProcess [KERNEL32.@]
2703 * Gets termination status of specified process.
2706 * hProcess [in] Handle to the process.
2707 * lpExitCode [out] Address to receive termination status.
2713 BOOL WINAPI
GetExitCodeProcess( HANDLE hProcess
, LPDWORD lpExitCode
)
2716 PROCESS_BASIC_INFORMATION pbi
;
2718 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2720 if (status
== STATUS_SUCCESS
)
2722 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2725 SetLastError( RtlNtStatusToDosError(status
) );
2730 /***********************************************************************
2731 * SetErrorMode (KERNEL32.@)
2733 UINT WINAPI
SetErrorMode( UINT mode
)
2737 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode
,
2738 &old
, sizeof(old
), NULL
);
2739 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode
,
2740 &mode
, sizeof(mode
) );
2744 /***********************************************************************
2745 * GetErrorMode (KERNEL32.@)
2747 UINT WINAPI
GetErrorMode( void )
2751 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode
,
2752 &mode
, sizeof(mode
), NULL
);
2756 /**********************************************************************
2757 * TlsAlloc [KERNEL32.@]
2759 * Allocates a thread local storage index.
2762 * Success: TLS index.
2763 * Failure: 0xFFFFFFFF
2765 DWORD WINAPI
TlsAlloc( void )
2768 PEB
* const peb
= NtCurrentTeb()->Peb
;
2770 RtlAcquirePebLock();
2771 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 1 );
2772 if (index
!= ~0U) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2775 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2778 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2779 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2780 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2782 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2784 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2788 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2789 index
+= TLS_MINIMUM_AVAILABLE
;
2792 else SetLastError( ERROR_NO_MORE_ITEMS
);
2794 RtlReleasePebLock();
2799 /**********************************************************************
2800 * TlsFree [KERNEL32.@]
2802 * Releases a thread local storage index, making it available for reuse.
2805 * index [in] TLS index to free.
2811 BOOL WINAPI
TlsFree( DWORD index
)
2815 RtlAcquirePebLock();
2816 if (index
>= TLS_MINIMUM_AVAILABLE
)
2818 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2819 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2823 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2824 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2826 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2827 else SetLastError( ERROR_INVALID_PARAMETER
);
2828 RtlReleasePebLock();
2833 /**********************************************************************
2834 * TlsGetValue [KERNEL32.@]
2836 * Gets value in a thread's TLS slot.
2839 * index [in] TLS index to retrieve value for.
2842 * Success: Value stored in calling thread's TLS slot for index.
2843 * Failure: 0 and GetLastError() returns NO_ERROR.
2845 LPVOID WINAPI
TlsGetValue( DWORD index
)
2849 if (index
< TLS_MINIMUM_AVAILABLE
)
2851 ret
= NtCurrentTeb()->TlsSlots
[index
];
2855 index
-= TLS_MINIMUM_AVAILABLE
;
2856 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2858 SetLastError( ERROR_INVALID_PARAMETER
);
2861 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2862 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2864 SetLastError( ERROR_SUCCESS
);
2869 /**********************************************************************
2870 * TlsSetValue [KERNEL32.@]
2872 * Stores a value in the thread's TLS slot.
2875 * index [in] TLS index to set value for.
2876 * value [in] Value to be stored.
2882 BOOL WINAPI
TlsSetValue( DWORD index
, LPVOID value
)
2884 if (index
< TLS_MINIMUM_AVAILABLE
)
2886 NtCurrentTeb()->TlsSlots
[index
] = value
;
2890 index
-= TLS_MINIMUM_AVAILABLE
;
2891 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2893 SetLastError( ERROR_INVALID_PARAMETER
);
2896 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2897 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2898 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2900 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2903 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2909 /***********************************************************************
2910 * GetProcessFlags (KERNEL32.@)
2912 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2914 IMAGE_NT_HEADERS
*nt
;
2917 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2919 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2921 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2922 flags
|= PDB32_CONSOLE_PROC
;
2924 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2925 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2930 /*********************************************************************
2931 * OpenProcess (KERNEL32.@)
2933 * Opens a handle to a process.
2936 * access [I] Desired access rights assigned to the returned handle.
2937 * inherit [I] Determines whether or not child processes will inherit the handle.
2938 * id [I] Process identifier of the process to get a handle to.
2941 * Success: Valid handle to the specified process.
2942 * Failure: NULL, check GetLastError().
2944 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2948 OBJECT_ATTRIBUTES attr
;
2951 cid
.UniqueProcess
= ULongToHandle(id
);
2952 cid
.UniqueThread
= 0; /* FIXME ? */
2954 attr
.Length
= sizeof(OBJECT_ATTRIBUTES
);
2955 attr
.RootDirectory
= NULL
;
2956 attr
.Attributes
= inherit
? OBJ_INHERIT
: 0;
2957 attr
.SecurityDescriptor
= NULL
;
2958 attr
.SecurityQualityOfService
= NULL
;
2959 attr
.ObjectName
= NULL
;
2961 if (GetVersion() & 0x80000000) access
= PROCESS_ALL_ACCESS
;
2963 status
= NtOpenProcess(&handle
, access
, &attr
, &cid
);
2964 if (status
!= STATUS_SUCCESS
)
2966 SetLastError( RtlNtStatusToDosError(status
) );
2973 /*********************************************************************
2974 * GetProcessId (KERNEL32.@)
2976 * Gets the a unique identifier of a process.
2979 * hProcess [I] Handle to the process.
2983 * Failure: FALSE, check GetLastError().
2987 * The identifier is unique only on the machine and only until the process
2988 * exits (including system shutdown).
2990 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2993 PROCESS_BASIC_INFORMATION pbi
;
2995 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2997 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2998 SetLastError( RtlNtStatusToDosError(status
) );
3003 /*********************************************************************
3004 * CloseHandle (KERNEL32.@)
3009 * handle [I] Handle to close.
3013 * Failure: FALSE, check GetLastError().
3015 BOOL WINAPI
CloseHandle( HANDLE handle
)
3019 /* stdio handles need special treatment */
3020 if (handle
== (HANDLE
)STD_INPUT_HANDLE
)
3021 handle
= InterlockedExchangePointer( &NtCurrentTeb()->Peb
->ProcessParameters
->hStdInput
, 0 );
3022 else if (handle
== (HANDLE
)STD_OUTPUT_HANDLE
)
3023 handle
= InterlockedExchangePointer( &NtCurrentTeb()->Peb
->ProcessParameters
->hStdOutput
, 0 );
3024 else if (handle
== (HANDLE
)STD_ERROR_HANDLE
)
3025 handle
= InterlockedExchangePointer( &NtCurrentTeb()->Peb
->ProcessParameters
->hStdError
, 0 );
3027 if (is_console_handle(handle
))
3028 return CloseConsoleHandle(handle
);
3030 status
= NtClose( handle
);
3031 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3036 /*********************************************************************
3037 * GetHandleInformation (KERNEL32.@)
3039 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
3041 OBJECT_DATA_INFORMATION info
;
3042 NTSTATUS status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
);
3044 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3048 if (info
.InheritHandle
) *flags
|= HANDLE_FLAG_INHERIT
;
3049 if (info
.ProtectFromClose
) *flags
|= HANDLE_FLAG_PROTECT_FROM_CLOSE
;
3055 /*********************************************************************
3056 * SetHandleInformation (KERNEL32.@)
3058 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
3060 OBJECT_DATA_INFORMATION info
;
3063 /* if not setting both fields, retrieve current value first */
3064 if ((mask
& (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
)) !=
3065 (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
))
3067 if ((status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
)))
3069 SetLastError( RtlNtStatusToDosError(status
) );
3073 if (mask
& HANDLE_FLAG_INHERIT
)
3074 info
.InheritHandle
= (flags
& HANDLE_FLAG_INHERIT
) != 0;
3075 if (mask
& HANDLE_FLAG_PROTECT_FROM_CLOSE
)
3076 info
.ProtectFromClose
= (flags
& HANDLE_FLAG_PROTECT_FROM_CLOSE
) != 0;
3078 status
= NtSetInformationObject( handle
, ObjectDataInformation
, &info
, sizeof(info
) );
3079 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3084 /*********************************************************************
3085 * DuplicateHandle (KERNEL32.@)
3087 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
3088 HANDLE dest_process
, HANDLE
*dest
,
3089 DWORD access
, BOOL inherit
, DWORD options
)
3093 if (is_console_handle(source
))
3095 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3096 if (source_process
!= dest_process
||
3097 source_process
!= GetCurrentProcess())
3099 SetLastError(ERROR_INVALID_PARAMETER
);
3102 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
3103 return (*dest
!= INVALID_HANDLE_VALUE
);
3105 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
3106 access
, inherit
? OBJ_INHERIT
: 0, options
);
3107 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3112 /***********************************************************************
3113 * ConvertToGlobalHandle (KERNEL32.@)
3115 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
3117 HANDLE ret
= INVALID_HANDLE_VALUE
;
3118 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
3119 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
3124 /***********************************************************************
3125 * SetHandleContext (KERNEL32.@)
3127 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
3129 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3130 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
3131 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3136 /***********************************************************************
3137 * GetHandleContext (KERNEL32.@)
3139 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
3141 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3142 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
3143 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3148 /***********************************************************************
3149 * CreateSocketHandle (KERNEL32.@)
3151 HANDLE WINAPI
CreateSocketHandle(void)
3153 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3154 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3155 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3156 return INVALID_HANDLE_VALUE
;
3160 /***********************************************************************
3161 * SetPriorityClass (KERNEL32.@)
3163 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
3166 PROCESS_PRIORITY_CLASS ppc
;
3168 ppc
.Foreground
= FALSE
;
3169 switch (priorityclass
)
3171 case IDLE_PRIORITY_CLASS
:
3172 ppc
.PriorityClass
= PROCESS_PRIOCLASS_IDLE
; break;
3173 case BELOW_NORMAL_PRIORITY_CLASS
:
3174 ppc
.PriorityClass
= PROCESS_PRIOCLASS_BELOW_NORMAL
; break;
3175 case NORMAL_PRIORITY_CLASS
:
3176 ppc
.PriorityClass
= PROCESS_PRIOCLASS_NORMAL
; break;
3177 case ABOVE_NORMAL_PRIORITY_CLASS
:
3178 ppc
.PriorityClass
= PROCESS_PRIOCLASS_ABOVE_NORMAL
; break;
3179 case HIGH_PRIORITY_CLASS
:
3180 ppc
.PriorityClass
= PROCESS_PRIOCLASS_HIGH
; break;
3181 case REALTIME_PRIORITY_CLASS
:
3182 ppc
.PriorityClass
= PROCESS_PRIOCLASS_REALTIME
; break;
3184 SetLastError(ERROR_INVALID_PARAMETER
);
3188 status
= NtSetInformationProcess(hprocess
, ProcessPriorityClass
,
3191 if (status
!= STATUS_SUCCESS
)
3193 SetLastError( RtlNtStatusToDosError(status
) );
3200 /***********************************************************************
3201 * GetPriorityClass (KERNEL32.@)
3203 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
3206 PROCESS_BASIC_INFORMATION pbi
;
3208 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
3210 if (status
!= STATUS_SUCCESS
)
3212 SetLastError( RtlNtStatusToDosError(status
) );
3215 switch (pbi
.BasePriority
)
3217 case PROCESS_PRIOCLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
3218 case PROCESS_PRIOCLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
3219 case PROCESS_PRIOCLASS_NORMAL
: return NORMAL_PRIORITY_CLASS
;
3220 case PROCESS_PRIOCLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
3221 case PROCESS_PRIOCLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
3222 case PROCESS_PRIOCLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
3224 SetLastError( ERROR_INVALID_PARAMETER
);
3229 /***********************************************************************
3230 * SetProcessAffinityMask (KERNEL32.@)
3232 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
3236 status
= NtSetInformationProcess(hProcess
, ProcessAffinityMask
,
3237 &affmask
, sizeof(DWORD_PTR
));
3240 SetLastError( RtlNtStatusToDosError(status
) );
3247 /**********************************************************************
3248 * GetProcessAffinityMask (KERNEL32.@)
3250 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
, PDWORD_PTR process_mask
, PDWORD_PTR system_mask
)
3252 NTSTATUS status
= STATUS_SUCCESS
;
3254 if (system_mask
) *system_mask
= (1 << NtCurrentTeb()->Peb
->NumberOfProcessors
) - 1;
3257 if ((status
= NtQueryInformationProcess( hProcess
, ProcessAffinityMask
,
3258 process_mask
, sizeof(*process_mask
), NULL
)))
3259 SetLastError( RtlNtStatusToDosError(status
) );
3265 /***********************************************************************
3266 * GetProcessVersion (KERNEL32.@)
3268 DWORD WINAPI
GetProcessVersion( DWORD pid
)
3272 PROCESS_BASIC_INFORMATION pbi
;
3275 IMAGE_DOS_HEADER dos
;
3276 IMAGE_NT_HEADERS nt
;
3279 if (!pid
|| pid
== GetCurrentProcessId())
3281 IMAGE_NT_HEADERS
*pnt
;
3283 if ((pnt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
3284 return ((pnt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
3285 pnt
->OptionalHeader
.MinorSubsystemVersion
);
3289 process
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
3290 if (!process
) return 0;
3292 status
= NtQueryInformationProcess(process
, ProcessBasicInformation
, &pbi
, sizeof(pbi
), NULL
);
3293 if (status
) goto err
;
3295 status
= NtReadVirtualMemory(process
, pbi
.PebBaseAddress
, &peb
, sizeof(peb
), &count
);
3296 if (status
|| count
!= sizeof(peb
)) goto err
;
3298 memset(&dos
, 0, sizeof(dos
));
3299 status
= NtReadVirtualMemory(process
, peb
.ImageBaseAddress
, &dos
, sizeof(dos
), &count
);
3300 if (status
|| count
!= sizeof(dos
)) goto err
;
3301 if (dos
.e_magic
!= IMAGE_DOS_SIGNATURE
) goto err
;
3303 memset(&nt
, 0, sizeof(nt
));
3304 status
= NtReadVirtualMemory(process
, (char *)peb
.ImageBaseAddress
+ dos
.e_lfanew
, &nt
, sizeof(nt
), &count
);
3305 if (status
|| count
!= sizeof(nt
)) goto err
;
3306 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) goto err
;
3308 ver
= MAKELONG(nt
.OptionalHeader
.MinorSubsystemVersion
, nt
.OptionalHeader
.MajorSubsystemVersion
);
3311 CloseHandle(process
);
3313 if (status
!= STATUS_SUCCESS
)
3314 SetLastError(RtlNtStatusToDosError(status
));
3320 /***********************************************************************
3321 * SetProcessWorkingSetSize [KERNEL32.@]
3322 * Sets the min/max working set sizes for a specified process.
3325 * hProcess [I] Handle to the process of interest
3326 * minset [I] Specifies minimum working set size
3327 * maxset [I] Specifies maximum working set size
3333 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
3336 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
3337 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
3338 /* Trim the working set to zero */
3339 /* Swap the process out of physical RAM */
3344 /***********************************************************************
3345 * K32EmptyWorkingSet (KERNEL32.@)
3347 BOOL WINAPI
K32EmptyWorkingSet(HANDLE hProcess
)
3349 return SetProcessWorkingSetSize(hProcess
, (SIZE_T
)-1, (SIZE_T
)-1);
3352 /***********************************************************************
3353 * GetProcessWorkingSetSize (KERNEL32.@)
3355 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
3358 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
3359 /* 32 MB working set size */
3360 if (minset
) *minset
= 32*1024*1024;
3361 if (maxset
) *maxset
= 32*1024*1024;
3366 /***********************************************************************
3367 * SetProcessShutdownParameters (KERNEL32.@)
3369 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
3371 FIXME("(%08x, %08x): partial stub.\n", level
, flags
);
3372 shutdown_flags
= flags
;
3373 shutdown_priority
= level
;
3378 /***********************************************************************
3379 * GetProcessShutdownParameters (KERNEL32.@)
3382 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
3384 *lpdwLevel
= shutdown_priority
;
3385 *lpdwFlags
= shutdown_flags
;
3390 /***********************************************************************
3391 * GetProcessPriorityBoost (KERNEL32.@)
3393 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
3395 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
3397 /* Report that no boost is present.. */
3398 *pDisablePriorityBoost
= FALSE
;
3403 /***********************************************************************
3404 * SetProcessPriorityBoost (KERNEL32.@)
3406 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
3408 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
3409 /* Say we can do it. I doubt the program will notice that we don't. */
3414 /***********************************************************************
3415 * ReadProcessMemory (KERNEL32.@)
3417 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
3418 SIZE_T
*bytes_read
)
3420 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
3421 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3426 /***********************************************************************
3427 * WriteProcessMemory (KERNEL32.@)
3429 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
3430 SIZE_T
*bytes_written
)
3432 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
3433 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3438 /****************************************************************************
3439 * FlushInstructionCache (KERNEL32.@)
3441 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
3444 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
3445 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3450 /******************************************************************
3451 * GetProcessIoCounters (KERNEL32.@)
3453 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
3457 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
3458 ioc
, sizeof(*ioc
), NULL
);
3459 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3463 /******************************************************************
3464 * GetProcessHandleCount (KERNEL32.@)
3466 BOOL WINAPI
GetProcessHandleCount(HANDLE hProcess
, DWORD
*cnt
)
3470 status
= NtQueryInformationProcess(hProcess
, ProcessHandleCount
,
3471 cnt
, sizeof(*cnt
), NULL
);
3472 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3476 /******************************************************************
3477 * QueryFullProcessImageNameA (KERNEL32.@)
3479 BOOL WINAPI
QueryFullProcessImageNameA(HANDLE hProcess
, DWORD dwFlags
, LPSTR lpExeName
, PDWORD pdwSize
)
3482 DWORD pdwSizeW
= *pdwSize
;
3483 LPWSTR lpExeNameW
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, *pdwSize
* sizeof(WCHAR
));
3485 retval
= QueryFullProcessImageNameW(hProcess
, dwFlags
, lpExeNameW
, &pdwSizeW
);
3488 retval
= (0 != WideCharToMultiByte(CP_ACP
, 0, lpExeNameW
, -1,
3489 lpExeName
, *pdwSize
, NULL
, NULL
));
3491 *pdwSize
= strlen(lpExeName
);
3493 HeapFree(GetProcessHeap(), 0, lpExeNameW
);
3497 /******************************************************************
3498 * QueryFullProcessImageNameW (KERNEL32.@)
3500 BOOL WINAPI
QueryFullProcessImageNameW(HANDLE hProcess
, DWORD dwFlags
, LPWSTR lpExeName
, PDWORD pdwSize
)
3502 BYTE buffer
[sizeof(UNICODE_STRING
) + MAX_PATH
*sizeof(WCHAR
)]; /* this buffer should be enough */
3503 UNICODE_STRING
*dynamic_buffer
= NULL
;
3504 UNICODE_STRING
*result
= NULL
;
3508 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3509 * is a DOS path and we depend on this. */
3510 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, buffer
,
3511 sizeof(buffer
) - sizeof(WCHAR
), &needed
);
3512 if (status
== STATUS_INFO_LENGTH_MISMATCH
)
3514 dynamic_buffer
= HeapAlloc(GetProcessHeap(), 0, needed
+ sizeof(WCHAR
));
3515 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, (LPBYTE
)dynamic_buffer
, needed
, &needed
);
3516 result
= dynamic_buffer
;
3519 result
= (PUNICODE_STRING
)buffer
;
3521 if (status
) goto cleanup
;
3523 if (dwFlags
& PROCESS_NAME_NATIVE
)
3527 DWORD ntlen
, devlen
;
3529 if (result
->Buffer
[1] != ':' || result
->Buffer
[0] < 'A' || result
->Buffer
[0] > 'Z')
3531 /* We cannot convert it to an NT device path so fail */
3532 status
= STATUS_NO_SUCH_DEVICE
;
3536 /* Find this drive's NT device path */
3537 drive
[0] = result
->Buffer
[0];
3540 if (!QueryDosDeviceW(drive
, device
, sizeof(device
)/sizeof(*device
)))
3542 status
= STATUS_NO_SUCH_DEVICE
;
3546 devlen
= lstrlenW(device
);
3547 ntlen
= devlen
+ (result
->Length
/sizeof(WCHAR
) - 2);
3548 if (ntlen
+ 1 > *pdwSize
)
3550 SetLastError(ERROR_INSUFFICIENT_BUFFER
);
3555 memcpy(lpExeName
, device
, devlen
* sizeof(*device
));
3556 memcpy(lpExeName
+ devlen
, result
->Buffer
+ 2, result
->Length
- 2 * sizeof(WCHAR
));
3557 lpExeName
[*pdwSize
] = 0;
3558 TRACE("NT path: %s\n", debugstr_w(lpExeName
));
3562 if (result
->Length
/sizeof(WCHAR
) + 1 > *pdwSize
)
3564 status
= STATUS_BUFFER_TOO_SMALL
;
3568 *pdwSize
= result
->Length
/sizeof(WCHAR
);
3569 memcpy( lpExeName
, result
->Buffer
, result
->Length
);
3570 lpExeName
[*pdwSize
] = 0;
3574 HeapFree(GetProcessHeap(), 0, dynamic_buffer
);
3575 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3579 /***********************************************************************
3580 * K32GetProcessImageFileNameA (KERNEL32.@)
3582 DWORD WINAPI
K32GetProcessImageFileNameA( HANDLE process
, LPSTR file
, DWORD size
)
3584 return QueryFullProcessImageNameA(process
, PROCESS_NAME_NATIVE
, file
, &size
) ? size
: 0;
3587 /***********************************************************************
3588 * K32GetProcessImageFileNameW (KERNEL32.@)
3590 DWORD WINAPI
K32GetProcessImageFileNameW( HANDLE process
, LPWSTR file
, DWORD size
)
3592 return QueryFullProcessImageNameW(process
, PROCESS_NAME_NATIVE
, file
, &size
) ? size
: 0;
3595 /***********************************************************************
3596 * K32EnumProcesses (KERNEL32.@)
3598 BOOL WINAPI
K32EnumProcesses(DWORD
*lpdwProcessIDs
, DWORD cb
, DWORD
*lpcbUsed
)
3600 SYSTEM_PROCESS_INFORMATION
*spi
;
3601 ULONG size
= 0x4000;
3607 HeapFree(GetProcessHeap(), 0, buf
);
3608 buf
= HeapAlloc(GetProcessHeap(), 0, size
);
3612 status
= NtQuerySystemInformation(SystemProcessInformation
, buf
, size
, NULL
);
3613 } while(status
== STATUS_INFO_LENGTH_MISMATCH
);
3615 if (status
!= STATUS_SUCCESS
)
3617 HeapFree(GetProcessHeap(), 0, buf
);
3618 SetLastError(RtlNtStatusToDosError(status
));
3624 for (*lpcbUsed
= 0; cb
>= sizeof(DWORD
); cb
-= sizeof(DWORD
))
3626 *lpdwProcessIDs
++ = HandleToUlong(spi
->UniqueProcessId
);
3627 *lpcbUsed
+= sizeof(DWORD
);
3629 if (spi
->NextEntryOffset
== 0)
3632 spi
= (SYSTEM_PROCESS_INFORMATION
*)(((PCHAR
)spi
) + spi
->NextEntryOffset
);
3635 HeapFree(GetProcessHeap(), 0, buf
);
3639 /***********************************************************************
3640 * K32QueryWorkingSet (KERNEL32.@)
3642 BOOL WINAPI
K32QueryWorkingSet( HANDLE process
, LPVOID buffer
, DWORD size
)
3646 TRACE( "(%p, %p, %d)\n", process
, buffer
, size
);
3648 status
= NtQueryVirtualMemory( process
, NULL
, MemoryWorkingSetList
, buffer
, size
, NULL
);
3652 SetLastError( RtlNtStatusToDosError( status
) );
3658 /***********************************************************************
3659 * K32QueryWorkingSetEx (KERNEL32.@)
3661 BOOL WINAPI
K32QueryWorkingSetEx( HANDLE process
, LPVOID buffer
, DWORD size
)
3665 TRACE( "(%p, %p, %d)\n", process
, buffer
, size
);
3667 status
= NtQueryVirtualMemory( process
, NULL
, MemoryWorkingSetList
, buffer
, size
, NULL
);
3671 SetLastError( RtlNtStatusToDosError( status
) );
3677 /***********************************************************************
3678 * K32GetProcessMemoryInfo (KERNEL32.@)
3680 * Retrieve memory usage information for a given process
3683 BOOL WINAPI
K32GetProcessMemoryInfo(HANDLE process
,
3684 PPROCESS_MEMORY_COUNTERS pmc
, DWORD cb
)
3689 if (cb
< sizeof(PROCESS_MEMORY_COUNTERS
))
3691 SetLastError(ERROR_INSUFFICIENT_BUFFER
);
3695 status
= NtQueryInformationProcess(process
, ProcessVmCounters
,
3696 &vmc
, sizeof(vmc
), NULL
);
3700 SetLastError(RtlNtStatusToDosError(status
));
3704 pmc
->cb
= sizeof(PROCESS_MEMORY_COUNTERS
);
3705 pmc
->PageFaultCount
= vmc
.PageFaultCount
;
3706 pmc
->PeakWorkingSetSize
= vmc
.PeakWorkingSetSize
;
3707 pmc
->WorkingSetSize
= vmc
.WorkingSetSize
;
3708 pmc
->QuotaPeakPagedPoolUsage
= vmc
.QuotaPeakPagedPoolUsage
;
3709 pmc
->QuotaPagedPoolUsage
= vmc
.QuotaPagedPoolUsage
;
3710 pmc
->QuotaPeakNonPagedPoolUsage
= vmc
.QuotaPeakNonPagedPoolUsage
;
3711 pmc
->QuotaNonPagedPoolUsage
= vmc
.QuotaNonPagedPoolUsage
;
3712 pmc
->PagefileUsage
= vmc
.PagefileUsage
;
3713 pmc
->PeakPagefileUsage
= vmc
.PeakPagefileUsage
;
3718 /***********************************************************************
3719 * ProcessIdToSessionId (KERNEL32.@)
3720 * This function is available on Terminal Server 4SP4 and Windows 2000
3722 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
3724 /* According to MSDN, if the calling process is not in a terminal
3725 * services environment, then the sessionid returned is zero.
3732 /***********************************************************************
3733 * RegisterServiceProcess (KERNEL32.@)
3735 * A service process calls this function to ensure that it continues to run
3736 * even after a user logged off.
3738 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
3740 /* I don't think that Wine needs to do anything in this function */
3741 return 1; /* success */
3745 /**********************************************************************
3746 * IsWow64Process (KERNEL32.@)
3748 BOOL WINAPI
IsWow64Process(HANDLE hProcess
, PBOOL Wow64Process
)
3753 status
= NtQueryInformationProcess( hProcess
, ProcessWow64Information
, &pbi
, sizeof(pbi
), NULL
);
3755 if (status
!= STATUS_SUCCESS
)
3757 SetLastError( RtlNtStatusToDosError( status
) );
3760 *Wow64Process
= (pbi
!= 0);
3765 /***********************************************************************
3766 * GetCurrentProcess (KERNEL32.@)
3768 * Get a handle to the current process.
3774 * A handle representing the current process.
3776 #undef GetCurrentProcess
3777 HANDLE WINAPI
GetCurrentProcess(void)
3779 return (HANDLE
)~(ULONG_PTR
)0;
3782 /***********************************************************************
3783 * GetLogicalProcessorInformation (KERNEL32.@)
3785 BOOL WINAPI
GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer
, PDWORD pBufLen
)
3789 TRACE("(%p,%p)\n", buffer
, pBufLen
);
3793 SetLastError(ERROR_INVALID_PARAMETER
);
3797 status
= NtQuerySystemInformation( SystemLogicalProcessorInformation
, buffer
, *pBufLen
, pBufLen
);
3799 if (status
== STATUS_INFO_LENGTH_MISMATCH
)
3801 SetLastError( ERROR_INSUFFICIENT_BUFFER
);
3804 if (status
!= STATUS_SUCCESS
)
3806 SetLastError( RtlNtStatusToDosError( status
) );
3812 /***********************************************************************
3813 * GetLogicalProcessorInformationEx (KERNEL32.@)
3815 BOOL WINAPI
GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship
, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer
, PDWORD pBufLen
)
3817 FIXME("(%u,%p,%p): stub\n", relationship
, buffer
, pBufLen
);
3818 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3822 /***********************************************************************
3823 * CmdBatNotification (KERNEL32.@)
3825 * Notifies the system that a batch file has started or finished.
3828 * bBatchRunning [I] TRUE if a batch file has started or
3829 * FALSE if a batch file has finished executing.
3834 BOOL WINAPI
CmdBatNotification( BOOL bBatchRunning
)
3836 FIXME("%d\n", bBatchRunning
);
3841 /***********************************************************************
3842 * RegisterApplicationRestart (KERNEL32.@)
3844 HRESULT WINAPI
RegisterApplicationRestart(PCWSTR pwzCommandLine
, DWORD dwFlags
)
3846 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine
), dwFlags
);
3851 /**********************************************************************
3852 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3854 DWORD WINAPI
WTSGetActiveConsoleSessionId(void)
3857 if (!once
++) FIXME("stub\n");
3861 /**********************************************************************
3862 * GetSystemDEPPolicy (KERNEL32.@)
3864 DEP_SYSTEM_POLICY_TYPE WINAPI
GetSystemDEPPolicy(void)
3870 /**********************************************************************
3871 * SetProcessDEPPolicy (KERNEL32.@)
3873 BOOL WINAPI
SetProcessDEPPolicy(DWORD newDEP
)
3875 FIXME("(%d): stub\n", newDEP
);
3876 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3880 /**********************************************************************
3881 * ApplicationRecoveryFinished (KERNEL32.@)
3883 VOID WINAPI
ApplicationRecoveryFinished(BOOL success
)
3886 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3889 /**********************************************************************
3890 * ApplicationRecoveryInProgress (KERNEL32.@)
3892 HRESULT WINAPI
ApplicationRecoveryInProgress(PBOOL canceled
)
3894 FIXME(":%p stub\n", canceled
);
3895 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3899 /**********************************************************************
3900 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3902 HRESULT WINAPI
RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback
, PVOID param
, DWORD pingint
, DWORD flags
)
3904 FIXME("%p, %p, %d, %d: stub\n", callback
, param
, pingint
, flags
);
3905 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3909 /**********************************************************************
3910 * GetNumaHighestNodeNumber (KERNEL32.@)
3912 BOOL WINAPI
GetNumaHighestNodeNumber(PULONG highestnode
)
3915 FIXME("(%p): semi-stub\n", highestnode
);
3919 /**********************************************************************
3920 * GetNumaNodeProcessorMask (KERNEL32.@)
3922 BOOL WINAPI
GetNumaNodeProcessorMask(UCHAR node
, PULONGLONG mask
)
3924 FIXME("(%c %p): stub\n", node
, mask
);
3925 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3929 /**********************************************************************
3930 * GetNumaAvailableMemoryNode (KERNEL32.@)
3932 BOOL WINAPI
GetNumaAvailableMemoryNode(UCHAR node
, PULONGLONG available_bytes
)
3934 FIXME("(%c %p): stub\n", node
, available_bytes
);
3935 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3939 /**********************************************************************
3940 * GetProcessDEPPolicy (KERNEL32.@)
3942 BOOL WINAPI
GetProcessDEPPolicy(HANDLE process
, LPDWORD flags
, PBOOL permanent
)
3944 FIXME("(%p %p %p): stub\n", process
, flags
, permanent
);
3945 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3949 /**********************************************************************
3950 * FlushProcessWriteBuffers (KERNEL32.@)
3952 VOID WINAPI
FlushProcessWriteBuffers(void)
3954 static int once
= 0;