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>
46 #define WIN32_NO_STATUS
48 #include "kernel_private.h"
50 #include "wine/library.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(process
);
56 WINE_DECLARE_DEBUG_CHANNEL(file
);
57 WINE_DECLARE_DEBUG_CHANNEL(relay
);
60 #include <CoreFoundation/CoreFoundation.h>
63 extern char **__wine_get_main_environment(void);
65 extern char **__wine_main_environ
;
66 static char **__wine_get_main_environment(void) { return __wine_main_environ
; }
77 static DWORD shutdown_flags
= 0;
78 static DWORD shutdown_priority
= 0x280;
80 static const int is_win64
= (sizeof(void *) > sizeof(int));
82 HMODULE kernel32_handle
= 0;
84 const WCHAR
*DIR_Windows
= NULL
;
85 const WCHAR
*DIR_System
= NULL
;
86 const WCHAR
*DIR_SysWow64
= NULL
;
89 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
90 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
91 #define PDB32_DOS_PROC 0x0010 /* Dos process */
92 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
93 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
94 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
96 static const WCHAR exeW
[] = {'.','e','x','e',0};
97 static const WCHAR comW
[] = {'.','c','o','m',0};
98 static const WCHAR batW
[] = {'.','b','a','t',0};
99 static const WCHAR cmdW
[] = {'.','c','m','d',0};
100 static const WCHAR pifW
[] = {'.','p','i','f',0};
101 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
103 static void exec_process( LPCWSTR name
);
105 extern void SHELL_LoadRegistry(void);
108 /***********************************************************************
111 static inline int contains_path( LPCWSTR name
)
113 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
117 /***********************************************************************
120 * Check if an environment variable needs to be handled specially when
121 * passed through the Unix environment (i.e. prefixed with "WINE").
123 static inline int is_special_env_var( const char *var
)
125 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
126 !strncmp( var
, "PWD=", sizeof("PWD=")-1 ) ||
127 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
128 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
129 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
133 /***********************************************************************
136 static inline unsigned int is_path_prefix( const WCHAR
*prefix
, const WCHAR
*filename
)
138 unsigned int len
= strlenW( prefix
);
140 if (strncmpiW( filename
, prefix
, len
) || filename
[len
] != '\\') return 0;
141 while (filename
[len
] == '\\') len
++;
146 /***************************************************************************
149 * Get the path of a builtin module when the native file does not exist.
151 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
,
152 UINT size
, struct binary_info
*binary_info
)
156 void *redir_disabled
= 0;
157 unsigned int flags
= (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT
: 0);
159 /* builtin names cannot be empty or contain spaces */
160 if (!libname
[0] || strchrW( libname
, ' ' ) || strchrW( libname
, '\t' )) return FALSE
;
162 if (is_wow64
&& Wow64DisableWow64FsRedirection( &redir_disabled
))
163 Wow64RevertWow64FsRedirection( redir_disabled
);
165 if (contains_path( libname
))
167 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
168 filename
, &file_part
) > size
* sizeof(WCHAR
))
169 return FALSE
; /* too long */
171 if ((len
= is_path_prefix( DIR_System
, filename
)))
173 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
175 else if (DIR_SysWow64
&& (len
= is_path_prefix( DIR_SysWow64
, filename
)))
181 if (filename
+ len
!= file_part
) return FALSE
;
185 len
= strlenW( DIR_System
);
186 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
187 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
188 file_part
= filename
+ len
;
189 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
190 strcpyW( file_part
, libname
);
191 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
193 if (ext
&& !strchrW( file_part
, '.' ))
195 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
196 return FALSE
; /* too long */
197 strcatW( file_part
, ext
);
199 binary_info
->type
= BINARY_UNIX_LIB
;
200 binary_info
->flags
= flags
;
201 binary_info
->res_start
= NULL
;
202 binary_info
->res_end
= NULL
;
207 /***********************************************************************
210 * Open a specific exe file, taking load order into account.
211 * Returns the file handle or 0 for a builtin exe.
213 static HANDLE
open_exe_file( const WCHAR
*name
, struct binary_info
*binary_info
)
217 TRACE("looking for %s\n", debugstr_w(name
) );
219 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
220 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
222 WCHAR buffer
[MAX_PATH
];
223 /* file doesn't exist, check for builtin */
224 if (contains_path( name
) && get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
), binary_info
))
227 else MODULE_get_binary_info( handle
, binary_info
);
233 /***********************************************************************
236 * Open an exe file, and return the full name and file handle.
237 * Returns FALSE if file could not be found.
238 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
239 * If file is a builtin exe, returns TRUE and sets handle to 0.
241 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
,
242 HANDLE
*handle
, struct binary_info
*binary_info
)
244 TRACE("looking for %s\n", debugstr_w(name
) );
246 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
))
248 if (contains_path( name
) && get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
))
253 /* no builtin found, try native without extension in case it is a Unix app */
254 if (!SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
)) return FALSE
;
257 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
258 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
259 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
261 MODULE_get_binary_info( *handle
, binary_info
);
268 /***********************************************************************
269 * build_initial_environment
271 * Build the Win32 environment from the Unix environment
273 static BOOL
build_initial_environment(void)
279 char **env
= __wine_get_main_environment();
281 /* Compute the total size of the Unix environment */
282 for (e
= env
; *e
; e
++)
284 if (is_special_env_var( *e
)) continue;
285 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
287 size
*= sizeof(WCHAR
);
289 /* Now allocate the environment */
291 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
292 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
295 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
296 endptr
= p
+ size
/ sizeof(WCHAR
);
298 /* And fill it with the Unix environment */
299 for (e
= env
; *e
; e
++)
303 /* skip Unix special variables and use the Wine variants instead */
304 if (!strncmp( str
, "WINE", 4 ))
306 if (is_special_env_var( str
+ 4 )) str
+= 4;
307 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
309 else if (is_special_env_var( str
)) continue; /* skip it */
311 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
319 /***********************************************************************
320 * set_registry_variables
322 * Set environment variables by enumerating the values of a key;
323 * helper for set_registry_environment().
324 * Note that Windows happily truncates the value if it's too big.
326 static void set_registry_variables( HANDLE hkey
, ULONG type
)
328 static const WCHAR pathW
[] = {'P','A','T','H'};
329 static const WCHAR sep
[] = {';',0};
330 UNICODE_STRING env_name
, env_value
;
334 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
337 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
340 tmp
.MaximumLength
= sizeof(tmpbuf
);
342 for (index
= 0; ; index
++)
344 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
345 buffer
, sizeof(buffer
), &size
);
346 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
348 if (info
->Type
!= type
)
350 env_name
.Buffer
= info
->Name
;
351 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
352 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
353 env_value
.Length
= info
->DataLength
;
354 env_value
.MaximumLength
= sizeof(buffer
) - info
->DataOffset
;
355 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
356 env_value
.Length
-= sizeof(WCHAR
); /* don't count terminating null if any */
357 if (!env_value
.Length
) continue;
358 if (info
->Type
== REG_EXPAND_SZ
)
360 status
= RtlExpandEnvironmentStrings_U( NULL
, &env_value
, &tmp
, NULL
);
361 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
) continue;
362 RtlCopyUnicodeString( &env_value
, &tmp
);
365 if (env_name
.Length
== sizeof(pathW
) &&
366 !memicmpW( env_name
.Buffer
, pathW
, sizeof(pathW
)/sizeof(WCHAR
) ) &&
367 !RtlQueryEnvironmentVariable_U( NULL
, &env_name
, &tmp
))
369 RtlAppendUnicodeToString( &tmp
, sep
);
370 if (RtlAppendUnicodeStringToString( &tmp
, &env_value
)) continue;
371 RtlCopyUnicodeString( &env_value
, &tmp
);
373 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
378 /***********************************************************************
379 * set_registry_environment
381 * Set the environment variables specified in the registry.
383 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
384 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
385 * on the order in which the variables are processed. But on Windows it
386 * does not really matter since they only use %SystemDrive% and
387 * %SystemRoot% which are predefined. But Wine defines these in the
388 * registry, so we need two passes.
390 static BOOL
set_registry_environment( BOOL volatile_only
)
392 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
393 'S','y','s','t','e','m','\\',
394 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
395 'C','o','n','t','r','o','l','\\',
396 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
397 'E','n','v','i','r','o','n','m','e','n','t',0};
398 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
399 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};
401 OBJECT_ATTRIBUTES attr
;
402 UNICODE_STRING nameW
;
406 attr
.Length
= sizeof(attr
);
407 attr
.RootDirectory
= 0;
408 attr
.ObjectName
= &nameW
;
410 attr
.SecurityDescriptor
= NULL
;
411 attr
.SecurityQualityOfService
= NULL
;
413 /* first the system environment variables */
414 RtlInitUnicodeString( &nameW
, env_keyW
);
415 if (!volatile_only
&& NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
417 set_registry_variables( hkey
, REG_SZ
);
418 set_registry_variables( hkey
, REG_EXPAND_SZ
);
423 /* then the ones for the current user */
424 if (RtlOpenCurrentUser( KEY_READ
, &attr
.RootDirectory
) != STATUS_SUCCESS
) return ret
;
425 RtlInitUnicodeString( &nameW
, envW
);
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
);
433 RtlInitUnicodeString( &nameW
, volatile_envW
);
434 if (NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
436 set_registry_variables( hkey
, REG_SZ
);
437 set_registry_variables( hkey
, REG_EXPAND_SZ
);
441 NtClose( attr
.RootDirectory
);
446 /***********************************************************************
449 static WCHAR
*get_reg_value( HKEY hkey
, const WCHAR
*name
)
451 char buffer
[1024 * sizeof(WCHAR
) + sizeof(KEY_VALUE_PARTIAL_INFORMATION
)];
452 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
453 DWORD len
, size
= sizeof(buffer
);
455 UNICODE_STRING nameW
;
457 RtlInitUnicodeString( &nameW
, name
);
458 if (NtQueryValueKey( hkey
, &nameW
, KeyValuePartialInformation
, buffer
, size
, &size
))
461 if (size
<= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) return NULL
;
462 len
= (size
- FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) / sizeof(WCHAR
);
464 if (info
->Type
== REG_EXPAND_SZ
)
466 UNICODE_STRING value
, expanded
;
468 value
.MaximumLength
= len
* sizeof(WCHAR
);
469 value
.Buffer
= (WCHAR
*)info
->Data
;
470 if (!value
.Buffer
[len
- 1]) len
--; /* don't count terminating null if any */
471 value
.Length
= len
* sizeof(WCHAR
);
472 expanded
.Length
= expanded
.MaximumLength
= 1024 * sizeof(WCHAR
);
473 if (!(expanded
.Buffer
= HeapAlloc( GetProcessHeap(), 0, expanded
.MaximumLength
))) return NULL
;
474 if (!RtlExpandEnvironmentStrings_U( NULL
, &value
, &expanded
, NULL
)) ret
= expanded
.Buffer
;
475 else RtlFreeUnicodeString( &expanded
);
477 else if (info
->Type
== REG_SZ
)
479 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
481 memcpy( ret
, info
->Data
, len
* sizeof(WCHAR
) );
489 /***********************************************************************
490 * set_additional_environment
492 * Set some additional environment variables not specified in the registry.
494 static void set_additional_environment(void)
496 static const WCHAR profile_keyW
[] = {'M','a','c','h','i','n','e','\\',
497 'S','o','f','t','w','a','r','e','\\',
498 'M','i','c','r','o','s','o','f','t','\\',
499 'W','i','n','d','o','w','s',' ','N','T','\\',
500 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
501 'P','r','o','f','i','l','e','L','i','s','t',0};
502 static const WCHAR profiles_valueW
[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
503 static const WCHAR all_users_valueW
[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
504 static const WCHAR allusersW
[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
505 OBJECT_ATTRIBUTES attr
;
506 UNICODE_STRING nameW
;
507 WCHAR
*profile_dir
= NULL
, *all_users_dir
= NULL
;
511 /* set the ALLUSERSPROFILE variables */
513 attr
.Length
= sizeof(attr
);
514 attr
.RootDirectory
= 0;
515 attr
.ObjectName
= &nameW
;
517 attr
.SecurityDescriptor
= NULL
;
518 attr
.SecurityQualityOfService
= NULL
;
519 RtlInitUnicodeString( &nameW
, profile_keyW
);
520 if (!NtOpenKey( &hkey
, KEY_READ
, &attr
))
522 profile_dir
= get_reg_value( hkey
, profiles_valueW
);
523 all_users_dir
= get_reg_value( hkey
, all_users_valueW
);
527 if (profile_dir
&& all_users_dir
)
531 len
= strlenW(profile_dir
) + strlenW(all_users_dir
) + 2;
532 value
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
533 strcpyW( value
, profile_dir
);
534 p
= value
+ strlenW(value
);
535 if (p
> value
&& p
[-1] != '\\') *p
++ = '\\';
536 strcpyW( p
, all_users_dir
);
537 SetEnvironmentVariableW( allusersW
, value
);
538 HeapFree( GetProcessHeap(), 0, value
);
541 HeapFree( GetProcessHeap(), 0, all_users_dir
);
542 HeapFree( GetProcessHeap(), 0, profile_dir
);
545 /***********************************************************************
546 * set_wow64_environment
548 * Set the environment variables that change across 32/64/Wow64.
550 static void set_wow64_environment(void)
552 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};
553 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};
554 static const WCHAR x86W
[] = {'x','8','6',0};
555 static const WCHAR versionW
[] = {'M','a','c','h','i','n','e','\\',
556 'S','o','f','t','w','a','r','e','\\',
557 'M','i','c','r','o','s','o','f','t','\\',
558 'W','i','n','d','o','w','s','\\',
559 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
560 static const WCHAR progdirW
[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
561 static const WCHAR progdir86W
[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
562 static const WCHAR progfilesW
[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
563 static const WCHAR progw6432W
[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
564 static const WCHAR commondirW
[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
565 static const WCHAR commondir86W
[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
566 static const WCHAR commonfilesW
[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
567 static const WCHAR commonw6432W
[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
569 OBJECT_ATTRIBUTES attr
;
570 UNICODE_STRING nameW
;
575 /* set the PROCESSOR_ARCHITECTURE variable */
577 if (GetEnvironmentVariableW( arch6432W
, arch
, sizeof(arch
)/sizeof(WCHAR
) ))
581 SetEnvironmentVariableW( archW
, arch
);
582 SetEnvironmentVariableW( arch6432W
, NULL
);
585 else if (GetEnvironmentVariableW( archW
, arch
, sizeof(arch
)/sizeof(WCHAR
) ))
589 SetEnvironmentVariableW( arch6432W
, arch
);
590 SetEnvironmentVariableW( archW
, x86W
);
594 attr
.Length
= sizeof(attr
);
595 attr
.RootDirectory
= 0;
596 attr
.ObjectName
= &nameW
;
598 attr
.SecurityDescriptor
= NULL
;
599 attr
.SecurityQualityOfService
= NULL
;
600 RtlInitUnicodeString( &nameW
, versionW
);
601 if (NtOpenKey( &hkey
, KEY_READ
| KEY_WOW64_64KEY
, &attr
)) return;
603 /* set the ProgramFiles variables */
605 if ((value
= get_reg_value( hkey
, progdirW
)))
607 if (is_win64
|| is_wow64
) SetEnvironmentVariableW( progw6432W
, value
);
608 if (is_win64
|| !is_wow64
) SetEnvironmentVariableW( progfilesW
, value
);
609 HeapFree( GetProcessHeap(), 0, value
);
611 if (is_wow64
&& (value
= get_reg_value( hkey
, progdir86W
)))
613 SetEnvironmentVariableW( progfilesW
, value
);
614 HeapFree( GetProcessHeap(), 0, value
);
617 /* set the CommonProgramFiles variables */
619 if ((value
= get_reg_value( hkey
, commondirW
)))
621 if (is_win64
|| is_wow64
) SetEnvironmentVariableW( commonw6432W
, value
);
622 if (is_win64
|| !is_wow64
) SetEnvironmentVariableW( commonfilesW
, value
);
623 HeapFree( GetProcessHeap(), 0, value
);
625 if (is_wow64
&& (value
= get_reg_value( hkey
, commondir86W
)))
627 SetEnvironmentVariableW( commonfilesW
, value
);
628 HeapFree( GetProcessHeap(), 0, value
);
634 /***********************************************************************
637 * Set the Wine library Unicode argv global variables.
639 static void set_library_wargv( char **argv
)
647 for (argc
= 0; argv
[argc
]; argc
++)
648 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
650 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
651 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
652 p
= (WCHAR
*)(wargv
+ argc
+ 1);
653 for (argc
= 0; argv
[argc
]; argc
++)
655 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
662 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
664 for (argc
= 0; wargv
[argc
]; argc
++)
665 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
667 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
668 q
= (char *)(argv
+ argc
+ 1);
669 for (argc
= 0; wargv
[argc
]; argc
++)
671 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
678 __wine_main_argc
= argc
;
679 __wine_main_argv
= argv
;
680 __wine_main_wargv
= wargv
;
684 /***********************************************************************
685 * update_library_argv0
687 * Update the argv[0] global variable with the binary we have found.
689 static void update_library_argv0( const WCHAR
*argv0
)
691 DWORD len
= strlenW( argv0
);
693 if (len
> strlenW( __wine_main_wargv
[0] ))
695 __wine_main_wargv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
697 strcpyW( __wine_main_wargv
[0], argv0
);
699 len
= WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, NULL
, 0, NULL
, NULL
);
700 if (len
> strlen( __wine_main_argv
[0] ) + 1)
702 __wine_main_argv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, len
);
704 WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, __wine_main_argv
[0], len
, NULL
, NULL
);
708 /***********************************************************************
711 * Build the command line of a process from the argv array.
713 * Note that it does NOT necessarily include the file name.
714 * Sometimes we don't even have any command line options at all.
716 * We must quote and escape characters so that the argv array can be rebuilt
717 * from the command line:
718 * - spaces and tabs must be quoted
720 * - quotes must be escaped
722 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
723 * resulting in an odd number of '\' followed by a '"'
726 * - '\'s that are not followed by a '"' can be left as is
730 static BOOL
build_command_line( WCHAR
**argv
)
735 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
737 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
740 for (arg
= argv
; *arg
; arg
++)
742 int has_space
,bcount
;
748 if( !*a
) has_space
=1;
753 if (*a
==' ' || *a
=='\t') {
755 } else if (*a
=='"') {
756 /* doubling of '\' preceding a '"',
757 * plus escaping of said '"'
765 len
+=(a
-*arg
)+1 /* for the separating space */;
767 len
+=2; /* for the quotes */
770 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
773 p
= rupp
->CommandLine
.Buffer
;
774 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
775 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
776 for (arg
= argv
; *arg
; arg
++)
778 int has_space
,has_quote
;
781 /* Check for quotes and spaces in this argument */
782 has_space
=has_quote
=0;
784 if( !*a
) has_space
=1;
786 if (*a
==' ' || *a
=='\t') {
790 } else if (*a
=='"') {
798 /* Now transfer it to the command line */
815 /* Double all the '\\' preceding this '"', plus one */
816 for (i
=0;i
<=bcount
;i
++)
828 while ((*p
=*x
++)) p
++;
834 if (p
> rupp
->CommandLine
.Buffer
)
835 p
--; /* remove last space */
842 /***********************************************************************
843 * init_current_directory
845 * Initialize the current directory from the Unix cwd or the parent info.
847 static void init_current_directory( CURDIR
*cur_dir
)
849 UNICODE_STRING dir_str
;
854 /* if we received a cur dir from the parent, try this first */
856 if (cur_dir
->DosPath
.Length
)
858 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
861 /* now try to get it from the Unix cwd */
863 for (size
= 256; ; size
*= 2)
865 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
866 if (getcwd( cwd
, size
)) break;
867 HeapFree( GetProcessHeap(), 0, cwd
);
868 if (errno
== ERANGE
) continue;
873 /* try to use PWD if it is valid, so that we don't resolve symlinks */
875 pwd
= getenv( "PWD" );
878 struct stat st1
, st2
;
880 if (!pwd
|| stat( pwd
, &st1
) == -1 ||
881 (!stat( cwd
, &st2
) && (st1
.st_dev
!= st2
.st_dev
|| st1
.st_ino
!= st2
.st_ino
)))
887 ANSI_STRING unix_name
;
888 UNICODE_STRING nt_name
;
889 RtlInitAnsiString( &unix_name
, pwd
);
890 if (!wine_unix_to_nt_file_name( &unix_name
, &nt_name
))
892 UNICODE_STRING dos_path
;
893 /* skip the \??\ prefix, nt_name is 0 terminated */
894 RtlInitUnicodeString( &dos_path
, nt_name
.Buffer
+ 4 );
895 RtlSetCurrentDirectory_U( &dos_path
);
896 RtlFreeUnicodeString( &nt_name
);
900 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
902 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
903 "starting in the Windows directory.\n", cwd
? cwd
: "" );
904 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
905 RtlSetCurrentDirectory_U( &dir_str
);
907 HeapFree( GetProcessHeap(), 0, cwd
);
910 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
911 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
915 /***********************************************************************
918 * Initialize the windows and system directories from the environment.
920 static void init_windows_dirs(void)
922 extern void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
924 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
925 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
926 static const WCHAR default_windirW
[] = {'C',':','\\','w','i','n','d','o','w','s',0};
927 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m','3','2',0};
928 static const WCHAR default_syswow64W
[] = {'\\','s','y','s','w','o','w','6','4',0};
933 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
935 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
936 GetEnvironmentVariableW( windirW
, buffer
, len
);
937 DIR_Windows
= buffer
;
939 else DIR_Windows
= default_windirW
;
941 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
943 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
944 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
949 len
= strlenW( DIR_Windows
);
950 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
951 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
952 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
956 if (!CreateDirectoryW( DIR_Windows
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
957 ERR( "directory %s could not be created, error %u\n",
958 debugstr_w(DIR_Windows
), GetLastError() );
959 if (!CreateDirectoryW( DIR_System
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
960 ERR( "directory %s could not be created, error %u\n",
961 debugstr_w(DIR_System
), GetLastError() );
963 if (is_win64
|| is_wow64
) /* SysWow64 is always defined on 64-bit */
965 len
= strlenW( DIR_Windows
);
966 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_syswow64W
) );
967 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
968 memcpy( buffer
+ len
, default_syswow64W
, sizeof(default_syswow64W
) );
969 DIR_SysWow64
= buffer
;
970 if (!CreateDirectoryW( DIR_SysWow64
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
971 ERR( "directory %s could not be created, error %u\n",
972 debugstr_w(DIR_SysWow64
), GetLastError() );
975 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
976 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
978 /* set the directories in ntdll too */
979 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
983 /***********************************************************************
986 * Start the wineboot process if necessary. Return the handles to wait on.
988 static void start_wineboot( HANDLE handles
[2] )
990 static const WCHAR wineboot_eventW
[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
993 if (!(handles
[0] = CreateEventW( NULL
, TRUE
, FALSE
, wineboot_eventW
)))
995 ERR( "failed to create wineboot event, expect trouble\n" );
998 if (GetLastError() != ERROR_ALREADY_EXISTS
) /* we created it */
1000 static const WCHAR wineboot
[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1001 static const WCHAR args
[] = {' ','-','-','i','n','i','t',0};
1003 PROCESS_INFORMATION pi
;
1005 WCHAR app
[MAX_PATH
];
1006 WCHAR cmdline
[MAX_PATH
+ (sizeof(wineboot
) + sizeof(args
)) / sizeof(WCHAR
)];
1008 memset( &si
, 0, sizeof(si
) );
1010 si
.dwFlags
= STARTF_USESTDHANDLES
;
1013 si
.hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
1015 GetSystemDirectoryW( app
, MAX_PATH
- sizeof(wineboot
)/sizeof(WCHAR
) );
1016 lstrcatW( app
, wineboot
);
1018 Wow64DisableWow64FsRedirection( &redir
);
1019 strcpyW( cmdline
, app
);
1020 strcatW( cmdline
, args
);
1021 if (CreateProcessW( app
, cmdline
, NULL
, NULL
, FALSE
, DETACHED_PROCESS
, NULL
, NULL
, &si
, &pi
))
1023 TRACE( "started wineboot pid %04x tid %04x\n", pi
.dwProcessId
, pi
.dwThreadId
);
1024 CloseHandle( pi
.hThread
);
1025 handles
[1] = pi
.hProcess
;
1029 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1030 CloseHandle( handles
[0] );
1033 Wow64RevertWow64FsRedirection( redir
);
1039 extern DWORD
call_process_entry( PEB
*peb
, LPTHREAD_START_ROUTINE entry
);
1040 __ASM_GLOBAL_FUNC( call_process_entry
,
1042 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1043 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1044 "movl %esp,%ebp\n\t"
1045 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1046 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1048 "call *12(%ebp)\n\t"
1050 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1051 __ASM_CFI(".cfi_same_value %ebp\n\t")
1054 static inline DWORD
call_process_entry( PEB
*peb
, LPTHREAD_START_ROUTINE entry
)
1056 return entry( peb
);
1060 /***********************************************************************
1063 * Startup routine of a new process. Runs on the new process stack.
1065 static DWORD WINAPI
start_process( PEB
*peb
)
1067 IMAGE_NT_HEADERS
*nt
;
1068 LPTHREAD_START_ROUTINE entry
;
1070 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1071 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
1072 nt
->OptionalHeader
.AddressOfEntryPoint
);
1074 if (!nt
->OptionalHeader
.AddressOfEntryPoint
)
1076 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1077 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
) );
1081 if (TRACE_ON(relay
))
1082 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1083 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
1085 SetLastError( 0 ); /* clear error code */
1086 if (peb
->BeingDebugged
) DbgBreakPoint();
1087 return call_process_entry( peb
, entry
);
1091 /***********************************************************************
1094 * Change the process name in the ps output.
1096 static void set_process_name( int argc
, char *argv
[] )
1098 #ifdef HAVE_SETPROCTITLE
1099 setproctitle("-%s", argv
[1]);
1104 char *p
, *prctl_name
= argv
[1];
1105 char *end
= argv
[argc
-1] + strlen(argv
[argc
-1]) + 1;
1108 # define PR_SET_NAME 15
1111 if ((p
= strrchr( prctl_name
, '\\' ))) prctl_name
= p
+ 1;
1112 if ((p
= strrchr( prctl_name
, '/' ))) prctl_name
= p
+ 1;
1114 if (prctl( PR_SET_NAME
, prctl_name
) != -1)
1116 offset
= argv
[1] - argv
[0];
1117 memmove( argv
[1] - offset
, argv
[1], end
- argv
[1] );
1118 memset( end
- offset
, 0, offset
);
1119 for (i
= 1; i
< argc
; i
++) argv
[i
-1] = argv
[i
] - offset
;
1123 #endif /* HAVE_PRCTL */
1125 /* remove argv[0] */
1126 memmove( argv
, argv
+ 1, argc
* sizeof(argv
[0]) );
1131 /***********************************************************************
1132 * __wine_kernel_init
1134 * Wine initialisation: load and start the main exe file.
1136 void CDECL
__wine_kernel_init(void)
1138 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
1139 static const WCHAR dotW
[] = {'.',0};
1141 WCHAR
*p
, main_exe_name
[MAX_PATH
+1];
1142 PEB
*peb
= NtCurrentTeb()->Peb
;
1143 RTL_USER_PROCESS_PARAMETERS
*params
= peb
->ProcessParameters
;
1144 HANDLE boot_events
[2];
1145 BOOL got_environment
= TRUE
;
1147 /* Initialize everything */
1149 setbuf(stdout
,NULL
);
1150 setbuf(stderr
,NULL
);
1151 kernel32_handle
= GetModuleHandleW(kernel32W
);
1152 IsWow64Process( GetCurrentProcess(), &is_wow64
);
1156 if (!params
->Environment
)
1158 /* Copy the parent environment */
1159 if (!build_initial_environment()) exit(1);
1161 /* convert old configuration to new format */
1162 convert_old_config();
1164 got_environment
= set_registry_environment( FALSE
);
1165 set_additional_environment();
1168 init_windows_dirs();
1169 init_current_directory( ¶ms
->CurrentDirectory
);
1171 set_process_name( __wine_main_argc
, __wine_main_argv
);
1172 set_library_wargv( __wine_main_argv
);
1173 boot_events
[0] = boot_events
[1] = 0;
1175 if (peb
->ProcessParameters
->ImagePathName
.Buffer
)
1177 strcpyW( main_exe_name
, peb
->ProcessParameters
->ImagePathName
.Buffer
);
1181 struct binary_info binary_info
;
1183 if (!SearchPathW( NULL
, __wine_main_wargv
[0], exeW
, MAX_PATH
, main_exe_name
, NULL
) &&
1184 !get_builtin_path( __wine_main_wargv
[0], exeW
, main_exe_name
, MAX_PATH
, &binary_info
))
1186 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1187 ExitProcess( GetLastError() );
1189 update_library_argv0( main_exe_name
);
1190 if (!build_command_line( __wine_main_wargv
)) goto error
;
1191 start_wineboot( boot_events
);
1194 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1195 p
= strrchrW( main_exe_name
, '.' );
1196 if (!p
|| strchrW( p
, '/' ) || strchrW( p
, '\\' )) strcatW( main_exe_name
, dotW
);
1198 TRACE( "starting process name=%s argv[0]=%s\n",
1199 debugstr_w(main_exe_name
), debugstr_w(__wine_main_wargv
[0]) );
1201 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1202 MODULE_get_dll_load_path(main_exe_name
) );
1206 DWORD timeout
= 2 * 60 * 1000, count
= 1;
1208 if (boot_events
[1]) count
++;
1209 if (!got_environment
) timeout
= 5 * 60 * 1000; /* initial prefix creation can take longer */
1210 if (WaitForMultipleObjects( count
, boot_events
, FALSE
, timeout
) == WAIT_TIMEOUT
)
1211 ERR( "boot event wait timed out\n" );
1212 CloseHandle( boot_events
[0] );
1213 if (boot_events
[1]) CloseHandle( boot_events
[1] );
1214 /* reload environment now that wineboot has run */
1215 set_registry_environment( got_environment
);
1216 set_additional_environment();
1218 set_wow64_environment();
1220 if (!(peb
->ImageBaseAddress
= LoadLibraryExW( main_exe_name
, 0, DONT_RESOLVE_DLL_REFERENCES
)))
1225 DWORD error
= GetLastError();
1227 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1228 if (error
== ERROR_BAD_EXE_FORMAT
||
1229 error
== ERROR_INVALID_ADDRESS
||
1230 error
== ERROR_NOT_ENOUGH_MEMORY
)
1232 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name
);
1233 /* if we get back here, it failed */
1235 else if (error
== ERROR_MOD_NOT_FOUND
)
1237 if ((p
= strrchrW( main_exe_name
, '\\' ))) p
++;
1238 else p
= main_exe_name
;
1239 if (!strcmpiW( p
, winevdmW
) && __wine_main_argc
> 3)
1241 /* args 1 and 2 are --app-name full_path */
1242 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1243 debugstr_w(__wine_main_wargv
[3]) );
1244 ExitProcess( ERROR_BAD_EXE_FORMAT
);
1246 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name
) );
1247 ExitProcess( ERROR_FILE_NOT_FOUND
);
1249 args
[0] = (DWORD_PTR
)main_exe_name
;
1250 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ARGUMENT_ARRAY
,
1251 NULL
, error
, 0, msgW
, sizeof(msgW
)/sizeof(WCHAR
), (__ms_va_list
*)args
);
1252 WideCharToMultiByte( CP_ACP
, 0, msgW
, -1, msg
, sizeof(msg
), NULL
, NULL
);
1253 MESSAGE( "wine: %s", msg
);
1254 ExitProcess( error
);
1257 LdrInitializeThunk( start_process
, 0, 0, 0 );
1260 ExitProcess( GetLastError() );
1264 /***********************************************************************
1267 * Build an argv array from a command-line.
1268 * 'reserved' is the number of args to reserve before the first one.
1270 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1274 char *arg
,*s
,*d
,*cmdline
;
1275 int in_quotes
,bcount
,len
;
1277 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1278 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, len
))) return NULL
;
1279 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1286 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1289 /* skip the remaining spaces */
1290 while (*s
==' ' || *s
=='\t') {
1297 } else if (*s
=='\\') {
1298 /* '\', count them */
1300 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1302 in_quotes
=!in_quotes
;
1305 /* a regular character */
1310 if (!(argv
= HeapAlloc( GetProcessHeap(), 0, argc
*sizeof(*argv
) + len
)))
1312 HeapFree( GetProcessHeap(), 0, cmdline
);
1316 arg
= d
= s
= (char *)(argv
+ argc
);
1317 memcpy( d
, cmdline
, len
);
1322 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1323 /* Close the argument and copy it */
1327 /* skip the remaining spaces */
1330 } while (*s
==' ' || *s
=='\t');
1332 /* Start with a new argument */
1335 } else if (*s
=='\\') {
1339 } else if (*s
=='"') {
1341 if ((bcount
& 1)==0) {
1342 /* Preceded by an even number of '\', this is half that
1343 * number of '\', plus a '"' which we discard.
1347 in_quotes
=!in_quotes
;
1349 /* Preceded by an odd number of '\', this is half that
1350 * number of '\' followed by a '"'
1358 /* a regular character */
1369 HeapFree( GetProcessHeap(), 0, cmdline
);
1374 /***********************************************************************
1377 * Build the environment of a new child process.
1379 static char **build_envp( const WCHAR
*envW
)
1381 static const char * const unix_vars
[] = { "PATH", "TEMP", "TMP", "HOME" };
1386 int count
= 1, length
;
1389 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1391 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1392 if (!(env
= HeapAlloc( GetProcessHeap(), 0, length
))) return NULL
;
1393 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1395 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1396 if (is_special_env_var( p
)) length
+= 4; /* prefix it with "WINE" */
1398 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1400 if (!(p
= getenv(unix_vars
[i
]))) continue;
1401 length
+= strlen(unix_vars
[i
]) + strlen(p
) + 2;
1405 if ((envp
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*envp
) + length
)))
1407 char **envptr
= envp
;
1408 char *dst
= (char *)(envp
+ count
);
1410 /* some variables must not be modified, so we get them directly from the unix env */
1411 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1413 if (!(p
= getenv(unix_vars
[i
]))) continue;
1414 *envptr
++ = strcpy( dst
, unix_vars
[i
] );
1417 dst
+= strlen(dst
) + 1;
1420 /* now put the Windows environment strings */
1421 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1423 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1424 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1425 if (!strncmp( p
, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1426 if (!strncmp( p
, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1427 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1429 *envptr
++ = strcpy( dst
, "WINE" );
1434 *envptr
++ = strcpy( dst
, p
);
1436 dst
+= strlen(dst
) + 1;
1440 HeapFree( GetProcessHeap(), 0, env
);
1445 /***********************************************************************
1448 * Fork and exec a new Unix binary, checking for errors.
1450 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
, const WCHAR
*env
,
1451 const char *newdir
, DWORD flags
, STARTUPINFOW
*startup
)
1453 int fd
[2], stdin_fd
= -1, stdout_fd
= -1, stderr_fd
= -1;
1455 char **argv
, **envp
;
1457 if (!env
) env
= GetEnvironmentStringsW();
1460 if (pipe2( fd
, O_CLOEXEC
) == -1)
1465 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1468 fcntl( fd
[0], F_SETFD
, FD_CLOEXEC
);
1469 fcntl( fd
[1], F_SETFD
, FD_CLOEXEC
);
1472 if (!(flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1474 HANDLE hstdin
, hstdout
, hstderr
;
1476 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1478 hstdin
= startup
->hStdInput
;
1479 hstdout
= startup
->hStdOutput
;
1480 hstderr
= startup
->hStdError
;
1484 hstdin
= GetStdHandle(STD_INPUT_HANDLE
);
1485 hstdout
= GetStdHandle(STD_OUTPUT_HANDLE
);
1486 hstderr
= GetStdHandle(STD_ERROR_HANDLE
);
1489 if (is_console_handle( hstdin
))
1490 hstdin
= wine_server_ptr_handle( console_handle_unmap( hstdin
));
1491 if (is_console_handle( hstdout
))
1492 hstdout
= wine_server_ptr_handle( console_handle_unmap( hstdout
));
1493 if (is_console_handle( hstderr
))
1494 hstderr
= wine_server_ptr_handle( console_handle_unmap( hstderr
));
1495 wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1496 wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1497 wine_server_handle_to_fd( hstderr
, FILE_WRITE_DATA
, &stderr_fd
, NULL
);
1500 argv
= build_argv( cmdline
, 0 );
1501 envp
= build_envp( env
);
1503 if (!(pid
= fork())) /* child */
1507 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1510 if (!(pid
= fork()))
1512 int fd
= open( "/dev/null", O_RDWR
);
1514 /* close stdin and stdout */
1522 else if (pid
!= -1) _exit(0); /* parent */
1528 dup2( stdin_fd
, 0 );
1531 if (stdout_fd
!= -1)
1533 dup2( stdout_fd
, 1 );
1536 if (stderr_fd
!= -1)
1538 dup2( stderr_fd
, 2 );
1543 /* Reset signals that we previously set to SIG_IGN */
1544 signal( SIGPIPE
, SIG_DFL
);
1545 signal( SIGCHLD
, SIG_DFL
);
1547 if (newdir
) chdir(newdir
);
1549 if (argv
&& envp
) execve( filename
, argv
, envp
);
1551 write( fd
[1], &err
, sizeof(err
) );
1554 HeapFree( GetProcessHeap(), 0, argv
);
1555 HeapFree( GetProcessHeap(), 0, envp
);
1556 if (stdin_fd
!= -1) close( stdin_fd
);
1557 if (stdout_fd
!= -1) close( stdout_fd
);
1558 if (stderr_fd
!= -1) close( stderr_fd
);
1560 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1565 if (pid
== -1) FILE_SetDosError();
1571 static inline DWORD
append_string( void **ptr
, const WCHAR
*str
)
1573 DWORD len
= strlenW( str
);
1574 memcpy( *ptr
, str
, len
* sizeof(WCHAR
) );
1575 *ptr
= (WCHAR
*)*ptr
+ len
;
1576 return len
* sizeof(WCHAR
);
1579 /***********************************************************************
1580 * create_startup_info
1582 static startup_info_t
*create_startup_info( LPCWSTR filename
, LPCWSTR cmdline
,
1583 LPCWSTR cur_dir
, LPWSTR env
, DWORD flags
,
1584 const STARTUPINFOW
*startup
, DWORD
*info_size
)
1586 const RTL_USER_PROCESS_PARAMETERS
*cur_params
;
1588 startup_info_t
*info
;
1591 UNICODE_STRING newdir
;
1592 WCHAR imagepath
[MAX_PATH
];
1593 HANDLE hstdin
, hstdout
, hstderr
;
1595 if(!GetLongPathNameW( filename
, imagepath
, MAX_PATH
))
1596 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1597 if(!GetFullPathNameW( imagepath
, MAX_PATH
, imagepath
, NULL
))
1598 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1600 cur_params
= NtCurrentTeb()->Peb
->ProcessParameters
;
1602 newdir
.Buffer
= NULL
;
1605 if (RtlDosPathNameToNtPathName_U( cur_dir
, &newdir
, NULL
, NULL
))
1606 cur_dir
= newdir
.Buffer
+ 4; /* skip \??\ prefix */
1612 if (NtCurrentTeb()->Tib
.SubSystemTib
) /* FIXME: hack */
1613 cur_dir
= ((WIN16_SUBSYSTEM_TIB
*)NtCurrentTeb()->Tib
.SubSystemTib
)->curdir
.DosPath
.Buffer
;
1615 cur_dir
= cur_params
->CurrentDirectory
.DosPath
.Buffer
;
1617 title
= startup
->lpTitle
? startup
->lpTitle
: imagepath
;
1619 size
= sizeof(*info
);
1620 size
+= strlenW( cur_dir
) * sizeof(WCHAR
);
1621 size
+= cur_params
->DllPath
.Length
;
1622 size
+= strlenW( imagepath
) * sizeof(WCHAR
);
1623 size
+= strlenW( cmdline
) * sizeof(WCHAR
);
1624 size
+= strlenW( title
) * sizeof(WCHAR
);
1625 if (startup
->lpDesktop
) size
+= strlenW( startup
->lpDesktop
) * sizeof(WCHAR
);
1626 /* FIXME: shellinfo */
1627 if (startup
->lpReserved2
&& startup
->cbReserved2
) size
+= startup
->cbReserved2
;
1628 size
= (size
+ 1) & ~1;
1631 if (!(info
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, size
))) goto done
;
1633 info
->console_flags
= cur_params
->ConsoleFlags
;
1634 if (flags
& CREATE_NEW_PROCESS_GROUP
) info
->console_flags
= 1;
1635 if (flags
& CREATE_NEW_CONSOLE
) info
->console
= wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC
);
1637 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1639 hstdin
= startup
->hStdInput
;
1640 hstdout
= startup
->hStdOutput
;
1641 hstderr
= startup
->hStdError
;
1645 hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1646 hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1647 hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1649 info
->hstdin
= wine_server_obj_handle( hstdin
);
1650 info
->hstdout
= wine_server_obj_handle( hstdout
);
1651 info
->hstderr
= wine_server_obj_handle( hstderr
);
1652 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1654 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1655 if (is_console_handle(hstdin
)) info
->hstdin
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1656 if (is_console_handle(hstdout
)) info
->hstdout
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1657 if (is_console_handle(hstderr
)) info
->hstderr
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1661 if (is_console_handle(hstdin
)) info
->hstdin
= console_handle_unmap(hstdin
);
1662 if (is_console_handle(hstdout
)) info
->hstdout
= console_handle_unmap(hstdout
);
1663 if (is_console_handle(hstderr
)) info
->hstderr
= console_handle_unmap(hstderr
);
1666 info
->x
= startup
->dwX
;
1667 info
->y
= startup
->dwY
;
1668 info
->xsize
= startup
->dwXSize
;
1669 info
->ysize
= startup
->dwYSize
;
1670 info
->xchars
= startup
->dwXCountChars
;
1671 info
->ychars
= startup
->dwYCountChars
;
1672 info
->attribute
= startup
->dwFillAttribute
;
1673 info
->flags
= startup
->dwFlags
;
1674 info
->show
= startup
->wShowWindow
;
1677 info
->curdir_len
= append_string( &ptr
, cur_dir
);
1678 info
->dllpath_len
= cur_params
->DllPath
.Length
;
1679 memcpy( ptr
, cur_params
->DllPath
.Buffer
, cur_params
->DllPath
.Length
);
1680 ptr
= (char *)ptr
+ cur_params
->DllPath
.Length
;
1681 info
->imagepath_len
= append_string( &ptr
, imagepath
);
1682 info
->cmdline_len
= append_string( &ptr
, cmdline
);
1683 info
->title_len
= append_string( &ptr
, title
);
1684 if (startup
->lpDesktop
) info
->desktop_len
= append_string( &ptr
, startup
->lpDesktop
);
1685 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1687 info
->runtime_len
= startup
->cbReserved2
;
1688 memcpy( ptr
, startup
->lpReserved2
, startup
->cbReserved2
);
1692 RtlFreeUnicodeString( &newdir
);
1696 /***********************************************************************
1697 * get_alternate_loader
1699 * Get the name of the alternate (32 or 64 bit) Wine loader.
1701 static const char *get_alternate_loader( char **ret_env
)
1704 const char *loader
= NULL
;
1705 const char *loader_env
= getenv( "WINELOADER" );
1709 if (wine_get_build_dir()) loader
= is_win64
? "loader/wine" : "server/../loader/wine64";
1713 int len
= strlen( loader_env
);
1716 if (!(env
= HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len
+ 2 ))) return NULL
;
1717 strcpy( env
, "WINELOADER=" );
1718 strcat( env
, loader_env
);
1719 strcat( env
, "64" );
1723 if (!(env
= HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len
))) return NULL
;
1724 strcpy( env
, "WINELOADER=" );
1725 strcat( env
, loader_env
);
1726 len
+= sizeof("WINELOADER=") - 1;
1727 if (!strcmp( env
+ len
- 2, "64" )) env
[len
- 2] = 0;
1731 if ((loader
= strrchr( env
, '/' ))) loader
++;
1736 if (!loader
) loader
= is_win64
? "wine" : "wine64";
1741 /***********************************************************************
1742 * terminate_main_thread
1744 * On some versions of Mac OS X, the execve system call fails with
1745 * ENOTSUP if the process has multiple threads. Wine is always multi-
1746 * threaded on Mac OS X because it specifically reserves the main thread
1747 * for use by the system frameworks (see apple_main_thread() in
1748 * libs/wine/loader.c). So, when we need to exec without first forking,
1749 * we need to terminate the main thread first. We do this by installing
1750 * a custom run loop source onto the main run loop and signaling it.
1751 * The source's "perform" callback is pthread_exit and it will be
1752 * executed on the main thread, terminating it.
1754 * Returns TRUE if there's still hope the main thread has terminated or
1755 * will soon. Return FALSE if we've given up.
1757 static BOOL
terminate_main_thread(void)
1763 CFRunLoopSourceContext source_context
= { 0 };
1764 CFRunLoopSourceRef source
;
1766 source_context
.perform
= pthread_exit
;
1767 if (!(source
= CFRunLoopSourceCreate( NULL
, 0, &source_context
)))
1770 CFRunLoopAddSource( CFRunLoopGetMain(), source
, kCFRunLoopCommonModes
);
1771 CFRunLoopSourceSignal( source
);
1772 CFRunLoopWakeUp( CFRunLoopGetMain() );
1773 CFRelease( source
);
1781 usleep(delayms
* 1000);
1788 /***********************************************************************
1791 * Create a new process. If hFile is a valid handle we have an exe
1792 * file, otherwise it is a Winelib app.
1794 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1795 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1796 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1797 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1798 const struct binary_info
*binary_info
, int exec_only
)
1800 BOOL ret
, success
= FALSE
;
1801 HANDLE process_info
;
1803 char *winedebug
= NULL
;
1804 char *wineloader
= NULL
;
1805 const char *loader
= NULL
;
1807 startup_info_t
*startup_info
;
1808 DWORD startup_info_size
;
1809 int socketfd
[2], stdin_fd
= -1, stdout_fd
= -1;
1813 if (!is_win64
&& !is_wow64
&& (binary_info
->flags
& BINARY_FLAG_64BIT
))
1815 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename
) );
1816 SetLastError( ERROR_BAD_EXE_FORMAT
);
1820 RtlAcquirePebLock();
1822 if (!(startup_info
= create_startup_info( filename
, cmd_line
, cur_dir
, env
, flags
, startup
,
1823 &startup_info_size
)))
1825 RtlReleasePebLock();
1828 if (!env
) env
= NtCurrentTeb()->Peb
->ProcessParameters
->Environment
;
1832 static const WCHAR WINEDEBUG
[] = {'W','I','N','E','D','E','B','U','G','=',0};
1833 if (!winedebug
&& !strncmpW( env_end
, WINEDEBUG
, sizeof(WINEDEBUG
)/sizeof(WCHAR
) - 1 ))
1835 DWORD len
= WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, NULL
, 0, NULL
, NULL
);
1836 if ((winedebug
= HeapAlloc( GetProcessHeap(), 0, len
)))
1837 WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, winedebug
, len
, NULL
, NULL
);
1839 env_end
+= strlenW(env_end
) + 1;
1843 /* create the socket for the new process */
1845 if (socketpair( PF_UNIX
, SOCK_STREAM
, 0, socketfd
) == -1)
1847 RtlReleasePebLock();
1848 HeapFree( GetProcessHeap(), 0, winedebug
);
1849 HeapFree( GetProcessHeap(), 0, startup_info
);
1850 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1853 wine_server_send_fd( socketfd
[1] );
1854 close( socketfd
[1] );
1856 /* create the process on the server side */
1858 SERVER_START_REQ( new_process
)
1860 req
->inherit_all
= inherit
;
1861 req
->create_flags
= flags
;
1862 req
->socket_fd
= socketfd
[1];
1863 req
->exe_file
= wine_server_obj_handle( hFile
);
1864 req
->process_access
= PROCESS_ALL_ACCESS
;
1865 req
->process_attr
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1866 req
->thread_access
= THREAD_ALL_ACCESS
;
1867 req
->thread_attr
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1868 req
->info_size
= startup_info_size
;
1870 wine_server_add_data( req
, startup_info
, startup_info_size
);
1871 wine_server_add_data( req
, env
, (env_end
- env
) * sizeof(WCHAR
) );
1872 if ((ret
= !wine_server_call_err( req
)))
1874 info
->dwProcessId
= (DWORD
)reply
->pid
;
1875 info
->dwThreadId
= (DWORD
)reply
->tid
;
1876 info
->hProcess
= wine_server_ptr_handle( reply
->phandle
);
1877 info
->hThread
= wine_server_ptr_handle( reply
->thandle
);
1879 process_info
= wine_server_ptr_handle( reply
->info
);
1883 RtlReleasePebLock();
1886 close( socketfd
[0] );
1887 HeapFree( GetProcessHeap(), 0, startup_info
);
1888 HeapFree( GetProcessHeap(), 0, winedebug
);
1892 if (!(flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1894 if (startup_info
->hstdin
)
1895 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdin
),
1896 FILE_READ_DATA
, &stdin_fd
, NULL
);
1897 if (startup_info
->hstdout
)
1898 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdout
),
1899 FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1901 HeapFree( GetProcessHeap(), 0, startup_info
);
1903 /* create the child process */
1904 argv
= build_argv( cmd_line
, 1 );
1906 if (!is_win64
^ !(binary_info
->flags
& BINARY_FLAG_64BIT
))
1907 loader
= get_alternate_loader( &wineloader
);
1909 if (exec_only
|| !(pid
= fork())) /* child */
1911 char preloader_reserve
[64], socket_env
[64];
1913 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1915 if (!(pid
= fork()))
1917 int fd
= open( "/dev/null", O_RDWR
);
1919 /* close stdin and stdout */
1927 else if (pid
!= -1) _exit(0); /* parent */
1931 if (stdin_fd
!= -1) dup2( stdin_fd
, 0 );
1932 if (stdout_fd
!= -1) dup2( stdout_fd
, 1 );
1935 if (stdin_fd
!= -1) close( stdin_fd
);
1936 if (stdout_fd
!= -1) close( stdout_fd
);
1938 /* Reset signals that we previously set to SIG_IGN */
1939 signal( SIGPIPE
, SIG_DFL
);
1940 signal( SIGCHLD
, SIG_DFL
);
1942 sprintf( socket_env
, "WINESERVERSOCKET=%u", socketfd
[0] );
1943 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx",
1944 (unsigned long)binary_info
->res_start
, (unsigned long)binary_info
->res_end
);
1946 putenv( preloader_reserve
);
1947 putenv( socket_env
);
1948 if (winedebug
) putenv( winedebug
);
1949 if (wineloader
) putenv( wineloader
);
1950 if (unixdir
) chdir(unixdir
);
1956 wine_exec_wine_binary( loader
, argv
, getenv("WINELOADER") );
1959 while (errno
== ENOTSUP
&& exec_only
&& terminate_main_thread());
1967 /* this is the parent */
1969 if (stdin_fd
!= -1) close( stdin_fd
);
1970 if (stdout_fd
!= -1) close( stdout_fd
);
1971 close( socketfd
[0] );
1972 HeapFree( GetProcessHeap(), 0, argv
);
1973 HeapFree( GetProcessHeap(), 0, winedebug
);
1974 HeapFree( GetProcessHeap(), 0, wineloader
);
1981 /* wait for the new process info to be ready */
1983 WaitForSingleObject( process_info
, INFINITE
);
1984 SERVER_START_REQ( get_new_process_info
)
1986 req
->info
= wine_server_obj_handle( process_info
);
1987 wine_server_call( req
);
1988 success
= reply
->success
;
1989 err
= reply
->exit_code
;
1995 SetLastError( err
? err
: ERROR_INTERNAL_ERROR
);
1998 CloseHandle( process_info
);
2002 CloseHandle( process_info
);
2003 CloseHandle( info
->hProcess
);
2004 CloseHandle( info
->hThread
);
2005 info
->hProcess
= info
->hThread
= 0;
2006 info
->dwProcessId
= info
->dwThreadId
= 0;
2011 /***********************************************************************
2012 * create_vdm_process
2014 * Create a new VDM process for a 16-bit or DOS application.
2016 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
2017 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
2018 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
2019 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
2020 const struct binary_info
*binary_info
, int exec_only
)
2022 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2025 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
2026 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
2030 SetLastError( ERROR_OUTOFMEMORY
);
2033 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
2034 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
2035 flags
, startup
, info
, unixdir
, binary_info
, exec_only
);
2036 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
2041 /***********************************************************************
2042 * create_cmd_process
2044 * Create a new cmd shell process for a .BAT file.
2046 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
2047 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
2048 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
2049 LPPROCESS_INFORMATION info
)
2052 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
2053 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
2054 WCHAR comspec
[MAX_PATH
];
2058 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
2060 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
2061 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
2064 strcpyW( newcmdline
, comspec
);
2065 strcatW( newcmdline
, slashcW
);
2066 strcatW( newcmdline
, cmd_line
);
2067 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
2068 flags
, env
, cur_dir
, startup
, info
);
2069 HeapFree( GetProcessHeap(), 0, newcmdline
);
2074 /*************************************************************************
2077 * Helper for CreateProcess: retrieve the file name to load from the
2078 * app name and command line. Store the file name in buffer, and
2079 * return a possibly modified command line.
2080 * Also returns a handle to the opened file if it's a Windows binary.
2082 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
2083 int buflen
, HANDLE
*handle
, struct binary_info
*binary_info
)
2085 static const WCHAR quotesW
[] = {'"','%','s','"',0};
2087 WCHAR
*name
, *pos
, *first_space
, *ret
= NULL
;
2090 /* if we have an app name, everything is easy */
2094 /* use the unmodified app name as file name */
2095 lstrcpynW( buffer
, appname
, buflen
);
2096 *handle
= open_exe_file( buffer
, binary_info
);
2097 if (!(ret
= cmdline
) || !cmdline
[0])
2099 /* no command-line, create one */
2100 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
2101 sprintfW( ret
, quotesW
, appname
);
2106 /* first check for a quoted file name */
2108 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
2110 int len
= p
- cmdline
- 1;
2111 /* extract the quoted portion as file name */
2112 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
2113 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
2116 if (!find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
2118 if (!get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
)) goto done
;
2121 ret
= cmdline
; /* no change necessary */
2125 /* now try the command-line word by word */
2127 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
2135 while (*p
&& *p
!= ' ' && *p
!= '\t') *pos
++ = *p
++;
2137 if (find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
2142 if (!first_space
) first_space
= pos
;
2143 if (!(*pos
++ = *p
++)) break;
2148 if (first_space
) *first_space
= 0; /* try only the first word as a builtin */
2149 if (get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
))
2154 else SetLastError( ERROR_FILE_NOT_FOUND
);
2156 else if (first_space
) /* build a new command-line with quotes */
2158 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
2160 sprintfW( ret
, quotesW
, name
);
2165 HeapFree( GetProcessHeap(), 0, name
);
2170 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2171 static BOOL
create_process_impl( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2172 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
2173 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
2174 LPPROCESS_INFORMATION info
)
2178 char *unixdir
= NULL
;
2179 WCHAR name
[MAX_PATH
];
2180 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
2181 struct binary_info binary_info
;
2183 /* Process the AppName and/or CmdLine to get module name and path */
2185 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
2187 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
)/sizeof(WCHAR
),
2188 &hFile
, &binary_info
)))
2190 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
2192 /* Warn if unsupported features are used */
2194 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
2195 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
2196 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
2197 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
2198 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name
), flags
);
2202 if (!(unixdir
= wine_get_unix_file_name( cur_dir
)))
2204 SetLastError(ERROR_DIRECTORY
);
2210 WCHAR buf
[MAX_PATH
];
2211 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
2214 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
2219 while (*p
) p
+= strlen(p
) + 1;
2220 p
++; /* final null */
2221 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
2222 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
2223 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
2224 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2227 info
->hThread
= info
->hProcess
= 0;
2228 info
->dwProcessId
= info
->dwThreadId
= 0;
2230 if (binary_info
.flags
& BINARY_FLAG_DLL
)
2232 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
2233 SetLastError( ERROR_BAD_EXE_FORMAT
);
2235 else switch (binary_info
.type
)
2238 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2239 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32,
2240 binary_info
.res_start
, binary_info
.res_end
);
2241 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2242 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2247 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2248 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2249 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2251 case BINARY_UNIX_LIB
:
2252 TRACE( "starting %s as %d-bit Winelib app\n",
2253 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32 );
2254 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2255 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2257 case BINARY_UNKNOWN
:
2258 /* check for .com or .bat extension */
2259 if ((p
= strrchrW( name
, '.' )))
2261 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
2263 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
2264 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2265 inherit
, flags
, startup_info
, info
, unixdir
,
2266 &binary_info
, FALSE
);
2269 if (!strcmpiW( p
, batW
) || !strcmpiW( p
, cmdW
) )
2271 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
2272 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2273 inherit
, flags
, startup_info
, info
);
2278 case BINARY_UNIX_EXE
:
2280 /* unknown file, try as unix executable */
2283 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
2285 if ((unix_name
= wine_get_unix_file_name( name
)))
2287 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
, flags
, startup_info
) != -1);
2288 HeapFree( GetProcessHeap(), 0, unix_name
);
2293 if (hFile
) CloseHandle( hFile
);
2296 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
2297 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
2298 HeapFree( GetProcessHeap(), 0, unixdir
);
2300 TRACE( "started process pid %04x tid %04x\n", info
->dwProcessId
, info
->dwThreadId
);
2305 /**********************************************************************
2306 * CreateProcessA (KERNEL32.@)
2308 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2309 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
2310 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
2311 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
2314 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
2315 UNICODE_STRING desktopW
, titleW
;
2318 desktopW
.Buffer
= NULL
;
2319 titleW
.Buffer
= NULL
;
2320 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
2321 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
2322 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
2324 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
2325 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
2327 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
2328 infoW
.lpDesktop
= desktopW
.Buffer
;
2329 infoW
.lpTitle
= titleW
.Buffer
;
2331 if (startup_info
->lpReserved
)
2332 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2333 debugstr_a(startup_info
->lpReserved
));
2335 ret
= create_process_impl( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
2336 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
2338 HeapFree( GetProcessHeap(), 0, app_nameW
);
2339 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
2340 HeapFree( GetProcessHeap(), 0, cur_dirW
);
2341 RtlFreeUnicodeString( &desktopW
);
2342 RtlFreeUnicodeString( &titleW
);
2347 /**********************************************************************
2348 * CreateProcessW (KERNEL32.@)
2350 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2351 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
2352 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
2353 LPPROCESS_INFORMATION info
)
2355 return create_process_impl( app_name
, cmd_line
, process_attr
, thread_attr
,
2356 inherit
, flags
, env
, cur_dir
, startup_info
, info
);
2360 /**********************************************************************
2363 static void exec_process( LPCWSTR name
)
2367 STARTUPINFOW startup_info
;
2368 PROCESS_INFORMATION info
;
2369 struct binary_info binary_info
;
2371 hFile
= open_exe_file( name
, &binary_info
);
2372 if (!hFile
|| hFile
== INVALID_HANDLE_VALUE
) return;
2374 memset( &startup_info
, 0, sizeof(startup_info
) );
2375 startup_info
.cb
= sizeof(startup_info
);
2377 /* Determine executable type */
2379 if (binary_info
.flags
& BINARY_FLAG_DLL
) return;
2380 switch (binary_info
.type
)
2383 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2384 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32,
2385 binary_info
.res_start
, binary_info
.res_end
);
2386 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2387 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2389 case BINARY_UNIX_LIB
:
2390 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
2391 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2392 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2394 case BINARY_UNKNOWN
:
2395 /* check for .com or .pif extension */
2396 if (!(p
= strrchrW( name
, '.' ))) break;
2397 if (strcmpiW( p
, comW
) && strcmpiW( p
, pifW
)) break;
2402 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2403 create_vdm_process( name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2404 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2409 CloseHandle( hFile
);
2413 /***********************************************************************
2416 * Wrapper to call WaitForInputIdle USER function
2418 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2420 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2422 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2425 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2426 if (ptr
) return ptr( process
, timeout
);
2432 /***********************************************************************
2433 * WinExec (KERNEL32.@)
2435 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2437 PROCESS_INFORMATION info
;
2438 STARTUPINFOA startup
;
2442 memset( &startup
, 0, sizeof(startup
) );
2443 startup
.cb
= sizeof(startup
);
2444 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2445 startup
.wShowWindow
= nCmdShow
;
2447 /* cmdline needs to be writable for CreateProcess */
2448 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2449 strcpy( cmdline
, lpCmdLine
);
2451 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2452 0, NULL
, NULL
, &startup
, &info
))
2454 /* Give 30 seconds to the app to come up */
2455 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2456 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2458 /* Close off the handles */
2459 CloseHandle( info
.hThread
);
2460 CloseHandle( info
.hProcess
);
2462 else if ((ret
= GetLastError()) >= 32)
2464 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2467 HeapFree( GetProcessHeap(), 0, cmdline
);
2472 /**********************************************************************
2473 * LoadModule (KERNEL32.@)
2475 DWORD WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2477 LOADPARMS32
*params
= paramBlock
;
2478 PROCESS_INFORMATION info
;
2479 STARTUPINFOA startup
;
2482 char filename
[MAX_PATH
];
2485 if (!name
) return ERROR_FILE_NOT_FOUND
;
2487 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2488 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2489 return GetLastError();
2491 len
= (BYTE
)params
->lpCmdLine
[0];
2492 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2493 return ERROR_NOT_ENOUGH_MEMORY
;
2495 strcpy( cmdline
, filename
);
2496 p
= cmdline
+ strlen(cmdline
);
2498 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2501 memset( &startup
, 0, sizeof(startup
) );
2502 startup
.cb
= sizeof(startup
);
2503 if (params
->lpCmdShow
)
2505 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2506 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2509 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2510 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2512 /* Give 30 seconds to the app to come up */
2513 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2514 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2516 /* Close off the handles */
2517 CloseHandle( info
.hThread
);
2518 CloseHandle( info
.hProcess
);
2520 else if ((ret
= GetLastError()) >= 32)
2522 FIXME("Strange error set by CreateProcess: %u\n", ret
);
2526 HeapFree( GetProcessHeap(), 0, cmdline
);
2531 /******************************************************************************
2532 * TerminateProcess (KERNEL32.@)
2534 * Terminates a process.
2537 * handle [I] Process to terminate.
2538 * exit_code [I] Exit code.
2542 * Failure: FALSE, check GetLastError().
2544 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2546 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2547 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2551 /***********************************************************************
2552 * ExitProcess (KERNEL32.@)
2554 * Exits the current process.
2557 * status [I] Status code to exit with.
2563 __ASM_STDCALL_FUNC( ExitProcess
, 4, /* Shrinker depend on this particular ExitProcess implementation */
2565 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2566 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2567 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2569 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2573 void WINAPI
process_ExitProcess( DWORD status
)
2575 LdrShutdownProcess();
2576 NtTerminateProcess(GetCurrentProcess(), status
);
2582 void WINAPI
ExitProcess( DWORD status
)
2584 LdrShutdownProcess();
2585 NtTerminateProcess(GetCurrentProcess(), status
);
2591 /***********************************************************************
2592 * GetExitCodeProcess [KERNEL32.@]
2594 * Gets termination status of specified process.
2597 * hProcess [in] Handle to the process.
2598 * lpExitCode [out] Address to receive termination status.
2604 BOOL WINAPI
GetExitCodeProcess( HANDLE hProcess
, LPDWORD lpExitCode
)
2607 PROCESS_BASIC_INFORMATION pbi
;
2609 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2611 if (status
== STATUS_SUCCESS
)
2613 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2616 SetLastError( RtlNtStatusToDosError(status
) );
2621 /***********************************************************************
2622 * SetErrorMode (KERNEL32.@)
2624 UINT WINAPI
SetErrorMode( UINT mode
)
2628 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode
,
2629 &old
, sizeof(old
), NULL
);
2630 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode
,
2631 &mode
, sizeof(mode
) );
2635 /***********************************************************************
2636 * GetErrorMode (KERNEL32.@)
2638 UINT WINAPI
GetErrorMode( void )
2642 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode
,
2643 &mode
, sizeof(mode
), NULL
);
2647 /**********************************************************************
2648 * TlsAlloc [KERNEL32.@]
2650 * Allocates a thread local storage index.
2653 * Success: TLS index.
2654 * Failure: 0xFFFFFFFF
2656 DWORD WINAPI
TlsAlloc( void )
2659 PEB
* const peb
= NtCurrentTeb()->Peb
;
2661 RtlAcquirePebLock();
2662 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 0 );
2663 if (index
!= ~0U) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2666 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2669 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2670 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2671 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2673 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2675 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2679 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2680 index
+= TLS_MINIMUM_AVAILABLE
;
2683 else SetLastError( ERROR_NO_MORE_ITEMS
);
2685 RtlReleasePebLock();
2690 /**********************************************************************
2691 * TlsFree [KERNEL32.@]
2693 * Releases a thread local storage index, making it available for reuse.
2696 * index [in] TLS index to free.
2702 BOOL WINAPI
TlsFree( DWORD index
)
2706 RtlAcquirePebLock();
2707 if (index
>= TLS_MINIMUM_AVAILABLE
)
2709 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2710 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2714 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2715 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2717 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2718 else SetLastError( ERROR_INVALID_PARAMETER
);
2719 RtlReleasePebLock();
2724 /**********************************************************************
2725 * TlsGetValue [KERNEL32.@]
2727 * Gets value in a thread's TLS slot.
2730 * index [in] TLS index to retrieve value for.
2733 * Success: Value stored in calling thread's TLS slot for index.
2734 * Failure: 0 and GetLastError() returns NO_ERROR.
2736 LPVOID WINAPI
TlsGetValue( DWORD index
)
2740 if (index
< TLS_MINIMUM_AVAILABLE
)
2742 ret
= NtCurrentTeb()->TlsSlots
[index
];
2746 index
-= TLS_MINIMUM_AVAILABLE
;
2747 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2749 SetLastError( ERROR_INVALID_PARAMETER
);
2752 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2753 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2755 SetLastError( ERROR_SUCCESS
);
2760 /**********************************************************************
2761 * TlsSetValue [KERNEL32.@]
2763 * Stores a value in the thread's TLS slot.
2766 * index [in] TLS index to set value for.
2767 * value [in] Value to be stored.
2773 BOOL WINAPI
TlsSetValue( DWORD index
, LPVOID value
)
2775 if (index
< TLS_MINIMUM_AVAILABLE
)
2777 NtCurrentTeb()->TlsSlots
[index
] = value
;
2781 index
-= TLS_MINIMUM_AVAILABLE
;
2782 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2784 SetLastError( ERROR_INVALID_PARAMETER
);
2787 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2788 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2789 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2791 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2794 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2800 /***********************************************************************
2801 * GetProcessFlags (KERNEL32.@)
2803 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2805 IMAGE_NT_HEADERS
*nt
;
2808 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2810 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2812 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2813 flags
|= PDB32_CONSOLE_PROC
;
2815 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2816 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2821 /*********************************************************************
2822 * OpenProcess (KERNEL32.@)
2824 * Opens a handle to a process.
2827 * access [I] Desired access rights assigned to the returned handle.
2828 * inherit [I] Determines whether or not child processes will inherit the handle.
2829 * id [I] Process identifier of the process to get a handle to.
2832 * Success: Valid handle to the specified process.
2833 * Failure: NULL, check GetLastError().
2835 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2839 OBJECT_ATTRIBUTES attr
;
2842 cid
.UniqueProcess
= ULongToHandle(id
);
2843 cid
.UniqueThread
= 0; /* FIXME ? */
2845 attr
.Length
= sizeof(OBJECT_ATTRIBUTES
);
2846 attr
.RootDirectory
= NULL
;
2847 attr
.Attributes
= inherit
? OBJ_INHERIT
: 0;
2848 attr
.SecurityDescriptor
= NULL
;
2849 attr
.SecurityQualityOfService
= NULL
;
2850 attr
.ObjectName
= NULL
;
2852 if (GetVersion() & 0x80000000) access
= PROCESS_ALL_ACCESS
;
2854 status
= NtOpenProcess(&handle
, access
, &attr
, &cid
);
2855 if (status
!= STATUS_SUCCESS
)
2857 SetLastError( RtlNtStatusToDosError(status
) );
2864 /*********************************************************************
2865 * GetProcessId (KERNEL32.@)
2867 * Gets the a unique identifier of a process.
2870 * hProcess [I] Handle to the process.
2874 * Failure: FALSE, check GetLastError().
2878 * The identifier is unique only on the machine and only until the process
2879 * exits (including system shutdown).
2881 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2884 PROCESS_BASIC_INFORMATION pbi
;
2886 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2888 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2889 SetLastError( RtlNtStatusToDosError(status
) );
2894 /*********************************************************************
2895 * CloseHandle (KERNEL32.@)
2900 * handle [I] Handle to close.
2904 * Failure: FALSE, check GetLastError().
2906 BOOL WINAPI
CloseHandle( HANDLE handle
)
2910 /* stdio handles need special treatment */
2911 if (handle
== (HANDLE
)STD_INPUT_HANDLE
)
2912 handle
= InterlockedExchangePointer( &NtCurrentTeb()->Peb
->ProcessParameters
->hStdInput
, 0 );
2913 else if (handle
== (HANDLE
)STD_OUTPUT_HANDLE
)
2914 handle
= InterlockedExchangePointer( &NtCurrentTeb()->Peb
->ProcessParameters
->hStdOutput
, 0 );
2915 else if (handle
== (HANDLE
)STD_ERROR_HANDLE
)
2916 handle
= InterlockedExchangePointer( &NtCurrentTeb()->Peb
->ProcessParameters
->hStdError
, 0 );
2918 if (is_console_handle(handle
))
2919 return CloseConsoleHandle(handle
);
2921 status
= NtClose( handle
);
2922 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2927 /*********************************************************************
2928 * GetHandleInformation (KERNEL32.@)
2930 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2932 OBJECT_DATA_INFORMATION info
;
2933 NTSTATUS status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
);
2935 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2939 if (info
.InheritHandle
) *flags
|= HANDLE_FLAG_INHERIT
;
2940 if (info
.ProtectFromClose
) *flags
|= HANDLE_FLAG_PROTECT_FROM_CLOSE
;
2946 /*********************************************************************
2947 * SetHandleInformation (KERNEL32.@)
2949 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2951 OBJECT_DATA_INFORMATION info
;
2954 /* if not setting both fields, retrieve current value first */
2955 if ((mask
& (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
)) !=
2956 (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
))
2958 if ((status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
)))
2960 SetLastError( RtlNtStatusToDosError(status
) );
2964 if (mask
& HANDLE_FLAG_INHERIT
)
2965 info
.InheritHandle
= (flags
& HANDLE_FLAG_INHERIT
) != 0;
2966 if (mask
& HANDLE_FLAG_PROTECT_FROM_CLOSE
)
2967 info
.ProtectFromClose
= (flags
& HANDLE_FLAG_PROTECT_FROM_CLOSE
) != 0;
2969 status
= NtSetInformationObject( handle
, ObjectDataInformation
, &info
, sizeof(info
) );
2970 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2975 /*********************************************************************
2976 * DuplicateHandle (KERNEL32.@)
2978 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2979 HANDLE dest_process
, HANDLE
*dest
,
2980 DWORD access
, BOOL inherit
, DWORD options
)
2984 if (is_console_handle(source
))
2986 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2987 if (source_process
!= dest_process
||
2988 source_process
!= GetCurrentProcess())
2990 SetLastError(ERROR_INVALID_PARAMETER
);
2993 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2994 return (*dest
!= INVALID_HANDLE_VALUE
);
2996 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2997 access
, inherit
? OBJ_INHERIT
: 0, options
);
2998 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3003 /***********************************************************************
3004 * ConvertToGlobalHandle (KERNEL32.@)
3006 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
3008 HANDLE ret
= INVALID_HANDLE_VALUE
;
3009 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
3010 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
3015 /***********************************************************************
3016 * SetHandleContext (KERNEL32.@)
3018 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
3020 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3021 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
3022 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3027 /***********************************************************************
3028 * GetHandleContext (KERNEL32.@)
3030 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
3032 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3033 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
3034 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3039 /***********************************************************************
3040 * CreateSocketHandle (KERNEL32.@)
3042 HANDLE WINAPI
CreateSocketHandle(void)
3044 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3045 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3046 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3047 return INVALID_HANDLE_VALUE
;
3051 /***********************************************************************
3052 * SetPriorityClass (KERNEL32.@)
3054 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
3057 PROCESS_PRIORITY_CLASS ppc
;
3059 ppc
.Foreground
= FALSE
;
3060 switch (priorityclass
)
3062 case IDLE_PRIORITY_CLASS
:
3063 ppc
.PriorityClass
= PROCESS_PRIOCLASS_IDLE
; break;
3064 case BELOW_NORMAL_PRIORITY_CLASS
:
3065 ppc
.PriorityClass
= PROCESS_PRIOCLASS_BELOW_NORMAL
; break;
3066 case NORMAL_PRIORITY_CLASS
:
3067 ppc
.PriorityClass
= PROCESS_PRIOCLASS_NORMAL
; break;
3068 case ABOVE_NORMAL_PRIORITY_CLASS
:
3069 ppc
.PriorityClass
= PROCESS_PRIOCLASS_ABOVE_NORMAL
; break;
3070 case HIGH_PRIORITY_CLASS
:
3071 ppc
.PriorityClass
= PROCESS_PRIOCLASS_HIGH
; break;
3072 case REALTIME_PRIORITY_CLASS
:
3073 ppc
.PriorityClass
= PROCESS_PRIOCLASS_REALTIME
; break;
3075 SetLastError(ERROR_INVALID_PARAMETER
);
3079 status
= NtSetInformationProcess(hprocess
, ProcessPriorityClass
,
3082 if (status
!= STATUS_SUCCESS
)
3084 SetLastError( RtlNtStatusToDosError(status
) );
3091 /***********************************************************************
3092 * GetPriorityClass (KERNEL32.@)
3094 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
3097 PROCESS_BASIC_INFORMATION pbi
;
3099 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
3101 if (status
!= STATUS_SUCCESS
)
3103 SetLastError( RtlNtStatusToDosError(status
) );
3106 switch (pbi
.BasePriority
)
3108 case PROCESS_PRIOCLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
3109 case PROCESS_PRIOCLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
3110 case PROCESS_PRIOCLASS_NORMAL
: return NORMAL_PRIORITY_CLASS
;
3111 case PROCESS_PRIOCLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
3112 case PROCESS_PRIOCLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
3113 case PROCESS_PRIOCLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
3115 SetLastError( ERROR_INVALID_PARAMETER
);
3120 /***********************************************************************
3121 * SetProcessAffinityMask (KERNEL32.@)
3123 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
3127 status
= NtSetInformationProcess(hProcess
, ProcessAffinityMask
,
3128 &affmask
, sizeof(DWORD_PTR
));
3131 SetLastError( RtlNtStatusToDosError(status
) );
3138 /**********************************************************************
3139 * GetProcessAffinityMask (KERNEL32.@)
3141 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
, PDWORD_PTR process_mask
, PDWORD_PTR system_mask
)
3143 NTSTATUS status
= STATUS_SUCCESS
;
3145 if (system_mask
) *system_mask
= (1 << NtCurrentTeb()->Peb
->NumberOfProcessors
) - 1;
3148 if ((status
= NtQueryInformationProcess( hProcess
, ProcessAffinityMask
,
3149 process_mask
, sizeof(*process_mask
), NULL
)))
3150 SetLastError( RtlNtStatusToDosError(status
) );
3156 /***********************************************************************
3157 * GetProcessVersion (KERNEL32.@)
3159 DWORD WINAPI
GetProcessVersion( DWORD pid
)
3163 PROCESS_BASIC_INFORMATION pbi
;
3166 IMAGE_DOS_HEADER dos
;
3167 IMAGE_NT_HEADERS nt
;
3170 if (!pid
|| pid
== GetCurrentProcessId())
3172 IMAGE_NT_HEADERS
*nt
;
3174 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
3175 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
3176 nt
->OptionalHeader
.MinorSubsystemVersion
);
3180 process
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
3181 if (!process
) return 0;
3183 status
= NtQueryInformationProcess(process
, ProcessBasicInformation
, &pbi
, sizeof(pbi
), NULL
);
3184 if (status
) goto err
;
3186 status
= NtReadVirtualMemory(process
, pbi
.PebBaseAddress
, &peb
, sizeof(peb
), &count
);
3187 if (status
|| count
!= sizeof(peb
)) goto err
;
3189 memset(&dos
, 0, sizeof(dos
));
3190 status
= NtReadVirtualMemory(process
, peb
.ImageBaseAddress
, &dos
, sizeof(dos
), &count
);
3191 if (status
|| count
!= sizeof(dos
)) goto err
;
3192 if (dos
.e_magic
!= IMAGE_DOS_SIGNATURE
) goto err
;
3194 memset(&nt
, 0, sizeof(nt
));
3195 status
= NtReadVirtualMemory(process
, (char *)peb
.ImageBaseAddress
+ dos
.e_lfanew
, &nt
, sizeof(nt
), &count
);
3196 if (status
|| count
!= sizeof(nt
)) goto err
;
3197 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) goto err
;
3199 ver
= MAKELONG(nt
.OptionalHeader
.MinorSubsystemVersion
, nt
.OptionalHeader
.MajorSubsystemVersion
);
3202 CloseHandle(process
);
3204 if (status
!= STATUS_SUCCESS
)
3205 SetLastError(RtlNtStatusToDosError(status
));
3211 /***********************************************************************
3212 * SetProcessWorkingSetSize [KERNEL32.@]
3213 * Sets the min/max working set sizes for a specified process.
3216 * hProcess [I] Handle to the process of interest
3217 * minset [I] Specifies minimum working set size
3218 * maxset [I] Specifies maximum working set size
3224 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
3227 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
3228 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
3229 /* Trim the working set to zero */
3230 /* Swap the process out of physical RAM */
3235 /***********************************************************************
3236 * K32EmptyWorkingSet (KERNEL32.@)
3238 BOOL WINAPI
K32EmptyWorkingSet(HANDLE hProcess
)
3240 return SetProcessWorkingSetSize(hProcess
, (SIZE_T
)-1, (SIZE_T
)-1);
3243 /***********************************************************************
3244 * GetProcessWorkingSetSize (KERNEL32.@)
3246 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
3249 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
3250 /* 32 MB working set size */
3251 if (minset
) *minset
= 32*1024*1024;
3252 if (maxset
) *maxset
= 32*1024*1024;
3257 /***********************************************************************
3258 * SetProcessShutdownParameters (KERNEL32.@)
3260 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
3262 FIXME("(%08x, %08x): partial stub.\n", level
, flags
);
3263 shutdown_flags
= flags
;
3264 shutdown_priority
= level
;
3269 /***********************************************************************
3270 * GetProcessShutdownParameters (KERNEL32.@)
3273 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
3275 *lpdwLevel
= shutdown_priority
;
3276 *lpdwFlags
= shutdown_flags
;
3281 /***********************************************************************
3282 * GetProcessPriorityBoost (KERNEL32.@)
3284 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
3286 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
3288 /* Report that no boost is present.. */
3289 *pDisablePriorityBoost
= FALSE
;
3294 /***********************************************************************
3295 * SetProcessPriorityBoost (KERNEL32.@)
3297 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
3299 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
3300 /* Say we can do it. I doubt the program will notice that we don't. */
3305 /***********************************************************************
3306 * ReadProcessMemory (KERNEL32.@)
3308 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
3309 SIZE_T
*bytes_read
)
3311 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
3312 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3317 /***********************************************************************
3318 * WriteProcessMemory (KERNEL32.@)
3320 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
3321 SIZE_T
*bytes_written
)
3323 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
3324 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3329 /****************************************************************************
3330 * FlushInstructionCache (KERNEL32.@)
3332 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
3335 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
3336 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3341 /******************************************************************
3342 * GetProcessIoCounters (KERNEL32.@)
3344 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
3348 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
3349 ioc
, sizeof(*ioc
), NULL
);
3350 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3354 /******************************************************************
3355 * GetProcessHandleCount (KERNEL32.@)
3357 BOOL WINAPI
GetProcessHandleCount(HANDLE hProcess
, DWORD
*cnt
)
3361 status
= NtQueryInformationProcess(hProcess
, ProcessHandleCount
,
3362 cnt
, sizeof(*cnt
), NULL
);
3363 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3367 /******************************************************************
3368 * QueryFullProcessImageNameA (KERNEL32.@)
3370 BOOL WINAPI
QueryFullProcessImageNameA(HANDLE hProcess
, DWORD dwFlags
, LPSTR lpExeName
, PDWORD pdwSize
)
3373 DWORD pdwSizeW
= *pdwSize
;
3374 LPWSTR lpExeNameW
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, *pdwSize
* sizeof(WCHAR
));
3376 retval
= QueryFullProcessImageNameW(hProcess
, dwFlags
, lpExeNameW
, &pdwSizeW
);
3379 retval
= (0 != WideCharToMultiByte(CP_ACP
, 0, lpExeNameW
, -1,
3380 lpExeName
, *pdwSize
, NULL
, NULL
));
3382 *pdwSize
= strlen(lpExeName
);
3384 HeapFree(GetProcessHeap(), 0, lpExeNameW
);
3388 /******************************************************************
3389 * QueryFullProcessImageNameW (KERNEL32.@)
3391 BOOL WINAPI
QueryFullProcessImageNameW(HANDLE hProcess
, DWORD dwFlags
, LPWSTR lpExeName
, PDWORD pdwSize
)
3393 BYTE buffer
[sizeof(UNICODE_STRING
) + MAX_PATH
*sizeof(WCHAR
)]; /* this buffer should be enough */
3394 UNICODE_STRING
*dynamic_buffer
= NULL
;
3395 UNICODE_STRING nt_path
;
3396 UNICODE_STRING
*result
= NULL
;
3400 RtlInitUnicodeStringEx(&nt_path
, NULL
);
3401 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3402 * as this is on Wine. */
3403 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, buffer
,
3404 sizeof(buffer
) - sizeof(WCHAR
), &needed
);
3405 if (status
== STATUS_INFO_LENGTH_MISMATCH
)
3407 dynamic_buffer
= HeapAlloc(GetProcessHeap(), 0, needed
+ sizeof(WCHAR
));
3408 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, (LPBYTE
)dynamic_buffer
, needed
, &needed
);
3409 result
= dynamic_buffer
;
3412 result
= (PUNICODE_STRING
)buffer
;
3414 if (status
) goto cleanup
;
3416 if (dwFlags
& PROCESS_NAME_NATIVE
)
3418 result
->Buffer
[result
->Length
/ sizeof(WCHAR
)] = 0;
3419 if (!RtlDosPathNameToNtPathName_U(result
->Buffer
, &nt_path
, NULL
, NULL
))
3421 status
= STATUS_OBJECT_PATH_NOT_FOUND
;
3427 if (result
->Length
/sizeof(WCHAR
) + 1 > *pdwSize
)
3429 status
= STATUS_BUFFER_TOO_SMALL
;
3433 *pdwSize
= result
->Length
/sizeof(WCHAR
);
3434 memcpy( lpExeName
, result
->Buffer
, result
->Length
);
3435 lpExeName
[*pdwSize
] = 0;
3438 HeapFree(GetProcessHeap(), 0, dynamic_buffer
);
3439 RtlFreeUnicodeString(&nt_path
);
3440 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3444 /***********************************************************************
3445 * K32GetProcessImageFileNameA (KERNEL32.@)
3447 DWORD WINAPI
K32GetProcessImageFileNameA( HANDLE process
, LPSTR file
, DWORD size
)
3449 FIXME("(%p, %p, %d) stub\n", process
, file
, size
);
3453 /***********************************************************************
3454 * K32GetProcessImageFileNameW (KERNEL32.@)
3456 DWORD WINAPI
K32GetProcessImageFileNameW( HANDLE process
, LPWSTR file
, DWORD size
)
3458 return QueryFullProcessImageNameW(process
, PROCESS_NAME_NATIVE
, file
, &size
) ? size
: 0;
3461 /***********************************************************************
3462 * K32EnumProcesses (KERNEL32.@)
3464 BOOL WINAPI
K32EnumProcesses(DWORD
*lpdwProcessIDs
, DWORD cb
, DWORD
*lpcbUsed
)
3466 SYSTEM_PROCESS_INFORMATION
*spi
;
3467 ULONG size
= 0x4000;
3473 HeapFree(GetProcessHeap(), 0, buf
);
3474 buf
= HeapAlloc(GetProcessHeap(), 0, size
);
3478 status
= NtQuerySystemInformation(SystemProcessInformation
, buf
, size
, NULL
);
3479 } while(status
== STATUS_INFO_LENGTH_MISMATCH
);
3481 if (status
!= STATUS_SUCCESS
)
3483 HeapFree(GetProcessHeap(), 0, buf
);
3484 SetLastError(RtlNtStatusToDosError(status
));
3490 for (*lpcbUsed
= 0; cb
>= sizeof(DWORD
); cb
-= sizeof(DWORD
))
3492 *lpdwProcessIDs
++ = HandleToUlong(spi
->UniqueProcessId
);
3493 *lpcbUsed
+= sizeof(DWORD
);
3495 if (spi
->NextEntryOffset
== 0)
3498 spi
= (SYSTEM_PROCESS_INFORMATION
*)(((PCHAR
)spi
) + spi
->NextEntryOffset
);
3501 HeapFree(GetProcessHeap(), 0, buf
);
3505 /***********************************************************************
3506 * K32QueryWorkingSet (KERNEL32.@)
3508 BOOL WINAPI
K32QueryWorkingSet( HANDLE process
, LPVOID buffer
, DWORD size
)
3512 TRACE( "(%p, %p, %d)\n", process
, buffer
, size
);
3514 status
= NtQueryVirtualMemory( process
, NULL
, MemoryWorkingSetList
, buffer
, size
, NULL
);
3518 SetLastError( RtlNtStatusToDosError( status
) );
3524 /***********************************************************************
3525 * K32QueryWorkingSetEx (KERNEL32.@)
3527 BOOL WINAPI
K32QueryWorkingSetEx( HANDLE process
, LPVOID buffer
, DWORD size
)
3531 TRACE( "(%p, %p, %d)\n", process
, buffer
, size
);
3533 status
= NtQueryVirtualMemory( process
, NULL
, MemoryWorkingSetList
, buffer
, size
, NULL
);
3537 SetLastError( RtlNtStatusToDosError( status
) );
3543 /***********************************************************************
3544 * K32GetProcessMemoryInfo (KERNEL32.@)
3546 * Retrieve memory usage information for a given process
3549 BOOL WINAPI
K32GetProcessMemoryInfo(HANDLE process
,
3550 PPROCESS_MEMORY_COUNTERS pmc
, DWORD cb
)
3555 if (cb
< sizeof(PROCESS_MEMORY_COUNTERS
))
3557 SetLastError(ERROR_INSUFFICIENT_BUFFER
);
3561 status
= NtQueryInformationProcess(process
, ProcessVmCounters
,
3562 &vmc
, sizeof(vmc
), NULL
);
3566 SetLastError(RtlNtStatusToDosError(status
));
3570 pmc
->cb
= sizeof(PROCESS_MEMORY_COUNTERS
);
3571 pmc
->PageFaultCount
= vmc
.PageFaultCount
;
3572 pmc
->PeakWorkingSetSize
= vmc
.PeakWorkingSetSize
;
3573 pmc
->WorkingSetSize
= vmc
.WorkingSetSize
;
3574 pmc
->QuotaPeakPagedPoolUsage
= vmc
.QuotaPeakPagedPoolUsage
;
3575 pmc
->QuotaPagedPoolUsage
= vmc
.QuotaPagedPoolUsage
;
3576 pmc
->QuotaPeakNonPagedPoolUsage
= vmc
.QuotaPeakNonPagedPoolUsage
;
3577 pmc
->QuotaNonPagedPoolUsage
= vmc
.QuotaNonPagedPoolUsage
;
3578 pmc
->PagefileUsage
= vmc
.PagefileUsage
;
3579 pmc
->PeakPagefileUsage
= vmc
.PeakPagefileUsage
;
3584 /***********************************************************************
3585 * ProcessIdToSessionId (KERNEL32.@)
3586 * This function is available on Terminal Server 4SP4 and Windows 2000
3588 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
3590 /* According to MSDN, if the calling process is not in a terminal
3591 * services environment, then the sessionid returned is zero.
3598 /***********************************************************************
3599 * RegisterServiceProcess (KERNEL32.@)
3601 * A service process calls this function to ensure that it continues to run
3602 * even after a user logged off.
3604 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
3606 /* I don't think that Wine needs to do anything in this function */
3607 return 1; /* success */
3611 /**********************************************************************
3612 * IsWow64Process (KERNEL32.@)
3614 BOOL WINAPI
IsWow64Process(HANDLE hProcess
, PBOOL Wow64Process
)
3619 status
= NtQueryInformationProcess( hProcess
, ProcessWow64Information
, &pbi
, sizeof(pbi
), NULL
);
3621 if (status
!= STATUS_SUCCESS
)
3623 SetLastError( RtlNtStatusToDosError( status
) );
3626 *Wow64Process
= (pbi
!= 0);
3631 /***********************************************************************
3632 * GetCurrentProcess (KERNEL32.@)
3634 * Get a handle to the current process.
3640 * A handle representing the current process.
3642 #undef GetCurrentProcess
3643 HANDLE WINAPI
GetCurrentProcess(void)
3645 return (HANDLE
)~(ULONG_PTR
)0;
3648 /***********************************************************************
3649 * GetLogicalProcessorInformation (KERNEL32.@)
3651 BOOL WINAPI
GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer
, PDWORD pBufLen
)
3653 FIXME("(%p,%p): stub\n", buffer
, pBufLen
);
3654 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3658 /***********************************************************************
3659 * GetLogicalProcessorInformationEx (KERNEL32.@)
3661 BOOL WINAPI
GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship
, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer
, PDWORD pBufLen
)
3663 FIXME("(%u,%p,%p): stub\n", relationship
, buffer
, pBufLen
);
3664 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3668 /***********************************************************************
3669 * CmdBatNotification (KERNEL32.@)
3671 * Notifies the system that a batch file has started or finished.
3674 * bBatchRunning [I] TRUE if a batch file has started or
3675 * FALSE if a batch file has finished executing.
3680 BOOL WINAPI
CmdBatNotification( BOOL bBatchRunning
)
3682 FIXME("%d\n", bBatchRunning
);
3687 /***********************************************************************
3688 * RegisterApplicationRestart (KERNEL32.@)
3690 HRESULT WINAPI
RegisterApplicationRestart(PCWSTR pwzCommandLine
, DWORD dwFlags
)
3692 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine
), dwFlags
);
3697 /**********************************************************************
3698 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3700 DWORD WINAPI
WTSGetActiveConsoleSessionId(void)
3706 /**********************************************************************
3707 * GetSystemDEPPolicy (KERNEL32.@)
3709 DEP_SYSTEM_POLICY_TYPE WINAPI
GetSystemDEPPolicy(void)
3715 /**********************************************************************
3716 * SetProcessDEPPolicy (KERNEL32.@)
3718 BOOL WINAPI
SetProcessDEPPolicy(DWORD newDEP
)
3720 FIXME("(%d): stub\n", newDEP
);
3721 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3725 /**********************************************************************
3726 * ApplicationRecoveryFinished (KERNEL32.@)
3728 VOID WINAPI
ApplicationRecoveryFinished(BOOL success
)
3731 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3734 /**********************************************************************
3735 * ApplicationRecoveryInProgress (KERNEL32.@)
3737 HRESULT WINAPI
ApplicationRecoveryInProgress(PBOOL canceled
)
3739 FIXME(":%p stub\n", canceled
);
3740 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3744 /**********************************************************************
3745 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3747 HRESULT WINAPI
RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback
, PVOID param
, DWORD pingint
, DWORD flags
)
3749 FIXME("%p, %p, %d, %d: stub\n", callback
, param
, pingint
, flags
);
3750 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);