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>
48 #include <CoreFoundation/CoreFoundation.h>
53 #define WIN32_NO_STATUS
55 #include "kernel_private.h"
57 #include "wine/library.h"
58 #include "wine/server.h"
59 #include "wine/unicode.h"
60 #include "wine/debug.h"
62 WINE_DEFAULT_DEBUG_CHANNEL(process
);
63 WINE_DECLARE_DEBUG_CHANNEL(file
);
64 WINE_DECLARE_DEBUG_CHANNEL(relay
);
67 extern char **__wine_get_main_environment(void);
69 extern char **__wine_main_environ
;
70 static char **__wine_get_main_environment(void) { return __wine_main_environ
; }
81 static DWORD shutdown_flags
= 0;
82 static DWORD shutdown_priority
= 0x280;
84 static const int is_win64
= (sizeof(void *) > sizeof(int));
86 HMODULE kernel32_handle
= 0;
88 const WCHAR
*DIR_Windows
= NULL
;
89 const WCHAR
*DIR_System
= NULL
;
90 const WCHAR
*DIR_SysWow64
= NULL
;
93 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
94 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
95 #define PDB32_DOS_PROC 0x0010 /* Dos process */
96 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
97 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
98 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
100 static const WCHAR exeW
[] = {'.','e','x','e',0};
101 static const WCHAR comW
[] = {'.','c','o','m',0};
102 static const WCHAR batW
[] = {'.','b','a','t',0};
103 static const WCHAR cmdW
[] = {'.','c','m','d',0};
104 static const WCHAR pifW
[] = {'.','p','i','f',0};
105 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
107 static void exec_process( LPCWSTR name
);
109 extern void SHELL_LoadRegistry(void);
112 /***********************************************************************
115 static inline int contains_path( LPCWSTR name
)
117 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
121 /***********************************************************************
124 * Check if an environment variable needs to be handled specially when
125 * passed through the Unix environment (i.e. prefixed with "WINE").
127 static inline int is_special_env_var( const char *var
)
129 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
130 !strncmp( var
, "PWD=", sizeof("PWD=")-1 ) ||
131 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
132 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
133 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
137 /***********************************************************************
140 static inline unsigned int is_path_prefix( const WCHAR
*prefix
, const WCHAR
*filename
)
142 unsigned int len
= strlenW( prefix
);
144 if (strncmpiW( filename
, prefix
, len
) || filename
[len
] != '\\') return 0;
145 while (filename
[len
] == '\\') len
++;
150 /***************************************************************************
153 * Get the path of a builtin module when the native file does not exist.
155 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
,
156 UINT size
, struct binary_info
*binary_info
)
160 void *redir_disabled
= 0;
161 unsigned int flags
= (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT
: 0);
163 /* builtin names cannot be empty or contain spaces */
164 if (!libname
[0] || strchrW( libname
, ' ' ) || strchrW( libname
, '\t' )) return FALSE
;
166 if (is_wow64
&& Wow64DisableWow64FsRedirection( &redir_disabled
))
167 Wow64RevertWow64FsRedirection( redir_disabled
);
169 if (contains_path( libname
))
171 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
172 filename
, &file_part
) > size
* sizeof(WCHAR
))
173 return FALSE
; /* too long */
175 if ((len
= is_path_prefix( DIR_System
, filename
)))
177 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
179 else if (DIR_SysWow64
&& (len
= is_path_prefix( DIR_SysWow64
, filename
)))
185 if (filename
+ len
!= file_part
) return FALSE
;
189 len
= strlenW( DIR_System
);
190 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
191 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
192 file_part
= filename
+ len
;
193 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
194 strcpyW( file_part
, libname
);
195 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
197 if (ext
&& !strchrW( file_part
, '.' ))
199 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
200 return FALSE
; /* too long */
201 strcatW( file_part
, ext
);
203 binary_info
->type
= BINARY_UNIX_LIB
;
204 binary_info
->flags
= flags
;
205 binary_info
->res_start
= NULL
;
206 binary_info
->res_end
= NULL
;
211 /***********************************************************************
214 * Open a specific exe file, taking load order into account.
215 * Returns the file handle or 0 for a builtin exe.
217 static HANDLE
open_exe_file( const WCHAR
*name
, struct binary_info
*binary_info
)
221 TRACE("looking for %s\n", debugstr_w(name
) );
223 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
224 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
226 WCHAR buffer
[MAX_PATH
];
227 /* file doesn't exist, check for builtin */
228 if (contains_path( name
) && get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
), binary_info
))
231 else MODULE_get_binary_info( handle
, binary_info
);
237 /***********************************************************************
240 * Open an exe file, and return the full name and file handle.
241 * Returns FALSE if file could not be found.
242 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
243 * If file is a builtin exe, returns TRUE and sets handle to 0.
245 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
,
246 HANDLE
*handle
, struct binary_info
*binary_info
)
248 TRACE("looking for %s\n", debugstr_w(name
) );
250 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
))
252 if (contains_path( name
) && get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
))
257 /* no builtin found, try native without extension in case it is a Unix app */
258 if (!SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
)) return FALSE
;
261 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
262 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
263 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
265 MODULE_get_binary_info( *handle
, binary_info
);
272 /***********************************************************************
273 * build_initial_environment
275 * Build the Win32 environment from the Unix environment
277 static BOOL
build_initial_environment(void)
283 char **env
= __wine_get_main_environment();
285 /* Compute the total size of the Unix environment */
286 for (e
= env
; *e
; e
++)
288 if (is_special_env_var( *e
)) continue;
289 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
291 size
*= sizeof(WCHAR
);
293 /* Now allocate the environment */
295 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
296 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
299 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
300 endptr
= p
+ size
/ sizeof(WCHAR
);
302 /* And fill it with the Unix environment */
303 for (e
= env
; *e
; e
++)
307 /* skip Unix special variables and use the Wine variants instead */
308 if (!strncmp( str
, "WINE", 4 ))
310 if (is_special_env_var( str
+ 4 )) str
+= 4;
311 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
313 else if (is_special_env_var( str
)) continue; /* skip it */
315 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
323 /***********************************************************************
324 * set_registry_variables
326 * Set environment variables by enumerating the values of a key;
327 * helper for set_registry_environment().
328 * Note that Windows happily truncates the value if it's too big.
330 static void set_registry_variables( HANDLE hkey
, ULONG type
)
332 static const WCHAR pathW
[] = {'P','A','T','H'};
333 static const WCHAR sep
[] = {';',0};
334 UNICODE_STRING env_name
, env_value
;
338 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
341 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
344 tmp
.MaximumLength
= sizeof(tmpbuf
);
346 for (index
= 0; ; index
++)
348 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
349 buffer
, sizeof(buffer
), &size
);
350 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
352 if (info
->Type
!= type
)
354 env_name
.Buffer
= info
->Name
;
355 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
356 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
357 env_value
.Length
= info
->DataLength
;
358 env_value
.MaximumLength
= sizeof(buffer
) - info
->DataOffset
;
359 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
360 env_value
.Length
-= sizeof(WCHAR
); /* don't count terminating null if any */
361 if (!env_value
.Length
) continue;
362 if (info
->Type
== REG_EXPAND_SZ
)
364 status
= RtlExpandEnvironmentStrings_U( NULL
, &env_value
, &tmp
, NULL
);
365 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
) continue;
366 RtlCopyUnicodeString( &env_value
, &tmp
);
369 if (env_name
.Length
== sizeof(pathW
) &&
370 !memicmpW( env_name
.Buffer
, pathW
, sizeof(pathW
)/sizeof(WCHAR
) ) &&
371 !RtlQueryEnvironmentVariable_U( NULL
, &env_name
, &tmp
))
373 RtlAppendUnicodeToString( &tmp
, sep
);
374 if (RtlAppendUnicodeStringToString( &tmp
, &env_value
)) continue;
375 RtlCopyUnicodeString( &env_value
, &tmp
);
377 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
382 /***********************************************************************
383 * set_registry_environment
385 * Set the environment variables specified in the registry.
387 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
388 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
389 * on the order in which the variables are processed. But on Windows it
390 * does not really matter since they only use %SystemDrive% and
391 * %SystemRoot% which are predefined. But Wine defines these in the
392 * registry, so we need two passes.
394 static BOOL
set_registry_environment( BOOL volatile_only
)
396 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
397 'S','y','s','t','e','m','\\',
398 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
399 'C','o','n','t','r','o','l','\\',
400 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
401 'E','n','v','i','r','o','n','m','e','n','t',0};
402 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
403 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};
405 OBJECT_ATTRIBUTES attr
;
406 UNICODE_STRING nameW
;
410 attr
.Length
= sizeof(attr
);
411 attr
.RootDirectory
= 0;
412 attr
.ObjectName
= &nameW
;
414 attr
.SecurityDescriptor
= NULL
;
415 attr
.SecurityQualityOfService
= NULL
;
417 /* first the system environment variables */
418 RtlInitUnicodeString( &nameW
, env_keyW
);
419 if (!volatile_only
&& NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
421 set_registry_variables( hkey
, REG_SZ
);
422 set_registry_variables( hkey
, REG_EXPAND_SZ
);
427 /* then the ones for the current user */
428 if (RtlOpenCurrentUser( KEY_READ
, &attr
.RootDirectory
) != STATUS_SUCCESS
) return ret
;
429 RtlInitUnicodeString( &nameW
, envW
);
430 if (!volatile_only
&& NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
432 set_registry_variables( hkey
, REG_SZ
);
433 set_registry_variables( hkey
, REG_EXPAND_SZ
);
437 RtlInitUnicodeString( &nameW
, volatile_envW
);
438 if (NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
440 set_registry_variables( hkey
, REG_SZ
);
441 set_registry_variables( hkey
, REG_EXPAND_SZ
);
445 NtClose( attr
.RootDirectory
);
450 /***********************************************************************
453 static WCHAR
*get_reg_value( HKEY hkey
, const WCHAR
*name
)
455 char buffer
[1024 * sizeof(WCHAR
) + sizeof(KEY_VALUE_PARTIAL_INFORMATION
)];
456 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
457 DWORD len
, size
= sizeof(buffer
);
459 UNICODE_STRING nameW
;
461 RtlInitUnicodeString( &nameW
, name
);
462 if (NtQueryValueKey( hkey
, &nameW
, KeyValuePartialInformation
, buffer
, size
, &size
))
465 if (size
<= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) return NULL
;
466 len
= (size
- FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) / sizeof(WCHAR
);
468 if (info
->Type
== REG_EXPAND_SZ
)
470 UNICODE_STRING value
, expanded
;
472 value
.MaximumLength
= len
* sizeof(WCHAR
);
473 value
.Buffer
= (WCHAR
*)info
->Data
;
474 if (!value
.Buffer
[len
- 1]) len
--; /* don't count terminating null if any */
475 value
.Length
= len
* sizeof(WCHAR
);
476 expanded
.Length
= expanded
.MaximumLength
= 1024 * sizeof(WCHAR
);
477 if (!(expanded
.Buffer
= HeapAlloc( GetProcessHeap(), 0, expanded
.MaximumLength
))) return NULL
;
478 if (!RtlExpandEnvironmentStrings_U( NULL
, &value
, &expanded
, NULL
)) ret
= expanded
.Buffer
;
479 else RtlFreeUnicodeString( &expanded
);
481 else if (info
->Type
== REG_SZ
)
483 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
485 memcpy( ret
, info
->Data
, len
* sizeof(WCHAR
) );
493 /***********************************************************************
494 * set_additional_environment
496 * Set some additional environment variables not specified in the registry.
498 static void set_additional_environment(void)
500 static const WCHAR profile_keyW
[] = {'M','a','c','h','i','n','e','\\',
501 'S','o','f','t','w','a','r','e','\\',
502 'M','i','c','r','o','s','o','f','t','\\',
503 'W','i','n','d','o','w','s',' ','N','T','\\',
504 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
505 'P','r','o','f','i','l','e','L','i','s','t',0};
506 static const WCHAR profiles_valueW
[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
507 static const WCHAR all_users_valueW
[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
508 static const WCHAR allusersW
[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
509 OBJECT_ATTRIBUTES attr
;
510 UNICODE_STRING nameW
;
511 WCHAR
*profile_dir
= NULL
, *all_users_dir
= NULL
;
515 /* set the ALLUSERSPROFILE variables */
517 attr
.Length
= sizeof(attr
);
518 attr
.RootDirectory
= 0;
519 attr
.ObjectName
= &nameW
;
521 attr
.SecurityDescriptor
= NULL
;
522 attr
.SecurityQualityOfService
= NULL
;
523 RtlInitUnicodeString( &nameW
, profile_keyW
);
524 if (!NtOpenKey( &hkey
, KEY_READ
, &attr
))
526 profile_dir
= get_reg_value( hkey
, profiles_valueW
);
527 all_users_dir
= get_reg_value( hkey
, all_users_valueW
);
531 if (profile_dir
&& all_users_dir
)
535 len
= strlenW(profile_dir
) + strlenW(all_users_dir
) + 2;
536 value
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
537 strcpyW( value
, profile_dir
);
538 p
= value
+ strlenW(value
);
539 if (p
> value
&& p
[-1] != '\\') *p
++ = '\\';
540 strcpyW( p
, all_users_dir
);
541 SetEnvironmentVariableW( allusersW
, value
);
542 HeapFree( GetProcessHeap(), 0, value
);
545 HeapFree( GetProcessHeap(), 0, all_users_dir
);
546 HeapFree( GetProcessHeap(), 0, profile_dir
);
549 /***********************************************************************
550 * set_wow64_environment
552 * Set the environment variables that change across 32/64/Wow64.
554 static void set_wow64_environment(void)
556 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};
557 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};
558 static const WCHAR x86W
[] = {'x','8','6',0};
559 static const WCHAR versionW
[] = {'M','a','c','h','i','n','e','\\',
560 'S','o','f','t','w','a','r','e','\\',
561 'M','i','c','r','o','s','o','f','t','\\',
562 'W','i','n','d','o','w','s','\\',
563 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
564 static const WCHAR progdirW
[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',0};
565 static const WCHAR progdir86W
[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
566 static const WCHAR progfilesW
[] = {'P','r','o','g','r','a','m','F','i','l','e','s',0};
567 static const WCHAR progw6432W
[] = {'P','r','o','g','r','a','m','W','6','4','3','2',0};
568 static const WCHAR commondirW
[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',0};
569 static const WCHAR commondir86W
[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')',0};
570 static const WCHAR commonfilesW
[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','F','i','l','e','s',0};
571 static const WCHAR commonw6432W
[] = {'C','o','m','m','o','n','P','r','o','g','r','a','m','W','6','4','3','2',0};
573 OBJECT_ATTRIBUTES attr
;
574 UNICODE_STRING nameW
;
579 /* set the PROCESSOR_ARCHITECTURE variable */
581 if (GetEnvironmentVariableW( arch6432W
, arch
, sizeof(arch
)/sizeof(WCHAR
) ))
585 SetEnvironmentVariableW( archW
, arch
);
586 SetEnvironmentVariableW( arch6432W
, NULL
);
589 else if (GetEnvironmentVariableW( archW
, arch
, sizeof(arch
)/sizeof(WCHAR
) ))
593 SetEnvironmentVariableW( arch6432W
, arch
);
594 SetEnvironmentVariableW( archW
, x86W
);
598 attr
.Length
= sizeof(attr
);
599 attr
.RootDirectory
= 0;
600 attr
.ObjectName
= &nameW
;
602 attr
.SecurityDescriptor
= NULL
;
603 attr
.SecurityQualityOfService
= NULL
;
604 RtlInitUnicodeString( &nameW
, versionW
);
605 if (NtOpenKey( &hkey
, KEY_READ
| KEY_WOW64_64KEY
, &attr
)) return;
607 /* set the ProgramFiles variables */
609 if ((value
= get_reg_value( hkey
, progdirW
)))
611 if (is_win64
|| is_wow64
) SetEnvironmentVariableW( progw6432W
, value
);
612 if (is_win64
|| !is_wow64
) SetEnvironmentVariableW( progfilesW
, value
);
613 HeapFree( GetProcessHeap(), 0, value
);
615 if (is_wow64
&& (value
= get_reg_value( hkey
, progdir86W
)))
617 SetEnvironmentVariableW( progfilesW
, value
);
618 HeapFree( GetProcessHeap(), 0, value
);
621 /* set the CommonProgramFiles variables */
623 if ((value
= get_reg_value( hkey
, commondirW
)))
625 if (is_win64
|| is_wow64
) SetEnvironmentVariableW( commonw6432W
, value
);
626 if (is_win64
|| !is_wow64
) SetEnvironmentVariableW( commonfilesW
, value
);
627 HeapFree( GetProcessHeap(), 0, value
);
629 if (is_wow64
&& (value
= get_reg_value( hkey
, commondir86W
)))
631 SetEnvironmentVariableW( commonfilesW
, value
);
632 HeapFree( GetProcessHeap(), 0, value
);
638 /***********************************************************************
641 * Set the Wine library Unicode argv global variables.
643 static void set_library_wargv( char **argv
)
651 for (argc
= 0; argv
[argc
]; argc
++)
652 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
654 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
655 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
656 p
= (WCHAR
*)(wargv
+ argc
+ 1);
657 for (argc
= 0; argv
[argc
]; argc
++)
659 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
666 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
668 for (argc
= 0; wargv
[argc
]; argc
++)
669 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
671 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
672 q
= (char *)(argv
+ argc
+ 1);
673 for (argc
= 0; wargv
[argc
]; argc
++)
675 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
682 __wine_main_argc
= argc
;
683 __wine_main_argv
= argv
;
684 __wine_main_wargv
= wargv
;
688 /***********************************************************************
689 * update_library_argv0
691 * Update the argv[0] global variable with the binary we have found.
693 static void update_library_argv0( const WCHAR
*argv0
)
695 DWORD len
= strlenW( argv0
);
697 if (len
> strlenW( __wine_main_wargv
[0] ))
699 __wine_main_wargv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
701 strcpyW( __wine_main_wargv
[0], argv0
);
703 len
= WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, NULL
, 0, NULL
, NULL
);
704 if (len
> strlen( __wine_main_argv
[0] ) + 1)
706 __wine_main_argv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, len
);
708 WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, __wine_main_argv
[0], len
, NULL
, NULL
);
712 /***********************************************************************
715 * Build the command line of a process from the argv array.
717 * Note that it does NOT necessarily include the file name.
718 * Sometimes we don't even have any command line options at all.
720 * We must quote and escape characters so that the argv array can be rebuilt
721 * from the command line:
722 * - spaces and tabs must be quoted
724 * - quotes must be escaped
726 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
727 * resulting in an odd number of '\' followed by a '"'
730 * - '\'s that are not followed by a '"' can be left as is
734 static BOOL
build_command_line( WCHAR
**argv
)
739 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
741 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
744 for (arg
= argv
; *arg
; arg
++)
746 int has_space
,bcount
;
752 if( !*a
) has_space
=1;
757 if (*a
==' ' || *a
=='\t') {
759 } else if (*a
=='"') {
760 /* doubling of '\' preceding a '"',
761 * plus escaping of said '"'
769 len
+=(a
-*arg
)+1 /* for the separating space */;
771 len
+=2; /* for the quotes */
774 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
777 p
= rupp
->CommandLine
.Buffer
;
778 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
779 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
780 for (arg
= argv
; *arg
; arg
++)
782 int has_space
,has_quote
;
785 /* Check for quotes and spaces in this argument */
786 has_space
=has_quote
=0;
788 if( !*a
) has_space
=1;
790 if (*a
==' ' || *a
=='\t') {
794 } else if (*a
=='"') {
802 /* Now transfer it to the command line */
819 /* Double all the '\\' preceding this '"', plus one */
820 for (i
=0;i
<=bcount
;i
++)
832 while ((*p
=*x
++)) p
++;
838 if (p
> rupp
->CommandLine
.Buffer
)
839 p
--; /* remove last space */
846 /***********************************************************************
847 * init_current_directory
849 * Initialize the current directory from the Unix cwd or the parent info.
851 static void init_current_directory( CURDIR
*cur_dir
)
853 UNICODE_STRING dir_str
;
858 /* if we received a cur dir from the parent, try this first */
860 if (cur_dir
->DosPath
.Length
)
862 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
865 /* now try to get it from the Unix cwd */
867 for (size
= 256; ; size
*= 2)
869 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
870 if (getcwd( cwd
, size
)) break;
871 HeapFree( GetProcessHeap(), 0, cwd
);
872 if (errno
== ERANGE
) continue;
877 /* try to use PWD if it is valid, so that we don't resolve symlinks */
879 pwd
= getenv( "PWD" );
882 struct stat st1
, st2
;
884 if (!pwd
|| stat( pwd
, &st1
) == -1 ||
885 (!stat( cwd
, &st2
) && (st1
.st_dev
!= st2
.st_dev
|| st1
.st_ino
!= st2
.st_ino
)))
891 ANSI_STRING unix_name
;
892 UNICODE_STRING nt_name
;
893 RtlInitAnsiString( &unix_name
, pwd
);
894 if (!wine_unix_to_nt_file_name( &unix_name
, &nt_name
))
896 UNICODE_STRING dos_path
;
897 /* skip the \??\ prefix, nt_name is 0 terminated */
898 RtlInitUnicodeString( &dos_path
, nt_name
.Buffer
+ 4 );
899 RtlSetCurrentDirectory_U( &dos_path
);
900 RtlFreeUnicodeString( &nt_name
);
904 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
906 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
907 "starting in the Windows directory.\n", cwd
? cwd
: "" );
908 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
909 RtlSetCurrentDirectory_U( &dir_str
);
911 HeapFree( GetProcessHeap(), 0, cwd
);
914 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
915 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
919 /***********************************************************************
922 * Initialize the windows and system directories from the environment.
924 static void init_windows_dirs(void)
926 extern void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
928 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
929 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
930 static const WCHAR default_windirW
[] = {'C',':','\\','w','i','n','d','o','w','s',0};
931 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m','3','2',0};
932 static const WCHAR default_syswow64W
[] = {'\\','s','y','s','w','o','w','6','4',0};
937 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
939 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
940 GetEnvironmentVariableW( windirW
, buffer
, len
);
941 DIR_Windows
= buffer
;
943 else DIR_Windows
= default_windirW
;
945 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
947 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
948 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
953 len
= strlenW( DIR_Windows
);
954 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
955 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
956 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
960 if (!CreateDirectoryW( DIR_Windows
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
961 ERR( "directory %s could not be created, error %u\n",
962 debugstr_w(DIR_Windows
), GetLastError() );
963 if (!CreateDirectoryW( DIR_System
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
964 ERR( "directory %s could not be created, error %u\n",
965 debugstr_w(DIR_System
), GetLastError() );
967 if (is_win64
|| is_wow64
) /* SysWow64 is always defined on 64-bit */
969 len
= strlenW( DIR_Windows
);
970 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_syswow64W
) );
971 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
972 memcpy( buffer
+ len
, default_syswow64W
, sizeof(default_syswow64W
) );
973 DIR_SysWow64
= buffer
;
974 if (!CreateDirectoryW( DIR_SysWow64
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
975 ERR( "directory %s could not be created, error %u\n",
976 debugstr_w(DIR_SysWow64
), GetLastError() );
979 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
980 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
982 /* set the directories in ntdll too */
983 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
987 /***********************************************************************
990 * Start the wineboot process if necessary. Return the handles to wait on.
992 static void start_wineboot( HANDLE handles
[2] )
994 static const WCHAR wineboot_eventW
[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
997 if (!(handles
[0] = CreateEventW( NULL
, TRUE
, FALSE
, wineboot_eventW
)))
999 ERR( "failed to create wineboot event, expect trouble\n" );
1002 if (GetLastError() != ERROR_ALREADY_EXISTS
) /* we created it */
1004 static const WCHAR wineboot
[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
1005 static const WCHAR args
[] = {' ','-','-','i','n','i','t',0};
1007 PROCESS_INFORMATION pi
;
1009 WCHAR app
[MAX_PATH
];
1010 WCHAR cmdline
[MAX_PATH
+ (sizeof(wineboot
) + sizeof(args
)) / sizeof(WCHAR
)];
1012 memset( &si
, 0, sizeof(si
) );
1014 si
.dwFlags
= STARTF_USESTDHANDLES
;
1017 si
.hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
1019 GetSystemDirectoryW( app
, MAX_PATH
- sizeof(wineboot
)/sizeof(WCHAR
) );
1020 lstrcatW( app
, wineboot
);
1022 Wow64DisableWow64FsRedirection( &redir
);
1023 strcpyW( cmdline
, app
);
1024 strcatW( cmdline
, args
);
1025 if (CreateProcessW( app
, cmdline
, NULL
, NULL
, FALSE
, DETACHED_PROCESS
, NULL
, NULL
, &si
, &pi
))
1027 TRACE( "started wineboot pid %04x tid %04x\n", pi
.dwProcessId
, pi
.dwThreadId
);
1028 CloseHandle( pi
.hThread
);
1029 handles
[1] = pi
.hProcess
;
1033 ERR( "failed to start wineboot, err %u\n", GetLastError() );
1034 CloseHandle( handles
[0] );
1037 Wow64RevertWow64FsRedirection( redir
);
1043 extern DWORD
call_process_entry( PEB
*peb
, LPTHREAD_START_ROUTINE entry
);
1044 __ASM_GLOBAL_FUNC( call_process_entry
,
1046 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1047 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
1048 "movl %esp,%ebp\n\t"
1049 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
1050 "subl $12,%esp\n\t" /* deliberately mis-align the stack by 8, Doom 3 needs this */
1052 "call *12(%ebp)\n\t"
1054 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
1055 __ASM_CFI(".cfi_same_value %ebp\n\t")
1058 static inline DWORD
call_process_entry( PEB
*peb
, LPTHREAD_START_ROUTINE entry
)
1060 return entry( peb
);
1064 /***********************************************************************
1067 * Startup routine of a new process. Runs on the new process stack.
1069 static DWORD WINAPI
start_process( PEB
*peb
)
1071 IMAGE_NT_HEADERS
*nt
;
1072 LPTHREAD_START_ROUTINE entry
;
1074 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1075 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
1076 nt
->OptionalHeader
.AddressOfEntryPoint
);
1078 if (!nt
->OptionalHeader
.AddressOfEntryPoint
)
1080 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1081 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
) );
1085 if (TRACE_ON(relay
))
1086 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1087 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
1089 SetLastError( 0 ); /* clear error code */
1090 if (peb
->BeingDebugged
) DbgBreakPoint();
1091 return call_process_entry( peb
, entry
);
1095 /***********************************************************************
1098 * Change the process name in the ps output.
1100 static void set_process_name( int argc
, char *argv
[] )
1102 #ifdef HAVE_SETPROCTITLE
1103 setproctitle("-%s", argv
[1]);
1108 char *p
, *prctl_name
= argv
[1];
1109 char *end
= argv
[argc
-1] + strlen(argv
[argc
-1]) + 1;
1112 # define PR_SET_NAME 15
1115 if ((p
= strrchr( prctl_name
, '\\' ))) prctl_name
= p
+ 1;
1116 if ((p
= strrchr( prctl_name
, '/' ))) prctl_name
= p
+ 1;
1118 if (prctl( PR_SET_NAME
, prctl_name
) != -1)
1120 offset
= argv
[1] - argv
[0];
1121 memmove( argv
[1] - offset
, argv
[1], end
- argv
[1] );
1122 memset( end
- offset
, 0, offset
);
1123 for (i
= 1; i
< argc
; i
++) argv
[i
-1] = argv
[i
] - offset
;
1127 #endif /* HAVE_PRCTL */
1129 /* remove argv[0] */
1130 memmove( argv
, argv
+ 1, argc
* sizeof(argv
[0]) );
1135 /***********************************************************************
1136 * __wine_kernel_init
1138 * Wine initialisation: load and start the main exe file.
1140 void CDECL
__wine_kernel_init(void)
1142 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
1143 static const WCHAR dotW
[] = {'.',0};
1145 WCHAR
*p
, main_exe_name
[MAX_PATH
+1];
1146 PEB
*peb
= NtCurrentTeb()->Peb
;
1147 RTL_USER_PROCESS_PARAMETERS
*params
= peb
->ProcessParameters
;
1148 HANDLE boot_events
[2];
1149 BOOL got_environment
= TRUE
;
1151 /* Initialize everything */
1153 setbuf(stdout
,NULL
);
1154 setbuf(stderr
,NULL
);
1155 kernel32_handle
= GetModuleHandleW(kernel32W
);
1156 IsWow64Process( GetCurrentProcess(), &is_wow64
);
1160 if (!params
->Environment
)
1162 /* Copy the parent environment */
1163 if (!build_initial_environment()) exit(1);
1165 /* convert old configuration to new format */
1166 convert_old_config();
1168 got_environment
= set_registry_environment( FALSE
);
1169 set_additional_environment();
1172 init_windows_dirs();
1173 init_current_directory( ¶ms
->CurrentDirectory
);
1175 set_process_name( __wine_main_argc
, __wine_main_argv
);
1176 set_library_wargv( __wine_main_argv
);
1177 boot_events
[0] = boot_events
[1] = 0;
1179 if (peb
->ProcessParameters
->ImagePathName
.Buffer
)
1181 strcpyW( main_exe_name
, peb
->ProcessParameters
->ImagePathName
.Buffer
);
1185 struct binary_info binary_info
;
1187 if (!SearchPathW( NULL
, __wine_main_wargv
[0], exeW
, MAX_PATH
, main_exe_name
, NULL
) &&
1188 !get_builtin_path( __wine_main_wargv
[0], exeW
, main_exe_name
, MAX_PATH
, &binary_info
))
1190 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1191 ExitProcess( GetLastError() );
1193 update_library_argv0( main_exe_name
);
1194 if (!build_command_line( __wine_main_wargv
)) goto error
;
1195 start_wineboot( boot_events
);
1198 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1199 p
= strrchrW( main_exe_name
, '.' );
1200 if (!p
|| strchrW( p
, '/' ) || strchrW( p
, '\\' )) strcatW( main_exe_name
, dotW
);
1202 TRACE( "starting process name=%s argv[0]=%s\n",
1203 debugstr_w(main_exe_name
), debugstr_w(__wine_main_wargv
[0]) );
1205 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1206 MODULE_get_dll_load_path(main_exe_name
) );
1210 DWORD timeout
= 2 * 60 * 1000, count
= 1;
1212 if (boot_events
[1]) count
++;
1213 if (!got_environment
) timeout
= 5 * 60 * 1000; /* initial prefix creation can take longer */
1214 if (WaitForMultipleObjects( count
, boot_events
, FALSE
, timeout
) == WAIT_TIMEOUT
)
1215 ERR( "boot event wait timed out\n" );
1216 CloseHandle( boot_events
[0] );
1217 if (boot_events
[1]) CloseHandle( boot_events
[1] );
1218 /* reload environment now that wineboot has run */
1219 set_registry_environment( got_environment
);
1220 set_additional_environment();
1222 set_wow64_environment();
1224 if (!(peb
->ImageBaseAddress
= LoadLibraryExW( main_exe_name
, 0, DONT_RESOLVE_DLL_REFERENCES
)))
1229 DWORD error
= GetLastError();
1231 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1232 if (error
== ERROR_BAD_EXE_FORMAT
||
1233 error
== ERROR_INVALID_ADDRESS
||
1234 error
== ERROR_NOT_ENOUGH_MEMORY
)
1236 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name
);
1237 /* if we get back here, it failed */
1239 else if (error
== ERROR_MOD_NOT_FOUND
)
1241 if ((p
= strrchrW( main_exe_name
, '\\' ))) p
++;
1242 else p
= main_exe_name
;
1243 if (!strcmpiW( p
, winevdmW
) && __wine_main_argc
> 3)
1245 /* args 1 and 2 are --app-name full_path */
1246 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1247 debugstr_w(__wine_main_wargv
[3]) );
1248 ExitProcess( ERROR_BAD_EXE_FORMAT
);
1250 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name
) );
1251 ExitProcess( ERROR_FILE_NOT_FOUND
);
1253 args
[0] = (DWORD_PTR
)main_exe_name
;
1254 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ARGUMENT_ARRAY
,
1255 NULL
, error
, 0, msgW
, sizeof(msgW
)/sizeof(WCHAR
), (__ms_va_list
*)args
);
1256 WideCharToMultiByte( CP_ACP
, 0, msgW
, -1, msg
, sizeof(msg
), NULL
, NULL
);
1257 MESSAGE( "wine: %s", msg
);
1258 ExitProcess( error
);
1261 LdrInitializeThunk( start_process
, 0, 0, 0 );
1264 ExitProcess( GetLastError() );
1268 /***********************************************************************
1271 * Build an argv array from a command-line.
1272 * 'reserved' is the number of args to reserve before the first one.
1274 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1278 char *arg
,*s
,*d
,*cmdline
;
1279 int in_quotes
,bcount
,len
;
1281 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1282 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, len
))) return NULL
;
1283 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1290 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1293 /* skip the remaining spaces */
1294 while (*s
==' ' || *s
=='\t') {
1301 } else if (*s
=='\\') {
1302 /* '\', count them */
1304 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1306 in_quotes
=!in_quotes
;
1309 /* a regular character */
1314 if (!(argv
= HeapAlloc( GetProcessHeap(), 0, argc
*sizeof(*argv
) + len
)))
1316 HeapFree( GetProcessHeap(), 0, cmdline
);
1320 arg
= d
= s
= (char *)(argv
+ argc
);
1321 memcpy( d
, cmdline
, len
);
1326 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1327 /* Close the argument and copy it */
1331 /* skip the remaining spaces */
1334 } while (*s
==' ' || *s
=='\t');
1336 /* Start with a new argument */
1339 } else if (*s
=='\\') {
1343 } else if (*s
=='"') {
1345 if ((bcount
& 1)==0) {
1346 /* Preceded by an even number of '\', this is half that
1347 * number of '\', plus a '"' which we discard.
1351 in_quotes
=!in_quotes
;
1353 /* Preceded by an odd number of '\', this is half that
1354 * number of '\' followed by a '"'
1362 /* a regular character */
1373 HeapFree( GetProcessHeap(), 0, cmdline
);
1378 /***********************************************************************
1381 * Build the environment of a new child process.
1383 static char **build_envp( const WCHAR
*envW
)
1385 static const char * const unix_vars
[] = { "PATH", "TEMP", "TMP", "HOME" };
1390 int count
= 1, length
;
1393 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1395 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1396 if (!(env
= HeapAlloc( GetProcessHeap(), 0, length
))) return NULL
;
1397 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1399 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1400 if (is_special_env_var( p
)) length
+= 4; /* prefix it with "WINE" */
1402 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1404 if (!(p
= getenv(unix_vars
[i
]))) continue;
1405 length
+= strlen(unix_vars
[i
]) + strlen(p
) + 2;
1409 if ((envp
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*envp
) + length
)))
1411 char **envptr
= envp
;
1412 char *dst
= (char *)(envp
+ count
);
1414 /* some variables must not be modified, so we get them directly from the unix env */
1415 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1417 if (!(p
= getenv(unix_vars
[i
]))) continue;
1418 *envptr
++ = strcpy( dst
, unix_vars
[i
] );
1421 dst
+= strlen(dst
) + 1;
1424 /* now put the Windows environment strings */
1425 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1427 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1428 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1429 if (!strncmp( p
, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1430 if (!strncmp( p
, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1431 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1433 *envptr
++ = strcpy( dst
, "WINE" );
1438 *envptr
++ = strcpy( dst
, p
);
1440 dst
+= strlen(dst
) + 1;
1444 HeapFree( GetProcessHeap(), 0, env
);
1449 /***********************************************************************
1452 * Fork and exec a new Unix binary, checking for errors.
1454 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
, const WCHAR
*env
,
1455 const char *newdir
, DWORD flags
, STARTUPINFOW
*startup
)
1457 int fd
[2], stdin_fd
= -1, stdout_fd
= -1, stderr_fd
= -1;
1459 char **argv
, **envp
;
1461 if (!env
) env
= GetEnvironmentStringsW();
1464 if (pipe2( fd
, O_CLOEXEC
) == -1)
1469 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1472 fcntl( fd
[0], F_SETFD
, FD_CLOEXEC
);
1473 fcntl( fd
[1], F_SETFD
, FD_CLOEXEC
);
1476 if (!(flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1478 HANDLE hstdin
, hstdout
, hstderr
;
1480 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1482 hstdin
= startup
->hStdInput
;
1483 hstdout
= startup
->hStdOutput
;
1484 hstderr
= startup
->hStdError
;
1488 hstdin
= GetStdHandle(STD_INPUT_HANDLE
);
1489 hstdout
= GetStdHandle(STD_OUTPUT_HANDLE
);
1490 hstderr
= GetStdHandle(STD_ERROR_HANDLE
);
1493 if (is_console_handle( hstdin
))
1494 hstdin
= wine_server_ptr_handle( console_handle_unmap( hstdin
));
1495 if (is_console_handle( hstdout
))
1496 hstdout
= wine_server_ptr_handle( console_handle_unmap( hstdout
));
1497 if (is_console_handle( hstderr
))
1498 hstderr
= wine_server_ptr_handle( console_handle_unmap( hstderr
));
1499 wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1500 wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1501 wine_server_handle_to_fd( hstderr
, FILE_WRITE_DATA
, &stderr_fd
, NULL
);
1504 argv
= build_argv( cmdline
, 0 );
1505 envp
= build_envp( env
);
1507 if (!(pid
= fork())) /* child */
1511 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1514 if (!(pid
= fork()))
1516 int fd
= open( "/dev/null", O_RDWR
);
1518 /* close stdin and stdout */
1526 else if (pid
!= -1) _exit(0); /* parent */
1532 dup2( stdin_fd
, 0 );
1535 if (stdout_fd
!= -1)
1537 dup2( stdout_fd
, 1 );
1540 if (stderr_fd
!= -1)
1542 dup2( stderr_fd
, 2 );
1547 /* Reset signals that we previously set to SIG_IGN */
1548 signal( SIGPIPE
, SIG_DFL
);
1549 signal( SIGCHLD
, SIG_DFL
);
1551 if (newdir
) chdir(newdir
);
1553 if (argv
&& envp
) execve( filename
, argv
, envp
);
1555 write( fd
[1], &err
, sizeof(err
) );
1558 HeapFree( GetProcessHeap(), 0, argv
);
1559 HeapFree( GetProcessHeap(), 0, envp
);
1560 if (stdin_fd
!= -1) close( stdin_fd
);
1561 if (stdout_fd
!= -1) close( stdout_fd
);
1562 if (stderr_fd
!= -1) close( stderr_fd
);
1564 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1569 if (pid
== -1) FILE_SetDosError();
1575 static inline DWORD
append_string( void **ptr
, const WCHAR
*str
)
1577 DWORD len
= strlenW( str
);
1578 memcpy( *ptr
, str
, len
* sizeof(WCHAR
) );
1579 *ptr
= (WCHAR
*)*ptr
+ len
;
1580 return len
* sizeof(WCHAR
);
1583 /***********************************************************************
1584 * create_startup_info
1586 static startup_info_t
*create_startup_info( LPCWSTR filename
, LPCWSTR cmdline
,
1587 LPCWSTR cur_dir
, LPWSTR env
, DWORD flags
,
1588 const STARTUPINFOW
*startup
, DWORD
*info_size
)
1590 const RTL_USER_PROCESS_PARAMETERS
*cur_params
;
1592 startup_info_t
*info
;
1595 UNICODE_STRING newdir
;
1596 WCHAR imagepath
[MAX_PATH
];
1597 HANDLE hstdin
, hstdout
, hstderr
;
1599 if(!GetLongPathNameW( filename
, imagepath
, MAX_PATH
))
1600 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1601 if(!GetFullPathNameW( imagepath
, MAX_PATH
, imagepath
, NULL
))
1602 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1604 cur_params
= NtCurrentTeb()->Peb
->ProcessParameters
;
1606 newdir
.Buffer
= NULL
;
1609 if (RtlDosPathNameToNtPathName_U( cur_dir
, &newdir
, NULL
, NULL
))
1610 cur_dir
= newdir
.Buffer
+ 4; /* skip \??\ prefix */
1616 if (NtCurrentTeb()->Tib
.SubSystemTib
) /* FIXME: hack */
1617 cur_dir
= ((WIN16_SUBSYSTEM_TIB
*)NtCurrentTeb()->Tib
.SubSystemTib
)->curdir
.DosPath
.Buffer
;
1619 cur_dir
= cur_params
->CurrentDirectory
.DosPath
.Buffer
;
1621 title
= startup
->lpTitle
? startup
->lpTitle
: imagepath
;
1623 size
= sizeof(*info
);
1624 size
+= strlenW( cur_dir
) * sizeof(WCHAR
);
1625 size
+= cur_params
->DllPath
.Length
;
1626 size
+= strlenW( imagepath
) * sizeof(WCHAR
);
1627 size
+= strlenW( cmdline
) * sizeof(WCHAR
);
1628 size
+= strlenW( title
) * sizeof(WCHAR
);
1629 if (startup
->lpDesktop
) size
+= strlenW( startup
->lpDesktop
) * sizeof(WCHAR
);
1630 /* FIXME: shellinfo */
1631 if (startup
->lpReserved2
&& startup
->cbReserved2
) size
+= startup
->cbReserved2
;
1632 size
= (size
+ 1) & ~1;
1635 if (!(info
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, size
))) goto done
;
1637 info
->console_flags
= cur_params
->ConsoleFlags
;
1638 if (flags
& CREATE_NEW_PROCESS_GROUP
) info
->console_flags
= 1;
1639 if (flags
& CREATE_NEW_CONSOLE
) info
->console
= wine_server_obj_handle(KERNEL32_CONSOLE_ALLOC
);
1641 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1643 hstdin
= startup
->hStdInput
;
1644 hstdout
= startup
->hStdOutput
;
1645 hstderr
= startup
->hStdError
;
1649 hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1650 hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1651 hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1653 info
->hstdin
= wine_server_obj_handle( hstdin
);
1654 info
->hstdout
= wine_server_obj_handle( hstdout
);
1655 info
->hstderr
= wine_server_obj_handle( hstderr
);
1656 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1658 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1659 if (is_console_handle(hstdin
)) info
->hstdin
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1660 if (is_console_handle(hstdout
)) info
->hstdout
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1661 if (is_console_handle(hstderr
)) info
->hstderr
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1665 if (is_console_handle(hstdin
)) info
->hstdin
= console_handle_unmap(hstdin
);
1666 if (is_console_handle(hstdout
)) info
->hstdout
= console_handle_unmap(hstdout
);
1667 if (is_console_handle(hstderr
)) info
->hstderr
= console_handle_unmap(hstderr
);
1670 info
->x
= startup
->dwX
;
1671 info
->y
= startup
->dwY
;
1672 info
->xsize
= startup
->dwXSize
;
1673 info
->ysize
= startup
->dwYSize
;
1674 info
->xchars
= startup
->dwXCountChars
;
1675 info
->ychars
= startup
->dwYCountChars
;
1676 info
->attribute
= startup
->dwFillAttribute
;
1677 info
->flags
= startup
->dwFlags
;
1678 info
->show
= startup
->wShowWindow
;
1681 info
->curdir_len
= append_string( &ptr
, cur_dir
);
1682 info
->dllpath_len
= cur_params
->DllPath
.Length
;
1683 memcpy( ptr
, cur_params
->DllPath
.Buffer
, cur_params
->DllPath
.Length
);
1684 ptr
= (char *)ptr
+ cur_params
->DllPath
.Length
;
1685 info
->imagepath_len
= append_string( &ptr
, imagepath
);
1686 info
->cmdline_len
= append_string( &ptr
, cmdline
);
1687 info
->title_len
= append_string( &ptr
, title
);
1688 if (startup
->lpDesktop
) info
->desktop_len
= append_string( &ptr
, startup
->lpDesktop
);
1689 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1691 info
->runtime_len
= startup
->cbReserved2
;
1692 memcpy( ptr
, startup
->lpReserved2
, startup
->cbReserved2
);
1696 RtlFreeUnicodeString( &newdir
);
1700 /***********************************************************************
1701 * get_alternate_loader
1703 * Get the name of the alternate (32 or 64 bit) Wine loader.
1705 static const char *get_alternate_loader( char **ret_env
)
1708 const char *loader
= NULL
;
1709 const char *loader_env
= getenv( "WINELOADER" );
1713 if (wine_get_build_dir()) loader
= is_win64
? "loader/wine" : "server/../loader/wine64";
1717 int len
= strlen( loader_env
);
1720 if (!(env
= HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len
+ 2 ))) return NULL
;
1721 strcpy( env
, "WINELOADER=" );
1722 strcat( env
, loader_env
);
1723 strcat( env
, "64" );
1727 if (!(env
= HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len
))) return NULL
;
1728 strcpy( env
, "WINELOADER=" );
1729 strcat( env
, loader_env
);
1730 len
+= sizeof("WINELOADER=") - 1;
1731 if (!strcmp( env
+ len
- 2, "64" )) env
[len
- 2] = 0;
1735 if ((loader
= strrchr( env
, '/' ))) loader
++;
1740 if (!loader
) loader
= is_win64
? "wine" : "wine64";
1745 /***********************************************************************
1746 * terminate_main_thread
1748 * On some versions of Mac OS X, the execve system call fails with
1749 * ENOTSUP if the process has multiple threads. Wine is always multi-
1750 * threaded on Mac OS X because it specifically reserves the main thread
1751 * for use by the system frameworks (see apple_main_thread() in
1752 * libs/wine/loader.c). So, when we need to exec without first forking,
1753 * we need to terminate the main thread first. We do this by installing
1754 * a custom run loop source onto the main run loop and signaling it.
1755 * The source's "perform" callback is pthread_exit and it will be
1756 * executed on the main thread, terminating it.
1758 * Returns TRUE if there's still hope the main thread has terminated or
1759 * will soon. Return FALSE if we've given up.
1761 static BOOL
terminate_main_thread(void)
1767 CFRunLoopSourceContext source_context
= { 0 };
1768 CFRunLoopSourceRef source
;
1770 source_context
.perform
= pthread_exit
;
1771 if (!(source
= CFRunLoopSourceCreate( NULL
, 0, &source_context
)))
1774 CFRunLoopAddSource( CFRunLoopGetMain(), source
, kCFRunLoopCommonModes
);
1775 CFRunLoopSourceSignal( source
);
1776 CFRunLoopWakeUp( CFRunLoopGetMain() );
1777 CFRelease( source
);
1785 usleep(delayms
* 1000);
1792 /***********************************************************************
1795 static pid_t
exec_loader( LPCWSTR cmd_line
, unsigned int flags
, int socketfd
,
1796 int stdin_fd
, int stdout_fd
, const char *unixdir
, char *winedebug
,
1797 const struct binary_info
*binary_info
, int exec_only
)
1800 char *wineloader
= NULL
;
1801 const char *loader
= NULL
;
1804 argv
= build_argv( cmd_line
, 1 );
1806 if (!is_win64
^ !(binary_info
->flags
& BINARY_FLAG_64BIT
))
1807 loader
= get_alternate_loader( &wineloader
);
1809 if (exec_only
|| !(pid
= fork())) /* child */
1811 char preloader_reserve
[64], socket_env
[64];
1813 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1815 if (!(pid
= fork()))
1817 int fd
= open( "/dev/null", O_RDWR
);
1819 /* close stdin and stdout */
1827 else if (pid
!= -1) _exit(0); /* parent */
1831 if (stdin_fd
!= -1) dup2( stdin_fd
, 0 );
1832 if (stdout_fd
!= -1) dup2( stdout_fd
, 1 );
1835 if (stdin_fd
!= -1) close( stdin_fd
);
1836 if (stdout_fd
!= -1) close( stdout_fd
);
1838 /* Reset signals that we previously set to SIG_IGN */
1839 signal( SIGPIPE
, SIG_DFL
);
1840 signal( SIGCHLD
, SIG_DFL
);
1842 sprintf( socket_env
, "WINESERVERSOCKET=%u", socketfd
);
1843 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx",
1844 (unsigned long)binary_info
->res_start
, (unsigned long)binary_info
->res_end
);
1846 putenv( preloader_reserve
);
1847 putenv( socket_env
);
1848 if (winedebug
) putenv( winedebug
);
1849 if (wineloader
) putenv( wineloader
);
1850 if (unixdir
) chdir(unixdir
);
1856 wine_exec_wine_binary( loader
, argv
, getenv("WINELOADER") );
1859 while (errno
== ENOTSUP
&& exec_only
&& terminate_main_thread());
1866 HeapFree( GetProcessHeap(), 0, wineloader
);
1867 HeapFree( GetProcessHeap(), 0, argv
);
1871 /***********************************************************************
1874 * Create a new process. If hFile is a valid handle we have an exe
1875 * file, otherwise it is a Winelib app.
1877 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1878 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1879 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1880 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1881 const struct binary_info
*binary_info
, int exec_only
)
1883 BOOL ret
, success
= FALSE
;
1884 HANDLE process_info
;
1886 char *winedebug
= NULL
;
1887 startup_info_t
*startup_info
;
1888 DWORD startup_info_size
;
1889 int socketfd
[2], stdin_fd
= -1, stdout_fd
= -1;
1893 if (!is_win64
&& !is_wow64
&& (binary_info
->flags
& BINARY_FLAG_64BIT
))
1895 ERR( "starting 64-bit process %s not supported in 32-bit wineprefix\n", debugstr_w(filename
) );
1896 SetLastError( ERROR_BAD_EXE_FORMAT
);
1900 /* create the socket for the new process */
1902 if (socketpair( PF_UNIX
, SOCK_STREAM
, 0, socketfd
) == -1)
1904 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1908 if (exec_only
) /* things are much simpler in this case */
1910 wine_server_send_fd( socketfd
[1] );
1911 close( socketfd
[1] );
1912 SERVER_START_REQ( new_process
)
1914 req
->create_flags
= flags
;
1915 req
->socket_fd
= socketfd
[1];
1916 req
->exe_file
= wine_server_obj_handle( hFile
);
1917 ret
= !wine_server_call_err( req
);
1921 if (ret
) exec_loader( cmd_line
, flags
, socketfd
[0], stdin_fd
, stdout_fd
, unixdir
,
1922 winedebug
, binary_info
, TRUE
);
1924 close( socketfd
[0] );
1928 RtlAcquirePebLock();
1930 if (!(startup_info
= create_startup_info( filename
, cmd_line
, cur_dir
, env
, flags
, startup
,
1931 &startup_info_size
)))
1933 RtlReleasePebLock();
1934 close( socketfd
[0] );
1935 close( socketfd
[1] );
1938 if (!env
) env
= NtCurrentTeb()->Peb
->ProcessParameters
->Environment
;
1942 static const WCHAR WINEDEBUG
[] = {'W','I','N','E','D','E','B','U','G','=',0};
1943 if (!winedebug
&& !strncmpW( env_end
, WINEDEBUG
, sizeof(WINEDEBUG
)/sizeof(WCHAR
) - 1 ))
1945 DWORD len
= WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, NULL
, 0, NULL
, NULL
);
1946 if ((winedebug
= HeapAlloc( GetProcessHeap(), 0, len
)))
1947 WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, winedebug
, len
, NULL
, NULL
);
1949 env_end
+= strlenW(env_end
) + 1;
1953 wine_server_send_fd( socketfd
[1] );
1954 close( socketfd
[1] );
1956 /* create the process on the server side */
1958 SERVER_START_REQ( new_process
)
1960 req
->inherit_all
= inherit
;
1961 req
->create_flags
= flags
;
1962 req
->socket_fd
= socketfd
[1];
1963 req
->exe_file
= wine_server_obj_handle( hFile
);
1964 req
->process_access
= PROCESS_ALL_ACCESS
;
1965 req
->process_attr
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1966 req
->thread_access
= THREAD_ALL_ACCESS
;
1967 req
->thread_attr
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1968 req
->info_size
= startup_info_size
;
1970 wine_server_add_data( req
, startup_info
, startup_info_size
);
1971 wine_server_add_data( req
, env
, (env_end
- env
) * sizeof(WCHAR
) );
1972 if ((ret
= !wine_server_call_err( req
)))
1974 info
->dwProcessId
= (DWORD
)reply
->pid
;
1975 info
->dwThreadId
= (DWORD
)reply
->tid
;
1976 info
->hProcess
= wine_server_ptr_handle( reply
->phandle
);
1977 info
->hThread
= wine_server_ptr_handle( reply
->thandle
);
1979 process_info
= wine_server_ptr_handle( reply
->info
);
1983 RtlReleasePebLock();
1986 close( socketfd
[0] );
1987 HeapFree( GetProcessHeap(), 0, startup_info
);
1988 HeapFree( GetProcessHeap(), 0, winedebug
);
1992 if (!(flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1994 if (startup_info
->hstdin
)
1995 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdin
),
1996 FILE_READ_DATA
, &stdin_fd
, NULL
);
1997 if (startup_info
->hstdout
)
1998 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdout
),
1999 FILE_WRITE_DATA
, &stdout_fd
, NULL
);
2001 HeapFree( GetProcessHeap(), 0, startup_info
);
2003 /* create the child process */
2005 pid
= exec_loader( cmd_line
, flags
, socketfd
[0], stdin_fd
, stdout_fd
, unixdir
,
2006 winedebug
, binary_info
, FALSE
);
2008 if (stdin_fd
!= -1) close( stdin_fd
);
2009 if (stdout_fd
!= -1) close( stdout_fd
);
2010 close( socketfd
[0] );
2011 HeapFree( GetProcessHeap(), 0, winedebug
);
2018 /* wait for the new process info to be ready */
2020 WaitForSingleObject( process_info
, INFINITE
);
2021 SERVER_START_REQ( get_new_process_info
)
2023 req
->info
= wine_server_obj_handle( process_info
);
2024 wine_server_call( req
);
2025 success
= reply
->success
;
2026 err
= reply
->exit_code
;
2032 SetLastError( err
? err
: ERROR_INTERNAL_ERROR
);
2035 CloseHandle( process_info
);
2039 CloseHandle( process_info
);
2040 CloseHandle( info
->hProcess
);
2041 CloseHandle( info
->hThread
);
2042 info
->hProcess
= info
->hThread
= 0;
2043 info
->dwProcessId
= info
->dwThreadId
= 0;
2048 /***********************************************************************
2049 * create_vdm_process
2051 * Create a new VDM process for a 16-bit or DOS application.
2053 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
2054 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
2055 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
2056 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
2057 const struct binary_info
*binary_info
, int exec_only
)
2059 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
2062 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
2063 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
2067 SetLastError( ERROR_OUTOFMEMORY
);
2070 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
2071 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
2072 flags
, startup
, info
, unixdir
, binary_info
, exec_only
);
2073 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
2078 /***********************************************************************
2079 * create_cmd_process
2081 * Create a new cmd shell process for a .BAT file.
2083 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
2084 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
2085 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
2086 LPPROCESS_INFORMATION info
)
2089 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
2090 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
2091 WCHAR comspec
[MAX_PATH
];
2095 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
2097 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
2098 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
2101 strcpyW( newcmdline
, comspec
);
2102 strcatW( newcmdline
, slashcW
);
2103 strcatW( newcmdline
, cmd_line
);
2104 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
2105 flags
, env
, cur_dir
, startup
, info
);
2106 HeapFree( GetProcessHeap(), 0, newcmdline
);
2111 /*************************************************************************
2114 * Helper for CreateProcess: retrieve the file name to load from the
2115 * app name and command line. Store the file name in buffer, and
2116 * return a possibly modified command line.
2117 * Also returns a handle to the opened file if it's a Windows binary.
2119 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
2120 int buflen
, HANDLE
*handle
, struct binary_info
*binary_info
)
2122 static const WCHAR quotesW
[] = {'"','%','s','"',0};
2124 WCHAR
*name
, *pos
, *first_space
, *ret
= NULL
;
2127 /* if we have an app name, everything is easy */
2131 /* use the unmodified app name as file name */
2132 lstrcpynW( buffer
, appname
, buflen
);
2133 *handle
= open_exe_file( buffer
, binary_info
);
2134 if (!(ret
= cmdline
) || !cmdline
[0])
2136 /* no command-line, create one */
2137 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
2138 sprintfW( ret
, quotesW
, appname
);
2143 /* first check for a quoted file name */
2145 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
2147 int len
= p
- cmdline
- 1;
2148 /* extract the quoted portion as file name */
2149 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
2150 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
2153 if (!find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
2155 if (!get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
)) goto done
;
2158 ret
= cmdline
; /* no change necessary */
2162 /* now try the command-line word by word */
2164 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
2172 while (*p
&& *p
!= ' ' && *p
!= '\t') *pos
++ = *p
++;
2174 if (find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
2179 if (!first_space
) first_space
= pos
;
2180 if (!(*pos
++ = *p
++)) break;
2185 if (first_space
) *first_space
= 0; /* try only the first word as a builtin */
2186 if (get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
))
2191 else SetLastError( ERROR_FILE_NOT_FOUND
);
2193 else if (first_space
) /* build a new command-line with quotes */
2195 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
2197 sprintfW( ret
, quotesW
, name
);
2202 HeapFree( GetProcessHeap(), 0, name
);
2207 /* Steam hotpatches CreateProcessA and W, so to prevent it from crashing use an internal function */
2208 static BOOL
create_process_impl( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2209 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
2210 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
2211 LPPROCESS_INFORMATION info
)
2215 char *unixdir
= NULL
;
2216 WCHAR name
[MAX_PATH
];
2217 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
2218 struct binary_info binary_info
;
2220 /* Process the AppName and/or CmdLine to get module name and path */
2222 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
2224 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
)/sizeof(WCHAR
),
2225 &hFile
, &binary_info
)))
2227 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
2229 /* Warn if unsupported features are used */
2231 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
2232 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
2233 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
2234 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
2235 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name
), flags
);
2239 if (!(unixdir
= wine_get_unix_file_name( cur_dir
)))
2241 SetLastError(ERROR_DIRECTORY
);
2247 WCHAR buf
[MAX_PATH
];
2248 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
2251 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
2256 while (*p
) p
+= strlen(p
) + 1;
2257 p
++; /* final null */
2258 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
2259 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
2260 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
2261 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2264 info
->hThread
= info
->hProcess
= 0;
2265 info
->dwProcessId
= info
->dwThreadId
= 0;
2267 if (binary_info
.flags
& BINARY_FLAG_DLL
)
2269 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
2270 SetLastError( ERROR_BAD_EXE_FORMAT
);
2272 else switch (binary_info
.type
)
2275 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2276 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32,
2277 binary_info
.res_start
, binary_info
.res_end
);
2278 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2279 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2284 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2285 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2286 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2288 case BINARY_UNIX_LIB
:
2289 TRACE( "starting %s as %d-bit Winelib app\n",
2290 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32 );
2291 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2292 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2294 case BINARY_UNKNOWN
:
2295 /* check for .com or .bat extension */
2296 if ((p
= strrchrW( name
, '.' )))
2298 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
2300 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
2301 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2302 inherit
, flags
, startup_info
, info
, unixdir
,
2303 &binary_info
, FALSE
);
2306 if (!strcmpiW( p
, batW
) || !strcmpiW( p
, cmdW
) )
2308 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
2309 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2310 inherit
, flags
, startup_info
, info
);
2315 case BINARY_UNIX_EXE
:
2317 /* unknown file, try as unix executable */
2320 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
2322 if ((unix_name
= wine_get_unix_file_name( name
)))
2324 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
, flags
, startup_info
) != -1);
2325 HeapFree( GetProcessHeap(), 0, unix_name
);
2330 if (hFile
) CloseHandle( hFile
);
2333 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
2334 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
2335 HeapFree( GetProcessHeap(), 0, unixdir
);
2337 TRACE( "started process pid %04x tid %04x\n", info
->dwProcessId
, info
->dwThreadId
);
2342 /**********************************************************************
2343 * CreateProcessA (KERNEL32.@)
2345 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2346 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
2347 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
2348 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
2351 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
2352 UNICODE_STRING desktopW
, titleW
;
2355 desktopW
.Buffer
= NULL
;
2356 titleW
.Buffer
= NULL
;
2357 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
2358 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
2359 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
2361 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
2362 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
2364 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
2365 infoW
.lpDesktop
= desktopW
.Buffer
;
2366 infoW
.lpTitle
= titleW
.Buffer
;
2368 if (startup_info
->lpReserved
)
2369 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2370 debugstr_a(startup_info
->lpReserved
));
2372 ret
= create_process_impl( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
2373 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
2375 HeapFree( GetProcessHeap(), 0, app_nameW
);
2376 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
2377 HeapFree( GetProcessHeap(), 0, cur_dirW
);
2378 RtlFreeUnicodeString( &desktopW
);
2379 RtlFreeUnicodeString( &titleW
);
2384 /**********************************************************************
2385 * CreateProcessW (KERNEL32.@)
2387 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2388 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
2389 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
2390 LPPROCESS_INFORMATION info
)
2392 return create_process_impl( app_name
, cmd_line
, process_attr
, thread_attr
,
2393 inherit
, flags
, env
, cur_dir
, startup_info
, info
);
2397 /**********************************************************************
2400 static void exec_process( LPCWSTR name
)
2404 STARTUPINFOW startup_info
;
2405 PROCESS_INFORMATION info
;
2406 struct binary_info binary_info
;
2408 hFile
= open_exe_file( name
, &binary_info
);
2409 if (!hFile
|| hFile
== INVALID_HANDLE_VALUE
) return;
2411 memset( &startup_info
, 0, sizeof(startup_info
) );
2412 startup_info
.cb
= sizeof(startup_info
);
2414 /* Determine executable type */
2416 if (binary_info
.flags
& BINARY_FLAG_DLL
) return;
2417 switch (binary_info
.type
)
2420 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2421 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32,
2422 binary_info
.res_start
, binary_info
.res_end
);
2423 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2424 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2426 case BINARY_UNIX_LIB
:
2427 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
2428 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2429 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2431 case BINARY_UNKNOWN
:
2432 /* check for .com or .pif extension */
2433 if (!(p
= strrchrW( name
, '.' ))) break;
2434 if (strcmpiW( p
, comW
) && strcmpiW( p
, pifW
)) break;
2439 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2440 create_vdm_process( name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2441 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2446 CloseHandle( hFile
);
2450 /***********************************************************************
2453 * Wrapper to call WaitForInputIdle USER function
2455 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2457 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2459 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2462 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2463 if (ptr
) return ptr( process
, timeout
);
2469 /***********************************************************************
2470 * WinExec (KERNEL32.@)
2472 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2474 PROCESS_INFORMATION info
;
2475 STARTUPINFOA startup
;
2479 memset( &startup
, 0, sizeof(startup
) );
2480 startup
.cb
= sizeof(startup
);
2481 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2482 startup
.wShowWindow
= nCmdShow
;
2484 /* cmdline needs to be writable for CreateProcess */
2485 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2486 strcpy( cmdline
, lpCmdLine
);
2488 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2489 0, NULL
, NULL
, &startup
, &info
))
2491 /* Give 30 seconds to the app to come up */
2492 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2493 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2495 /* Close off the handles */
2496 CloseHandle( info
.hThread
);
2497 CloseHandle( info
.hProcess
);
2499 else if ((ret
= GetLastError()) >= 32)
2501 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2504 HeapFree( GetProcessHeap(), 0, cmdline
);
2509 /**********************************************************************
2510 * LoadModule (KERNEL32.@)
2512 DWORD WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2514 LOADPARMS32
*params
= paramBlock
;
2515 PROCESS_INFORMATION info
;
2516 STARTUPINFOA startup
;
2519 char filename
[MAX_PATH
];
2522 if (!name
) return ERROR_FILE_NOT_FOUND
;
2524 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2525 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2526 return GetLastError();
2528 len
= (BYTE
)params
->lpCmdLine
[0];
2529 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2530 return ERROR_NOT_ENOUGH_MEMORY
;
2532 strcpy( cmdline
, filename
);
2533 p
= cmdline
+ strlen(cmdline
);
2535 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2538 memset( &startup
, 0, sizeof(startup
) );
2539 startup
.cb
= sizeof(startup
);
2540 if (params
->lpCmdShow
)
2542 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2543 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2546 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2547 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2549 /* Give 30 seconds to the app to come up */
2550 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2551 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2553 /* Close off the handles */
2554 CloseHandle( info
.hThread
);
2555 CloseHandle( info
.hProcess
);
2557 else if ((ret
= GetLastError()) >= 32)
2559 FIXME("Strange error set by CreateProcess: %u\n", ret
);
2563 HeapFree( GetProcessHeap(), 0, cmdline
);
2568 /******************************************************************************
2569 * TerminateProcess (KERNEL32.@)
2571 * Terminates a process.
2574 * handle [I] Process to terminate.
2575 * exit_code [I] Exit code.
2579 * Failure: FALSE, check GetLastError().
2581 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2583 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2584 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2588 /***********************************************************************
2589 * ExitProcess (KERNEL32.@)
2591 * Exits the current process.
2594 * status [I] Status code to exit with.
2600 __ASM_STDCALL_FUNC( ExitProcess
, 4, /* Shrinker depend on this particular ExitProcess implementation */
2602 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2603 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2604 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2606 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2610 void WINAPI
process_ExitProcess( DWORD status
)
2612 LdrShutdownProcess();
2613 NtTerminateProcess(GetCurrentProcess(), status
);
2619 void WINAPI
ExitProcess( DWORD status
)
2621 LdrShutdownProcess();
2622 NtTerminateProcess(GetCurrentProcess(), status
);
2628 /***********************************************************************
2629 * GetExitCodeProcess [KERNEL32.@]
2631 * Gets termination status of specified process.
2634 * hProcess [in] Handle to the process.
2635 * lpExitCode [out] Address to receive termination status.
2641 BOOL WINAPI
GetExitCodeProcess( HANDLE hProcess
, LPDWORD lpExitCode
)
2644 PROCESS_BASIC_INFORMATION pbi
;
2646 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2648 if (status
== STATUS_SUCCESS
)
2650 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2653 SetLastError( RtlNtStatusToDosError(status
) );
2658 /***********************************************************************
2659 * SetErrorMode (KERNEL32.@)
2661 UINT WINAPI
SetErrorMode( UINT mode
)
2665 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode
,
2666 &old
, sizeof(old
), NULL
);
2667 NtSetInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode
,
2668 &mode
, sizeof(mode
) );
2672 /***********************************************************************
2673 * GetErrorMode (KERNEL32.@)
2675 UINT WINAPI
GetErrorMode( void )
2679 NtQueryInformationProcess( GetCurrentProcess(), ProcessDefaultHardErrorMode
,
2680 &mode
, sizeof(mode
), NULL
);
2684 /**********************************************************************
2685 * TlsAlloc [KERNEL32.@]
2687 * Allocates a thread local storage index.
2690 * Success: TLS index.
2691 * Failure: 0xFFFFFFFF
2693 DWORD WINAPI
TlsAlloc( void )
2696 PEB
* const peb
= NtCurrentTeb()->Peb
;
2698 RtlAcquirePebLock();
2699 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 0 );
2700 if (index
!= ~0U) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2703 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2706 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2707 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2708 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2710 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2712 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2716 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2717 index
+= TLS_MINIMUM_AVAILABLE
;
2720 else SetLastError( ERROR_NO_MORE_ITEMS
);
2722 RtlReleasePebLock();
2727 /**********************************************************************
2728 * TlsFree [KERNEL32.@]
2730 * Releases a thread local storage index, making it available for reuse.
2733 * index [in] TLS index to free.
2739 BOOL WINAPI
TlsFree( DWORD index
)
2743 RtlAcquirePebLock();
2744 if (index
>= TLS_MINIMUM_AVAILABLE
)
2746 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2747 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2751 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2752 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2754 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2755 else SetLastError( ERROR_INVALID_PARAMETER
);
2756 RtlReleasePebLock();
2761 /**********************************************************************
2762 * TlsGetValue [KERNEL32.@]
2764 * Gets value in a thread's TLS slot.
2767 * index [in] TLS index to retrieve value for.
2770 * Success: Value stored in calling thread's TLS slot for index.
2771 * Failure: 0 and GetLastError() returns NO_ERROR.
2773 LPVOID WINAPI
TlsGetValue( DWORD index
)
2777 if (index
< TLS_MINIMUM_AVAILABLE
)
2779 ret
= NtCurrentTeb()->TlsSlots
[index
];
2783 index
-= TLS_MINIMUM_AVAILABLE
;
2784 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2786 SetLastError( ERROR_INVALID_PARAMETER
);
2789 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2790 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2792 SetLastError( ERROR_SUCCESS
);
2797 /**********************************************************************
2798 * TlsSetValue [KERNEL32.@]
2800 * Stores a value in the thread's TLS slot.
2803 * index [in] TLS index to set value for.
2804 * value [in] Value to be stored.
2810 BOOL WINAPI
TlsSetValue( DWORD index
, LPVOID value
)
2812 if (index
< TLS_MINIMUM_AVAILABLE
)
2814 NtCurrentTeb()->TlsSlots
[index
] = value
;
2818 index
-= TLS_MINIMUM_AVAILABLE
;
2819 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2821 SetLastError( ERROR_INVALID_PARAMETER
);
2824 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2825 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2826 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2828 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2831 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2837 /***********************************************************************
2838 * GetProcessFlags (KERNEL32.@)
2840 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2842 IMAGE_NT_HEADERS
*nt
;
2845 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2847 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2849 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2850 flags
|= PDB32_CONSOLE_PROC
;
2852 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2853 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2858 /*********************************************************************
2859 * OpenProcess (KERNEL32.@)
2861 * Opens a handle to a process.
2864 * access [I] Desired access rights assigned to the returned handle.
2865 * inherit [I] Determines whether or not child processes will inherit the handle.
2866 * id [I] Process identifier of the process to get a handle to.
2869 * Success: Valid handle to the specified process.
2870 * Failure: NULL, check GetLastError().
2872 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2876 OBJECT_ATTRIBUTES attr
;
2879 cid
.UniqueProcess
= ULongToHandle(id
);
2880 cid
.UniqueThread
= 0; /* FIXME ? */
2882 attr
.Length
= sizeof(OBJECT_ATTRIBUTES
);
2883 attr
.RootDirectory
= NULL
;
2884 attr
.Attributes
= inherit
? OBJ_INHERIT
: 0;
2885 attr
.SecurityDescriptor
= NULL
;
2886 attr
.SecurityQualityOfService
= NULL
;
2887 attr
.ObjectName
= NULL
;
2889 if (GetVersion() & 0x80000000) access
= PROCESS_ALL_ACCESS
;
2891 status
= NtOpenProcess(&handle
, access
, &attr
, &cid
);
2892 if (status
!= STATUS_SUCCESS
)
2894 SetLastError( RtlNtStatusToDosError(status
) );
2901 /*********************************************************************
2902 * GetProcessId (KERNEL32.@)
2904 * Gets the a unique identifier of a process.
2907 * hProcess [I] Handle to the process.
2911 * Failure: FALSE, check GetLastError().
2915 * The identifier is unique only on the machine and only until the process
2916 * exits (including system shutdown).
2918 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2921 PROCESS_BASIC_INFORMATION pbi
;
2923 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2925 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2926 SetLastError( RtlNtStatusToDosError(status
) );
2931 /*********************************************************************
2932 * CloseHandle (KERNEL32.@)
2937 * handle [I] Handle to close.
2941 * Failure: FALSE, check GetLastError().
2943 BOOL WINAPI
CloseHandle( HANDLE handle
)
2947 /* stdio handles need special treatment */
2948 if (handle
== (HANDLE
)STD_INPUT_HANDLE
)
2949 handle
= InterlockedExchangePointer( &NtCurrentTeb()->Peb
->ProcessParameters
->hStdInput
, 0 );
2950 else if (handle
== (HANDLE
)STD_OUTPUT_HANDLE
)
2951 handle
= InterlockedExchangePointer( &NtCurrentTeb()->Peb
->ProcessParameters
->hStdOutput
, 0 );
2952 else if (handle
== (HANDLE
)STD_ERROR_HANDLE
)
2953 handle
= InterlockedExchangePointer( &NtCurrentTeb()->Peb
->ProcessParameters
->hStdError
, 0 );
2955 if (is_console_handle(handle
))
2956 return CloseConsoleHandle(handle
);
2958 status
= NtClose( handle
);
2959 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2964 /*********************************************************************
2965 * GetHandleInformation (KERNEL32.@)
2967 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2969 OBJECT_DATA_INFORMATION info
;
2970 NTSTATUS status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
);
2972 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2976 if (info
.InheritHandle
) *flags
|= HANDLE_FLAG_INHERIT
;
2977 if (info
.ProtectFromClose
) *flags
|= HANDLE_FLAG_PROTECT_FROM_CLOSE
;
2983 /*********************************************************************
2984 * SetHandleInformation (KERNEL32.@)
2986 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2988 OBJECT_DATA_INFORMATION info
;
2991 /* if not setting both fields, retrieve current value first */
2992 if ((mask
& (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
)) !=
2993 (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
))
2995 if ((status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
)))
2997 SetLastError( RtlNtStatusToDosError(status
) );
3001 if (mask
& HANDLE_FLAG_INHERIT
)
3002 info
.InheritHandle
= (flags
& HANDLE_FLAG_INHERIT
) != 0;
3003 if (mask
& HANDLE_FLAG_PROTECT_FROM_CLOSE
)
3004 info
.ProtectFromClose
= (flags
& HANDLE_FLAG_PROTECT_FROM_CLOSE
) != 0;
3006 status
= NtSetInformationObject( handle
, ObjectDataInformation
, &info
, sizeof(info
) );
3007 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3012 /*********************************************************************
3013 * DuplicateHandle (KERNEL32.@)
3015 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
3016 HANDLE dest_process
, HANDLE
*dest
,
3017 DWORD access
, BOOL inherit
, DWORD options
)
3021 if (is_console_handle(source
))
3023 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
3024 if (source_process
!= dest_process
||
3025 source_process
!= GetCurrentProcess())
3027 SetLastError(ERROR_INVALID_PARAMETER
);
3030 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
3031 return (*dest
!= INVALID_HANDLE_VALUE
);
3033 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
3034 access
, inherit
? OBJ_INHERIT
: 0, options
);
3035 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3040 /***********************************************************************
3041 * ConvertToGlobalHandle (KERNEL32.@)
3043 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
3045 HANDLE ret
= INVALID_HANDLE_VALUE
;
3046 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
3047 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
3052 /***********************************************************************
3053 * SetHandleContext (KERNEL32.@)
3055 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
3057 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
3058 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
3059 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3064 /***********************************************************************
3065 * GetHandleContext (KERNEL32.@)
3067 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
3069 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
3070 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
3071 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3076 /***********************************************************************
3077 * CreateSocketHandle (KERNEL32.@)
3079 HANDLE WINAPI
CreateSocketHandle(void)
3081 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
3082 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
3083 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3084 return INVALID_HANDLE_VALUE
;
3088 /***********************************************************************
3089 * SetPriorityClass (KERNEL32.@)
3091 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
3094 PROCESS_PRIORITY_CLASS ppc
;
3096 ppc
.Foreground
= FALSE
;
3097 switch (priorityclass
)
3099 case IDLE_PRIORITY_CLASS
:
3100 ppc
.PriorityClass
= PROCESS_PRIOCLASS_IDLE
; break;
3101 case BELOW_NORMAL_PRIORITY_CLASS
:
3102 ppc
.PriorityClass
= PROCESS_PRIOCLASS_BELOW_NORMAL
; break;
3103 case NORMAL_PRIORITY_CLASS
:
3104 ppc
.PriorityClass
= PROCESS_PRIOCLASS_NORMAL
; break;
3105 case ABOVE_NORMAL_PRIORITY_CLASS
:
3106 ppc
.PriorityClass
= PROCESS_PRIOCLASS_ABOVE_NORMAL
; break;
3107 case HIGH_PRIORITY_CLASS
:
3108 ppc
.PriorityClass
= PROCESS_PRIOCLASS_HIGH
; break;
3109 case REALTIME_PRIORITY_CLASS
:
3110 ppc
.PriorityClass
= PROCESS_PRIOCLASS_REALTIME
; break;
3112 SetLastError(ERROR_INVALID_PARAMETER
);
3116 status
= NtSetInformationProcess(hprocess
, ProcessPriorityClass
,
3119 if (status
!= STATUS_SUCCESS
)
3121 SetLastError( RtlNtStatusToDosError(status
) );
3128 /***********************************************************************
3129 * GetPriorityClass (KERNEL32.@)
3131 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
3134 PROCESS_BASIC_INFORMATION pbi
;
3136 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
3138 if (status
!= STATUS_SUCCESS
)
3140 SetLastError( RtlNtStatusToDosError(status
) );
3143 switch (pbi
.BasePriority
)
3145 case PROCESS_PRIOCLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
3146 case PROCESS_PRIOCLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
3147 case PROCESS_PRIOCLASS_NORMAL
: return NORMAL_PRIORITY_CLASS
;
3148 case PROCESS_PRIOCLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
3149 case PROCESS_PRIOCLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
3150 case PROCESS_PRIOCLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
3152 SetLastError( ERROR_INVALID_PARAMETER
);
3157 /***********************************************************************
3158 * SetProcessAffinityMask (KERNEL32.@)
3160 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
3164 status
= NtSetInformationProcess(hProcess
, ProcessAffinityMask
,
3165 &affmask
, sizeof(DWORD_PTR
));
3168 SetLastError( RtlNtStatusToDosError(status
) );
3175 /**********************************************************************
3176 * GetProcessAffinityMask (KERNEL32.@)
3178 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
, PDWORD_PTR process_mask
, PDWORD_PTR system_mask
)
3180 NTSTATUS status
= STATUS_SUCCESS
;
3182 if (system_mask
) *system_mask
= (1 << NtCurrentTeb()->Peb
->NumberOfProcessors
) - 1;
3185 if ((status
= NtQueryInformationProcess( hProcess
, ProcessAffinityMask
,
3186 process_mask
, sizeof(*process_mask
), NULL
)))
3187 SetLastError( RtlNtStatusToDosError(status
) );
3193 /***********************************************************************
3194 * GetProcessVersion (KERNEL32.@)
3196 DWORD WINAPI
GetProcessVersion( DWORD pid
)
3200 PROCESS_BASIC_INFORMATION pbi
;
3203 IMAGE_DOS_HEADER dos
;
3204 IMAGE_NT_HEADERS nt
;
3207 if (!pid
|| pid
== GetCurrentProcessId())
3209 IMAGE_NT_HEADERS
*nt
;
3211 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
3212 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
3213 nt
->OptionalHeader
.MinorSubsystemVersion
);
3217 process
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
3218 if (!process
) return 0;
3220 status
= NtQueryInformationProcess(process
, ProcessBasicInformation
, &pbi
, sizeof(pbi
), NULL
);
3221 if (status
) goto err
;
3223 status
= NtReadVirtualMemory(process
, pbi
.PebBaseAddress
, &peb
, sizeof(peb
), &count
);
3224 if (status
|| count
!= sizeof(peb
)) goto err
;
3226 memset(&dos
, 0, sizeof(dos
));
3227 status
= NtReadVirtualMemory(process
, peb
.ImageBaseAddress
, &dos
, sizeof(dos
), &count
);
3228 if (status
|| count
!= sizeof(dos
)) goto err
;
3229 if (dos
.e_magic
!= IMAGE_DOS_SIGNATURE
) goto err
;
3231 memset(&nt
, 0, sizeof(nt
));
3232 status
= NtReadVirtualMemory(process
, (char *)peb
.ImageBaseAddress
+ dos
.e_lfanew
, &nt
, sizeof(nt
), &count
);
3233 if (status
|| count
!= sizeof(nt
)) goto err
;
3234 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) goto err
;
3236 ver
= MAKELONG(nt
.OptionalHeader
.MinorSubsystemVersion
, nt
.OptionalHeader
.MajorSubsystemVersion
);
3239 CloseHandle(process
);
3241 if (status
!= STATUS_SUCCESS
)
3242 SetLastError(RtlNtStatusToDosError(status
));
3248 /***********************************************************************
3249 * SetProcessWorkingSetSize [KERNEL32.@]
3250 * Sets the min/max working set sizes for a specified process.
3253 * hProcess [I] Handle to the process of interest
3254 * minset [I] Specifies minimum working set size
3255 * maxset [I] Specifies maximum working set size
3261 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
3264 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
3265 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
3266 /* Trim the working set to zero */
3267 /* Swap the process out of physical RAM */
3272 /***********************************************************************
3273 * K32EmptyWorkingSet (KERNEL32.@)
3275 BOOL WINAPI
K32EmptyWorkingSet(HANDLE hProcess
)
3277 return SetProcessWorkingSetSize(hProcess
, (SIZE_T
)-1, (SIZE_T
)-1);
3280 /***********************************************************************
3281 * GetProcessWorkingSetSize (KERNEL32.@)
3283 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
3286 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
3287 /* 32 MB working set size */
3288 if (minset
) *minset
= 32*1024*1024;
3289 if (maxset
) *maxset
= 32*1024*1024;
3294 /***********************************************************************
3295 * SetProcessShutdownParameters (KERNEL32.@)
3297 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
3299 FIXME("(%08x, %08x): partial stub.\n", level
, flags
);
3300 shutdown_flags
= flags
;
3301 shutdown_priority
= level
;
3306 /***********************************************************************
3307 * GetProcessShutdownParameters (KERNEL32.@)
3310 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
3312 *lpdwLevel
= shutdown_priority
;
3313 *lpdwFlags
= shutdown_flags
;
3318 /***********************************************************************
3319 * GetProcessPriorityBoost (KERNEL32.@)
3321 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
3323 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
3325 /* Report that no boost is present.. */
3326 *pDisablePriorityBoost
= FALSE
;
3331 /***********************************************************************
3332 * SetProcessPriorityBoost (KERNEL32.@)
3334 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
3336 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
3337 /* Say we can do it. I doubt the program will notice that we don't. */
3342 /***********************************************************************
3343 * ReadProcessMemory (KERNEL32.@)
3345 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
3346 SIZE_T
*bytes_read
)
3348 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
3349 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3354 /***********************************************************************
3355 * WriteProcessMemory (KERNEL32.@)
3357 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
3358 SIZE_T
*bytes_written
)
3360 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
3361 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3366 /****************************************************************************
3367 * FlushInstructionCache (KERNEL32.@)
3369 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
3372 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
3373 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3378 /******************************************************************
3379 * GetProcessIoCounters (KERNEL32.@)
3381 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
3385 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
3386 ioc
, sizeof(*ioc
), NULL
);
3387 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3391 /******************************************************************
3392 * GetProcessHandleCount (KERNEL32.@)
3394 BOOL WINAPI
GetProcessHandleCount(HANDLE hProcess
, DWORD
*cnt
)
3398 status
= NtQueryInformationProcess(hProcess
, ProcessHandleCount
,
3399 cnt
, sizeof(*cnt
), NULL
);
3400 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3404 /******************************************************************
3405 * QueryFullProcessImageNameA (KERNEL32.@)
3407 BOOL WINAPI
QueryFullProcessImageNameA(HANDLE hProcess
, DWORD dwFlags
, LPSTR lpExeName
, PDWORD pdwSize
)
3410 DWORD pdwSizeW
= *pdwSize
;
3411 LPWSTR lpExeNameW
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, *pdwSize
* sizeof(WCHAR
));
3413 retval
= QueryFullProcessImageNameW(hProcess
, dwFlags
, lpExeNameW
, &pdwSizeW
);
3416 retval
= (0 != WideCharToMultiByte(CP_ACP
, 0, lpExeNameW
, -1,
3417 lpExeName
, *pdwSize
, NULL
, NULL
));
3419 *pdwSize
= strlen(lpExeName
);
3421 HeapFree(GetProcessHeap(), 0, lpExeNameW
);
3425 /******************************************************************
3426 * QueryFullProcessImageNameW (KERNEL32.@)
3428 BOOL WINAPI
QueryFullProcessImageNameW(HANDLE hProcess
, DWORD dwFlags
, LPWSTR lpExeName
, PDWORD pdwSize
)
3430 BYTE buffer
[sizeof(UNICODE_STRING
) + MAX_PATH
*sizeof(WCHAR
)]; /* this buffer should be enough */
3431 UNICODE_STRING
*dynamic_buffer
= NULL
;
3432 UNICODE_STRING
*result
= NULL
;
3436 /* FIXME: On Windows, ProcessImageFileName return an NT path. In Wine it
3437 * is a DOS path and we depend on this. */
3438 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, buffer
,
3439 sizeof(buffer
) - sizeof(WCHAR
), &needed
);
3440 if (status
== STATUS_INFO_LENGTH_MISMATCH
)
3442 dynamic_buffer
= HeapAlloc(GetProcessHeap(), 0, needed
+ sizeof(WCHAR
));
3443 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, (LPBYTE
)dynamic_buffer
, needed
, &needed
);
3444 result
= dynamic_buffer
;
3447 result
= (PUNICODE_STRING
)buffer
;
3449 if (status
) goto cleanup
;
3451 if (dwFlags
& PROCESS_NAME_NATIVE
)
3455 DWORD ntlen
, devlen
;
3457 if (result
->Buffer
[1] != ':' || result
->Buffer
[0] < 'A' || result
->Buffer
[0] > 'Z')
3459 /* We cannot convert it to an NT device path so fail */
3460 status
= STATUS_NO_SUCH_DEVICE
;
3464 /* Find this drive's NT device path */
3465 drive
[0] = result
->Buffer
[0];
3468 if (!QueryDosDeviceW(drive
, device
, sizeof(device
)/sizeof(*device
)))
3470 status
= STATUS_NO_SUCH_DEVICE
;
3474 devlen
= lstrlenW(device
);
3475 ntlen
= devlen
+ (result
->Length
/sizeof(WCHAR
) - 2);
3476 if (ntlen
+ 1 > *pdwSize
)
3478 SetLastError(ERROR_INSUFFICIENT_BUFFER
);
3483 memcpy(lpExeName
, device
, devlen
* sizeof(*device
));
3484 memcpy(lpExeName
+ devlen
, result
->Buffer
+ 2, result
->Length
- 2 * sizeof(WCHAR
));
3485 lpExeName
[*pdwSize
] = 0;
3486 TRACE("NT path: %s\n", debugstr_w(lpExeName
));
3490 if (result
->Length
/sizeof(WCHAR
) + 1 > *pdwSize
)
3492 status
= STATUS_BUFFER_TOO_SMALL
;
3496 *pdwSize
= result
->Length
/sizeof(WCHAR
);
3497 memcpy( lpExeName
, result
->Buffer
, result
->Length
);
3498 lpExeName
[*pdwSize
] = 0;
3502 HeapFree(GetProcessHeap(), 0, dynamic_buffer
);
3503 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3507 /***********************************************************************
3508 * K32GetProcessImageFileNameA (KERNEL32.@)
3510 DWORD WINAPI
K32GetProcessImageFileNameA( HANDLE process
, LPSTR file
, DWORD size
)
3512 return QueryFullProcessImageNameA(process
, PROCESS_NAME_NATIVE
, file
, &size
) ? size
: 0;
3515 /***********************************************************************
3516 * K32GetProcessImageFileNameW (KERNEL32.@)
3518 DWORD WINAPI
K32GetProcessImageFileNameW( HANDLE process
, LPWSTR file
, DWORD size
)
3520 return QueryFullProcessImageNameW(process
, PROCESS_NAME_NATIVE
, file
, &size
) ? size
: 0;
3523 /***********************************************************************
3524 * K32EnumProcesses (KERNEL32.@)
3526 BOOL WINAPI
K32EnumProcesses(DWORD
*lpdwProcessIDs
, DWORD cb
, DWORD
*lpcbUsed
)
3528 SYSTEM_PROCESS_INFORMATION
*spi
;
3529 ULONG size
= 0x4000;
3535 HeapFree(GetProcessHeap(), 0, buf
);
3536 buf
= HeapAlloc(GetProcessHeap(), 0, size
);
3540 status
= NtQuerySystemInformation(SystemProcessInformation
, buf
, size
, NULL
);
3541 } while(status
== STATUS_INFO_LENGTH_MISMATCH
);
3543 if (status
!= STATUS_SUCCESS
)
3545 HeapFree(GetProcessHeap(), 0, buf
);
3546 SetLastError(RtlNtStatusToDosError(status
));
3552 for (*lpcbUsed
= 0; cb
>= sizeof(DWORD
); cb
-= sizeof(DWORD
))
3554 *lpdwProcessIDs
++ = HandleToUlong(spi
->UniqueProcessId
);
3555 *lpcbUsed
+= sizeof(DWORD
);
3557 if (spi
->NextEntryOffset
== 0)
3560 spi
= (SYSTEM_PROCESS_INFORMATION
*)(((PCHAR
)spi
) + spi
->NextEntryOffset
);
3563 HeapFree(GetProcessHeap(), 0, buf
);
3567 /***********************************************************************
3568 * K32QueryWorkingSet (KERNEL32.@)
3570 BOOL WINAPI
K32QueryWorkingSet( HANDLE process
, LPVOID buffer
, DWORD size
)
3574 TRACE( "(%p, %p, %d)\n", process
, buffer
, size
);
3576 status
= NtQueryVirtualMemory( process
, NULL
, MemoryWorkingSetList
, buffer
, size
, NULL
);
3580 SetLastError( RtlNtStatusToDosError( status
) );
3586 /***********************************************************************
3587 * K32QueryWorkingSetEx (KERNEL32.@)
3589 BOOL WINAPI
K32QueryWorkingSetEx( HANDLE process
, LPVOID buffer
, DWORD size
)
3593 TRACE( "(%p, %p, %d)\n", process
, buffer
, size
);
3595 status
= NtQueryVirtualMemory( process
, NULL
, MemoryWorkingSetList
, buffer
, size
, NULL
);
3599 SetLastError( RtlNtStatusToDosError( status
) );
3605 /***********************************************************************
3606 * K32GetProcessMemoryInfo (KERNEL32.@)
3608 * Retrieve memory usage information for a given process
3611 BOOL WINAPI
K32GetProcessMemoryInfo(HANDLE process
,
3612 PPROCESS_MEMORY_COUNTERS pmc
, DWORD cb
)
3617 if (cb
< sizeof(PROCESS_MEMORY_COUNTERS
))
3619 SetLastError(ERROR_INSUFFICIENT_BUFFER
);
3623 status
= NtQueryInformationProcess(process
, ProcessVmCounters
,
3624 &vmc
, sizeof(vmc
), NULL
);
3628 SetLastError(RtlNtStatusToDosError(status
));
3632 pmc
->cb
= sizeof(PROCESS_MEMORY_COUNTERS
);
3633 pmc
->PageFaultCount
= vmc
.PageFaultCount
;
3634 pmc
->PeakWorkingSetSize
= vmc
.PeakWorkingSetSize
;
3635 pmc
->WorkingSetSize
= vmc
.WorkingSetSize
;
3636 pmc
->QuotaPeakPagedPoolUsage
= vmc
.QuotaPeakPagedPoolUsage
;
3637 pmc
->QuotaPagedPoolUsage
= vmc
.QuotaPagedPoolUsage
;
3638 pmc
->QuotaPeakNonPagedPoolUsage
= vmc
.QuotaPeakNonPagedPoolUsage
;
3639 pmc
->QuotaNonPagedPoolUsage
= vmc
.QuotaNonPagedPoolUsage
;
3640 pmc
->PagefileUsage
= vmc
.PagefileUsage
;
3641 pmc
->PeakPagefileUsage
= vmc
.PeakPagefileUsage
;
3646 /***********************************************************************
3647 * ProcessIdToSessionId (KERNEL32.@)
3648 * This function is available on Terminal Server 4SP4 and Windows 2000
3650 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
3652 /* According to MSDN, if the calling process is not in a terminal
3653 * services environment, then the sessionid returned is zero.
3660 /***********************************************************************
3661 * RegisterServiceProcess (KERNEL32.@)
3663 * A service process calls this function to ensure that it continues to run
3664 * even after a user logged off.
3666 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
3668 /* I don't think that Wine needs to do anything in this function */
3669 return 1; /* success */
3673 /**********************************************************************
3674 * IsWow64Process (KERNEL32.@)
3676 BOOL WINAPI
IsWow64Process(HANDLE hProcess
, PBOOL Wow64Process
)
3681 status
= NtQueryInformationProcess( hProcess
, ProcessWow64Information
, &pbi
, sizeof(pbi
), NULL
);
3683 if (status
!= STATUS_SUCCESS
)
3685 SetLastError( RtlNtStatusToDosError( status
) );
3688 *Wow64Process
= (pbi
!= 0);
3693 /***********************************************************************
3694 * GetCurrentProcess (KERNEL32.@)
3696 * Get a handle to the current process.
3702 * A handle representing the current process.
3704 #undef GetCurrentProcess
3705 HANDLE WINAPI
GetCurrentProcess(void)
3707 return (HANDLE
)~(ULONG_PTR
)0;
3710 /***********************************************************************
3711 * GetLogicalProcessorInformation (KERNEL32.@)
3713 BOOL WINAPI
GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer
, PDWORD pBufLen
)
3715 FIXME("(%p,%p): stub\n", buffer
, pBufLen
);
3716 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3720 /***********************************************************************
3721 * GetLogicalProcessorInformationEx (KERNEL32.@)
3723 BOOL WINAPI
GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP relationship
, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX buffer
, PDWORD pBufLen
)
3725 FIXME("(%u,%p,%p): stub\n", relationship
, buffer
, pBufLen
);
3726 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3730 /***********************************************************************
3731 * CmdBatNotification (KERNEL32.@)
3733 * Notifies the system that a batch file has started or finished.
3736 * bBatchRunning [I] TRUE if a batch file has started or
3737 * FALSE if a batch file has finished executing.
3742 BOOL WINAPI
CmdBatNotification( BOOL bBatchRunning
)
3744 FIXME("%d\n", bBatchRunning
);
3749 /***********************************************************************
3750 * RegisterApplicationRestart (KERNEL32.@)
3752 HRESULT WINAPI
RegisterApplicationRestart(PCWSTR pwzCommandLine
, DWORD dwFlags
)
3754 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine
), dwFlags
);
3759 /**********************************************************************
3760 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3762 DWORD WINAPI
WTSGetActiveConsoleSessionId(void)
3768 /**********************************************************************
3769 * GetSystemDEPPolicy (KERNEL32.@)
3771 DEP_SYSTEM_POLICY_TYPE WINAPI
GetSystemDEPPolicy(void)
3777 /**********************************************************************
3778 * SetProcessDEPPolicy (KERNEL32.@)
3780 BOOL WINAPI
SetProcessDEPPolicy(DWORD newDEP
)
3782 FIXME("(%d): stub\n", newDEP
);
3783 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3787 /**********************************************************************
3788 * ApplicationRecoveryFinished (KERNEL32.@)
3790 VOID WINAPI
ApplicationRecoveryFinished(BOOL success
)
3793 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3796 /**********************************************************************
3797 * ApplicationRecoveryInProgress (KERNEL32.@)
3799 HRESULT WINAPI
ApplicationRecoveryInProgress(PBOOL canceled
)
3801 FIXME(":%p stub\n", canceled
);
3802 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3806 /**********************************************************************
3807 * RegisterApplicationRecoveryCallback (KERNEL32.@)
3809 HRESULT WINAPI
RegisterApplicationRecoveryCallback(APPLICATION_RECOVERY_CALLBACK callback
, PVOID param
, DWORD pingint
, DWORD flags
)
3811 FIXME("%p, %p, %d, %d: stub\n", callback
, param
, pingint
, flags
);
3812 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3816 /**********************************************************************
3817 * GetNumaHighestNodeNumber (KERNEL32.@)
3819 BOOL WINAPI
GetNumaHighestNodeNumber(PULONG highestnode
)
3821 FIXME("(%p): stub\n", highestnode
);
3822 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3826 /**********************************************************************
3827 * GetNumaNodeProcessorMask (KERNEL32.@)
3829 BOOL WINAPI
GetNumaNodeProcessorMask(UCHAR node
, PULONGLONG mask
)
3831 FIXME("(%c %p): stub\n", node
, mask
);
3832 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
3836 /**********************************************************************
3837 * GetNumaAvailableMemoryNode (KERNEL32.@)
3839 BOOL WINAPI
GetNumaAvailableMemoryNode(UCHAR node
, PULONGLONG available_bytes
)
3841 FIXME("(%c %p): stub\n", node
, available_bytes
);
3842 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);