4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
43 #include <sys/types.h>
46 #define WIN32_NO_STATUS
48 #include "kernel_private.h"
49 #include "wine/library.h"
50 #include "wine/server.h"
51 #include "wine/unicode.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(process
);
55 WINE_DECLARE_DEBUG_CHANNEL(file
);
56 WINE_DECLARE_DEBUG_CHANNEL(relay
);
59 extern char **__wine_get_main_environment(void);
61 extern char **__wine_main_environ
;
62 static char **__wine_get_main_environment(void) { return __wine_main_environ
; }
73 static UINT process_error_mode
;
75 static DWORD shutdown_flags
= 0;
76 static DWORD shutdown_priority
= 0x280;
78 static const int is_win64
= (sizeof(void *) > sizeof(int));
80 HMODULE kernel32_handle
= 0;
82 const WCHAR
*DIR_Windows
= NULL
;
83 const WCHAR
*DIR_System
= NULL
;
84 const WCHAR
*DIR_SysWow64
= NULL
;
87 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
88 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
89 #define PDB32_DOS_PROC 0x0010 /* Dos process */
90 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
91 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
92 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
94 static const WCHAR exeW
[] = {'.','e','x','e',0};
95 static const WCHAR comW
[] = {'.','c','o','m',0};
96 static const WCHAR batW
[] = {'.','b','a','t',0};
97 static const WCHAR cmdW
[] = {'.','c','m','d',0};
98 static const WCHAR pifW
[] = {'.','p','i','f',0};
99 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
101 static void exec_process( LPCWSTR name
);
103 extern void SHELL_LoadRegistry(void);
106 /***********************************************************************
109 static inline int contains_path( LPCWSTR name
)
111 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
115 /***********************************************************************
118 * Check if an environment variable needs to be handled specially when
119 * passed through the Unix environment (i.e. prefixed with "WINE").
121 static inline int is_special_env_var( const char *var
)
123 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
124 !strncmp( var
, "PWD=", sizeof("PWD=")-1 ) ||
125 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
126 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
127 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
131 /***********************************************************************
134 static inline unsigned int is_path_prefix( const WCHAR
*prefix
, const WCHAR
*filename
)
136 unsigned int len
= strlenW( prefix
);
138 if (strncmpiW( filename
, prefix
, len
) || filename
[len
] != '\\') return 0;
139 while (filename
[len
] == '\\') len
++;
144 /***************************************************************************
147 * Get the path of a builtin module when the native file does not exist.
149 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
,
150 UINT size
, struct binary_info
*binary_info
)
154 void *redir_disabled
= 0;
155 unsigned int flags
= (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT
: 0);
157 /* builtin names cannot be empty or contain spaces */
158 if (!libname
[0] || strchrW( libname
, ' ' ) || strchrW( libname
, '\t' )) return FALSE
;
160 if (is_wow64
&& Wow64DisableWow64FsRedirection( &redir_disabled
))
161 Wow64RevertWow64FsRedirection( redir_disabled
);
163 if (contains_path( libname
))
165 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
166 filename
, &file_part
) > size
* sizeof(WCHAR
))
167 return FALSE
; /* too long */
169 if ((len
= is_path_prefix( DIR_System
, filename
)))
171 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
173 else if (DIR_SysWow64
&& (len
= is_path_prefix( DIR_SysWow64
, filename
)))
179 if (filename
+ len
!= file_part
) return FALSE
;
183 len
= strlenW( DIR_System
);
184 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
185 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
186 file_part
= filename
+ len
;
187 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
188 strcpyW( file_part
, libname
);
189 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
191 if (ext
&& !strchrW( file_part
, '.' ))
193 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
194 return FALSE
; /* too long */
195 strcatW( file_part
, ext
);
197 binary_info
->type
= BINARY_UNIX_LIB
;
198 binary_info
->flags
= flags
;
199 binary_info
->res_start
= NULL
;
200 binary_info
->res_end
= NULL
;
205 /***********************************************************************
208 * Open a specific exe file, taking load order into account.
209 * Returns the file handle or 0 for a builtin exe.
211 static HANDLE
open_exe_file( const WCHAR
*name
, struct binary_info
*binary_info
)
215 TRACE("looking for %s\n", debugstr_w(name
) );
217 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
218 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
220 WCHAR buffer
[MAX_PATH
];
221 /* file doesn't exist, check for builtin */
222 if (contains_path( name
) && get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
), binary_info
))
225 else MODULE_get_binary_info( handle
, binary_info
);
231 /***********************************************************************
234 * Open an exe file, and return the full name and file handle.
235 * Returns FALSE if file could not be found.
236 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
237 * If file is a builtin exe, returns TRUE and sets handle to 0.
239 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
,
240 HANDLE
*handle
, struct binary_info
*binary_info
)
242 TRACE("looking for %s\n", debugstr_w(name
) );
244 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
))
246 if (contains_path( name
) && get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
))
251 /* no builtin found, try native without extension in case it is a Unix app */
252 if (!SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
)) return FALSE
;
255 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
256 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
257 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
259 MODULE_get_binary_info( *handle
, binary_info
);
266 /***********************************************************************
267 * build_initial_environment
269 * Build the Win32 environment from the Unix environment
271 static BOOL
build_initial_environment(void)
277 char **env
= __wine_get_main_environment();
279 /* Compute the total size of the Unix environment */
280 for (e
= env
; *e
; e
++)
282 if (is_special_env_var( *e
)) continue;
283 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
285 size
*= sizeof(WCHAR
);
287 /* Now allocate the environment */
289 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
290 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
293 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
294 endptr
= p
+ size
/ sizeof(WCHAR
);
296 /* And fill it with the Unix environment */
297 for (e
= env
; *e
; e
++)
301 /* skip Unix special variables and use the Wine variants instead */
302 if (!strncmp( str
, "WINE", 4 ))
304 if (is_special_env_var( str
+ 4 )) str
+= 4;
305 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
307 else if (is_special_env_var( str
)) continue; /* skip it */
309 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
317 /***********************************************************************
318 * set_registry_variables
320 * Set environment variables by enumerating the values of a key;
321 * helper for set_registry_environment().
322 * Note that Windows happily truncates the value if it's too big.
324 static void set_registry_variables( HANDLE hkey
, ULONG type
)
326 static const WCHAR pathW
[] = {'P','A','T','H'};
327 static const WCHAR sep
[] = {';',0};
328 UNICODE_STRING env_name
, env_value
;
332 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
335 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
338 tmp
.MaximumLength
= sizeof(tmpbuf
);
340 for (index
= 0; ; index
++)
342 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
343 buffer
, sizeof(buffer
), &size
);
344 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
346 if (info
->Type
!= type
)
348 env_name
.Buffer
= info
->Name
;
349 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
350 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
351 env_value
.Length
= info
->DataLength
;
352 env_value
.MaximumLength
= sizeof(buffer
) - info
->DataOffset
;
353 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
354 env_value
.Length
-= sizeof(WCHAR
); /* don't count terminating null if any */
355 if (!env_value
.Length
) continue;
356 if (info
->Type
== REG_EXPAND_SZ
)
358 status
= RtlExpandEnvironmentStrings_U( NULL
, &env_value
, &tmp
, NULL
);
359 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
) continue;
360 RtlCopyUnicodeString( &env_value
, &tmp
);
363 if (env_name
.Length
== sizeof(pathW
) &&
364 !memicmpW( env_name
.Buffer
, pathW
, sizeof(pathW
)/sizeof(WCHAR
) ) &&
365 !RtlQueryEnvironmentVariable_U( NULL
, &env_name
, &tmp
))
367 RtlAppendUnicodeToString( &tmp
, sep
);
368 if (RtlAppendUnicodeStringToString( &tmp
, &env_value
)) continue;
369 RtlCopyUnicodeString( &env_value
, &tmp
);
371 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
376 /***********************************************************************
377 * set_registry_environment
379 * Set the environment variables specified in the registry.
381 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
382 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
383 * on the order in which the variables are processed. But on Windows it
384 * does not really matter since they only use %SystemDrive% and
385 * %SystemRoot% which are predefined. But Wine defines these in the
386 * registry, so we need two passes.
388 static BOOL
set_registry_environment( BOOL volatile_only
)
390 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
391 'S','y','s','t','e','m','\\',
392 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
393 'C','o','n','t','r','o','l','\\',
394 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
395 'E','n','v','i','r','o','n','m','e','n','t',0};
396 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
397 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};
399 OBJECT_ATTRIBUTES attr
;
400 UNICODE_STRING nameW
;
404 attr
.Length
= sizeof(attr
);
405 attr
.RootDirectory
= 0;
406 attr
.ObjectName
= &nameW
;
408 attr
.SecurityDescriptor
= NULL
;
409 attr
.SecurityQualityOfService
= NULL
;
411 /* first the system environment variables */
412 RtlInitUnicodeString( &nameW
, env_keyW
);
413 if (!volatile_only
&& NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
415 set_registry_variables( hkey
, REG_SZ
);
416 set_registry_variables( hkey
, REG_EXPAND_SZ
);
421 /* then the ones for the current user */
422 if (RtlOpenCurrentUser( KEY_READ
, &attr
.RootDirectory
) != STATUS_SUCCESS
) return ret
;
423 RtlInitUnicodeString( &nameW
, envW
);
424 if (!volatile_only
&& NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
426 set_registry_variables( hkey
, REG_SZ
);
427 set_registry_variables( hkey
, REG_EXPAND_SZ
);
431 RtlInitUnicodeString( &nameW
, volatile_envW
);
432 if (NtOpenKey( &hkey
, KEY_READ
, &attr
) == STATUS_SUCCESS
)
434 set_registry_variables( hkey
, REG_SZ
);
435 set_registry_variables( hkey
, REG_EXPAND_SZ
);
439 NtClose( attr
.RootDirectory
);
444 /***********************************************************************
447 static WCHAR
*get_reg_value( HKEY hkey
, const WCHAR
*name
)
449 char buffer
[1024 * sizeof(WCHAR
) + sizeof(KEY_VALUE_PARTIAL_INFORMATION
)];
450 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
451 DWORD len
, size
= sizeof(buffer
);
453 UNICODE_STRING nameW
;
455 RtlInitUnicodeString( &nameW
, name
);
456 if (NtQueryValueKey( hkey
, &nameW
, KeyValuePartialInformation
, buffer
, size
, &size
))
459 if (size
<= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) return NULL
;
460 len
= (size
- FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) / sizeof(WCHAR
);
462 if (info
->Type
== REG_EXPAND_SZ
)
464 UNICODE_STRING value
, expanded
;
466 value
.MaximumLength
= len
* sizeof(WCHAR
);
467 value
.Buffer
= (WCHAR
*)info
->Data
;
468 if (!value
.Buffer
[len
- 1]) len
--; /* don't count terminating null if any */
469 value
.Length
= len
* sizeof(WCHAR
);
470 expanded
.Length
= expanded
.MaximumLength
= 1024 * sizeof(WCHAR
);
471 if (!(expanded
.Buffer
= HeapAlloc( GetProcessHeap(), 0, expanded
.MaximumLength
))) return NULL
;
472 if (!RtlExpandEnvironmentStrings_U( NULL
, &value
, &expanded
, NULL
)) ret
= expanded
.Buffer
;
473 else RtlFreeUnicodeString( &expanded
);
475 else if (info
->Type
== REG_SZ
)
477 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
479 memcpy( ret
, info
->Data
, len
* sizeof(WCHAR
) );
487 /***********************************************************************
488 * set_additional_environment
490 * Set some additional environment variables not specified in the registry.
492 static void set_additional_environment(void)
494 static const WCHAR profile_keyW
[] = {'M','a','c','h','i','n','e','\\',
495 'S','o','f','t','w','a','r','e','\\',
496 'M','i','c','r','o','s','o','f','t','\\',
497 'W','i','n','d','o','w','s',' ','N','T','\\',
498 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
499 'P','r','o','f','i','l','e','L','i','s','t',0};
500 static const WCHAR profiles_valueW
[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
501 static const WCHAR all_users_valueW
[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
502 static const WCHAR allusersW
[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
503 OBJECT_ATTRIBUTES attr
;
504 UNICODE_STRING nameW
;
505 WCHAR
*profile_dir
= NULL
, *all_users_dir
= NULL
;
509 /* set the ALLUSERSPROFILE variables */
511 attr
.Length
= sizeof(attr
);
512 attr
.RootDirectory
= 0;
513 attr
.ObjectName
= &nameW
;
515 attr
.SecurityDescriptor
= NULL
;
516 attr
.SecurityQualityOfService
= NULL
;
517 RtlInitUnicodeString( &nameW
, profile_keyW
);
518 if (!NtOpenKey( &hkey
, KEY_READ
, &attr
))
520 profile_dir
= get_reg_value( hkey
, profiles_valueW
);
521 all_users_dir
= get_reg_value( hkey
, all_users_valueW
);
525 if (profile_dir
&& all_users_dir
)
529 len
= strlenW(profile_dir
) + strlenW(all_users_dir
) + 2;
530 value
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
531 strcpyW( value
, profile_dir
);
532 p
= value
+ strlenW(value
);
533 if (p
> value
&& p
[-1] != '\\') *p
++ = '\\';
534 strcpyW( p
, all_users_dir
);
535 SetEnvironmentVariableW( allusersW
, value
);
536 HeapFree( GetProcessHeap(), 0, value
);
539 HeapFree( GetProcessHeap(), 0, all_users_dir
);
540 HeapFree( GetProcessHeap(), 0, profile_dir
);
543 /***********************************************************************
546 * Set the Wine library Unicode argv global variables.
548 static void set_library_wargv( char **argv
)
556 for (argc
= 0; argv
[argc
]; argc
++)
557 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
559 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
560 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
561 p
= (WCHAR
*)(wargv
+ argc
+ 1);
562 for (argc
= 0; argv
[argc
]; argc
++)
564 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
571 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
573 for (argc
= 0; wargv
[argc
]; argc
++)
574 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
576 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
577 q
= (char *)(argv
+ argc
+ 1);
578 for (argc
= 0; wargv
[argc
]; argc
++)
580 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
587 __wine_main_argc
= argc
;
588 __wine_main_argv
= argv
;
589 __wine_main_wargv
= wargv
;
593 /***********************************************************************
594 * update_library_argv0
596 * Update the argv[0] global variable with the binary we have found.
598 static void update_library_argv0( const WCHAR
*argv0
)
600 DWORD len
= strlenW( argv0
);
602 if (len
> strlenW( __wine_main_wargv
[0] ))
604 __wine_main_wargv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
606 strcpyW( __wine_main_wargv
[0], argv0
);
608 len
= WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, NULL
, 0, NULL
, NULL
);
609 if (len
> strlen( __wine_main_argv
[0] ) + 1)
611 __wine_main_argv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, len
);
613 WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, __wine_main_argv
[0], len
, NULL
, NULL
);
617 /***********************************************************************
620 * Build the command line of a process from the argv array.
622 * Note that it does NOT necessarily include the file name.
623 * Sometimes we don't even have any command line options at all.
625 * We must quote and escape characters so that the argv array can be rebuilt
626 * from the command line:
627 * - spaces and tabs must be quoted
629 * - quotes must be escaped
631 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
632 * resulting in an odd number of '\' followed by a '"'
635 * - '\'s that are not followed by a '"' can be left as is
639 static BOOL
build_command_line( WCHAR
**argv
)
644 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
646 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
649 for (arg
= argv
; *arg
; arg
++)
651 int has_space
,bcount
;
657 if( !*a
) has_space
=1;
662 if (*a
==' ' || *a
=='\t') {
664 } else if (*a
=='"') {
665 /* doubling of '\' preceding a '"',
666 * plus escaping of said '"'
674 len
+=(a
-*arg
)+1 /* for the separating space */;
676 len
+=2; /* for the quotes */
679 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
682 p
= rupp
->CommandLine
.Buffer
;
683 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
684 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
685 for (arg
= argv
; *arg
; arg
++)
687 int has_space
,has_quote
;
690 /* Check for quotes and spaces in this argument */
691 has_space
=has_quote
=0;
693 if( !*a
) has_space
=1;
695 if (*a
==' ' || *a
=='\t') {
699 } else if (*a
=='"') {
707 /* Now transfer it to the command line */
724 /* Double all the '\\' preceding this '"', plus one */
725 for (i
=0;i
<=bcount
;i
++)
737 while ((*p
=*x
++)) p
++;
743 if (p
> rupp
->CommandLine
.Buffer
)
744 p
--; /* remove last space */
751 /***********************************************************************
752 * init_current_directory
754 * Initialize the current directory from the Unix cwd or the parent info.
756 static void init_current_directory( CURDIR
*cur_dir
)
758 UNICODE_STRING dir_str
;
763 /* if we received a cur dir from the parent, try this first */
765 if (cur_dir
->DosPath
.Length
)
767 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
770 /* now try to get it from the Unix cwd */
772 for (size
= 256; ; size
*= 2)
774 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
775 if (getcwd( cwd
, size
)) break;
776 HeapFree( GetProcessHeap(), 0, cwd
);
777 if (errno
== ERANGE
) continue;
782 /* try to use PWD if it is valid, so that we don't resolve symlinks */
784 pwd
= getenv( "PWD" );
787 struct stat st1
, st2
;
789 if (!pwd
|| stat( pwd
, &st1
) == -1 ||
790 (!stat( cwd
, &st2
) && (st1
.st_dev
!= st2
.st_dev
|| st1
.st_ino
!= st2
.st_ino
)))
796 ANSI_STRING unix_name
;
797 UNICODE_STRING nt_name
;
798 RtlInitAnsiString( &unix_name
, pwd
);
799 if (!wine_unix_to_nt_file_name( &unix_name
, &nt_name
))
801 UNICODE_STRING dos_path
;
802 /* skip the \??\ prefix, nt_name is 0 terminated */
803 RtlInitUnicodeString( &dos_path
, nt_name
.Buffer
+ 4 );
804 RtlSetCurrentDirectory_U( &dos_path
);
805 RtlFreeUnicodeString( &nt_name
);
809 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
811 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
812 "starting in the Windows directory.\n", cwd
? cwd
: "" );
813 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
814 RtlSetCurrentDirectory_U( &dir_str
);
816 HeapFree( GetProcessHeap(), 0, cwd
);
819 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
820 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
824 /***********************************************************************
827 * Initialize the windows and system directories from the environment.
829 static void init_windows_dirs(void)
831 extern void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
833 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
834 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
835 static const WCHAR default_windirW
[] = {'C',':','\\','w','i','n','d','o','w','s',0};
836 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m','3','2',0};
837 static const WCHAR default_syswow64W
[] = {'\\','s','y','s','w','o','w','6','4',0};
842 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
844 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
845 GetEnvironmentVariableW( windirW
, buffer
, len
);
846 DIR_Windows
= buffer
;
848 else DIR_Windows
= default_windirW
;
850 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
852 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
853 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
858 len
= strlenW( DIR_Windows
);
859 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
860 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
861 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
865 if (!CreateDirectoryW( DIR_Windows
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
866 ERR( "directory %s could not be created, error %u\n",
867 debugstr_w(DIR_Windows
), GetLastError() );
868 if (!CreateDirectoryW( DIR_System
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
869 ERR( "directory %s could not be created, error %u\n",
870 debugstr_w(DIR_System
), GetLastError() );
872 if (is_win64
|| is_wow64
) /* SysWow64 is always defined on 64-bit */
874 len
= strlenW( DIR_Windows
);
875 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_syswow64W
) );
876 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
877 memcpy( buffer
+ len
, default_syswow64W
, sizeof(default_syswow64W
) );
878 DIR_SysWow64
= buffer
;
879 if (!CreateDirectoryW( DIR_SysWow64
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
880 ERR( "directory %s could not be created, error %u\n",
881 debugstr_w(DIR_SysWow64
), GetLastError() );
884 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
885 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
887 /* set the directories in ntdll too */
888 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
892 /***********************************************************************
895 * Start the wineboot process if necessary. Return the handles to wait on.
897 static void start_wineboot( HANDLE handles
[2] )
899 static const WCHAR wineboot_eventW
[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
902 if (!(handles
[0] = CreateEventW( NULL
, TRUE
, FALSE
, wineboot_eventW
)))
904 ERR( "failed to create wineboot event, expect trouble\n" );
907 if (GetLastError() != ERROR_ALREADY_EXISTS
) /* we created it */
909 static const WCHAR wineboot
[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
910 static const WCHAR args
[] = {' ','-','-','i','n','i','t',0};
912 PROCESS_INFORMATION pi
;
915 WCHAR cmdline
[MAX_PATH
+ (sizeof(wineboot
) + sizeof(args
)) / sizeof(WCHAR
)];
917 memset( &si
, 0, sizeof(si
) );
919 si
.dwFlags
= STARTF_USESTDHANDLES
;
922 si
.hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
924 GetSystemDirectoryW( app
, MAX_PATH
- sizeof(wineboot
)/sizeof(WCHAR
) );
925 lstrcatW( app
, wineboot
);
927 Wow64DisableWow64FsRedirection( &redir
);
928 strcpyW( cmdline
, app
);
929 strcatW( cmdline
, args
);
930 if (CreateProcessW( app
, cmdline
, NULL
, NULL
, FALSE
, DETACHED_PROCESS
, NULL
, NULL
, &si
, &pi
))
932 TRACE( "started wineboot pid %04x tid %04x\n", pi
.dwProcessId
, pi
.dwThreadId
);
933 CloseHandle( pi
.hThread
);
934 handles
[1] = pi
.hProcess
;
938 ERR( "failed to start wineboot, err %u\n", GetLastError() );
939 CloseHandle( handles
[0] );
942 Wow64RevertWow64FsRedirection( redir
);
947 /***********************************************************************
950 * Startup routine of a new process. Runs on the new process stack.
952 static DWORD WINAPI
start_process( PEB
*peb
)
954 IMAGE_NT_HEADERS
*nt
;
955 LPTHREAD_START_ROUTINE entry
;
957 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
958 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
959 nt
->OptionalHeader
.AddressOfEntryPoint
);
961 if (!nt
->OptionalHeader
.AddressOfEntryPoint
)
963 ERR( "%s doesn't have an entry point, it cannot be executed\n",
964 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
) );
969 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
970 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
972 SetLastError( 0 ); /* clear error code */
973 if (peb
->BeingDebugged
) DbgBreakPoint();
978 /***********************************************************************
981 * Change the process name in the ps output.
983 static void set_process_name( int argc
, char *argv
[] )
985 #ifdef HAVE_SETPROCTITLE
986 setproctitle("-%s", argv
[1]);
991 char *p
, *prctl_name
= argv
[1];
992 char *end
= argv
[argc
-1] + strlen(argv
[argc
-1]) + 1;
995 # define PR_SET_NAME 15
998 if ((p
= strrchr( prctl_name
, '\\' ))) prctl_name
= p
+ 1;
999 if ((p
= strrchr( prctl_name
, '/' ))) prctl_name
= p
+ 1;
1001 if (prctl( PR_SET_NAME
, prctl_name
) != -1)
1003 offset
= argv
[1] - argv
[0];
1004 memmove( argv
[1] - offset
, argv
[1], end
- argv
[1] );
1005 memset( end
- offset
, 0, offset
);
1006 for (i
= 1; i
< argc
; i
++) argv
[i
-1] = argv
[i
] - offset
;
1010 #endif /* HAVE_PRCTL */
1012 /* remove argv[0] */
1013 memmove( argv
, argv
+ 1, argc
* sizeof(argv
[0]) );
1018 /***********************************************************************
1019 * __wine_kernel_init
1021 * Wine initialisation: load and start the main exe file.
1023 void CDECL
__wine_kernel_init(void)
1025 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
1026 static const WCHAR dotW
[] = {'.',0};
1028 WCHAR
*p
, main_exe_name
[MAX_PATH
+1];
1029 PEB
*peb
= NtCurrentTeb()->Peb
;
1030 RTL_USER_PROCESS_PARAMETERS
*params
= peb
->ProcessParameters
;
1031 HANDLE boot_events
[2];
1032 BOOL got_environment
= TRUE
;
1034 /* Initialize everything */
1036 setbuf(stdout
,NULL
);
1037 setbuf(stderr
,NULL
);
1038 kernel32_handle
= GetModuleHandleW(kernel32W
);
1039 IsWow64Process( GetCurrentProcess(), &is_wow64
);
1043 if (!params
->Environment
)
1045 /* Copy the parent environment */
1046 if (!build_initial_environment()) exit(1);
1048 /* convert old configuration to new format */
1049 convert_old_config();
1051 got_environment
= set_registry_environment( FALSE
);
1052 set_additional_environment();
1055 init_windows_dirs();
1056 init_current_directory( ¶ms
->CurrentDirectory
);
1058 set_process_name( __wine_main_argc
, __wine_main_argv
);
1059 set_library_wargv( __wine_main_argv
);
1060 boot_events
[0] = boot_events
[1] = 0;
1062 if (peb
->ProcessParameters
->ImagePathName
.Buffer
)
1064 strcpyW( main_exe_name
, peb
->ProcessParameters
->ImagePathName
.Buffer
);
1068 struct binary_info binary_info
;
1070 if (!SearchPathW( NULL
, __wine_main_wargv
[0], exeW
, MAX_PATH
, main_exe_name
, NULL
) &&
1071 !get_builtin_path( __wine_main_wargv
[0], exeW
, main_exe_name
, MAX_PATH
, &binary_info
))
1073 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1074 ExitProcess( GetLastError() );
1076 update_library_argv0( main_exe_name
);
1077 if (!build_command_line( __wine_main_wargv
)) goto error
;
1078 start_wineboot( boot_events
);
1081 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1082 p
= strrchrW( main_exe_name
, '.' );
1083 if (!p
|| strchrW( p
, '/' ) || strchrW( p
, '\\' )) strcatW( main_exe_name
, dotW
);
1085 TRACE( "starting process name=%s argv[0]=%s\n",
1086 debugstr_w(main_exe_name
), debugstr_w(__wine_main_wargv
[0]) );
1088 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1089 MODULE_get_dll_load_path(main_exe_name
) );
1093 DWORD timeout
= 2 * 60 * 1000, count
= 1;
1095 if (boot_events
[1]) count
++;
1096 if (!got_environment
) timeout
= 5 * 60 * 1000; /* initial prefix creation can take longer */
1097 if (WaitForMultipleObjects( count
, boot_events
, FALSE
, timeout
) == WAIT_TIMEOUT
)
1098 ERR( "boot event wait timed out\n" );
1099 CloseHandle( boot_events
[0] );
1100 if (boot_events
[1]) CloseHandle( boot_events
[1] );
1101 /* reload environment now that wineboot has run */
1102 set_registry_environment( got_environment
);
1103 set_additional_environment();
1106 if (!(peb
->ImageBaseAddress
= LoadLibraryExW( main_exe_name
, 0, DONT_RESOLVE_DLL_REFERENCES
)))
1111 DWORD error
= GetLastError();
1113 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1114 if (error
== ERROR_BAD_EXE_FORMAT
||
1115 error
== ERROR_INVALID_ADDRESS
||
1116 error
== ERROR_NOT_ENOUGH_MEMORY
)
1118 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name
);
1119 /* if we get back here, it failed */
1121 else if (error
== ERROR_MOD_NOT_FOUND
)
1123 if ((p
= strrchrW( main_exe_name
, '\\' ))) p
++;
1124 else p
= main_exe_name
;
1125 if (!strcmpiW( p
, winevdmW
) && __wine_main_argc
> 3)
1127 /* args 1 and 2 are --app-name full_path */
1128 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1129 debugstr_w(__wine_main_wargv
[3]) );
1130 ExitProcess( ERROR_BAD_EXE_FORMAT
);
1132 MESSAGE( "wine: cannot find %s\n", debugstr_w(main_exe_name
) );
1133 ExitProcess( ERROR_FILE_NOT_FOUND
);
1135 args
[0] = (DWORD_PTR
)main_exe_name
;
1136 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ARGUMENT_ARRAY
,
1137 NULL
, error
, 0, msgW
, sizeof(msgW
)/sizeof(WCHAR
), (__ms_va_list
*)args
);
1138 WideCharToMultiByte( CP_ACP
, 0, msgW
, -1, msg
, sizeof(msg
), NULL
, NULL
);
1139 MESSAGE( "wine: %s", msg
);
1140 ExitProcess( error
);
1143 LdrInitializeThunk( start_process
, 0, 0, 0 );
1146 ExitProcess( GetLastError() );
1150 /***********************************************************************
1153 * Build an argv array from a command-line.
1154 * 'reserved' is the number of args to reserve before the first one.
1156 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1160 char *arg
,*s
,*d
,*cmdline
;
1161 int in_quotes
,bcount
,len
;
1163 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1164 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, len
))) return NULL
;
1165 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1172 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1175 /* skip the remaining spaces */
1176 while (*s
==' ' || *s
=='\t') {
1183 } else if (*s
=='\\') {
1184 /* '\', count them */
1186 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1188 in_quotes
=!in_quotes
;
1191 /* a regular character */
1196 if (!(argv
= HeapAlloc( GetProcessHeap(), 0, argc
*sizeof(*argv
) + len
)))
1198 HeapFree( GetProcessHeap(), 0, cmdline
);
1202 arg
= d
= s
= (char *)(argv
+ argc
);
1203 memcpy( d
, cmdline
, len
);
1208 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1209 /* Close the argument and copy it */
1213 /* skip the remaining spaces */
1216 } while (*s
==' ' || *s
=='\t');
1218 /* Start with a new argument */
1221 } else if (*s
=='\\') {
1225 } else if (*s
=='"') {
1227 if ((bcount
& 1)==0) {
1228 /* Preceded by an even number of '\', this is half that
1229 * number of '\', plus a '"' which we discard.
1233 in_quotes
=!in_quotes
;
1235 /* Preceded by an odd number of '\', this is half that
1236 * number of '\' followed by a '"'
1244 /* a regular character */
1255 HeapFree( GetProcessHeap(), 0, cmdline
);
1260 /***********************************************************************
1263 * Build the environment of a new child process.
1265 static char **build_envp( const WCHAR
*envW
)
1267 static const char * const unix_vars
[] = { "PATH", "TEMP", "TMP", "HOME" };
1272 int count
= 1, length
;
1275 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1277 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1278 if (!(env
= HeapAlloc( GetProcessHeap(), 0, length
))) return NULL
;
1279 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1281 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1282 if (is_special_env_var( p
)) length
+= 4; /* prefix it with "WINE" */
1284 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1286 if (!(p
= getenv(unix_vars
[i
]))) continue;
1287 length
+= strlen(unix_vars
[i
]) + strlen(p
) + 2;
1291 if ((envp
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*envp
) + length
)))
1293 char **envptr
= envp
;
1294 char *dst
= (char *)(envp
+ count
);
1296 /* some variables must not be modified, so we get them directly from the unix env */
1297 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1299 if (!(p
= getenv(unix_vars
[i
]))) continue;
1300 *envptr
++ = strcpy( dst
, unix_vars
[i
] );
1303 dst
+= strlen(dst
) + 1;
1306 /* now put the Windows environment strings */
1307 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1309 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1310 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1311 if (!strncmp( p
, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1312 if (!strncmp( p
, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1313 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1315 *envptr
++ = strcpy( dst
, "WINE" );
1320 *envptr
++ = strcpy( dst
, p
);
1322 dst
+= strlen(dst
) + 1;
1326 HeapFree( GetProcessHeap(), 0, env
);
1331 /***********************************************************************
1334 * Fork and exec a new Unix binary, checking for errors.
1336 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
, const WCHAR
*env
,
1337 const char *newdir
, DWORD flags
, STARTUPINFOW
*startup
)
1339 int fd
[2], stdin_fd
= -1, stdout_fd
= -1;
1341 char **argv
, **envp
;
1343 if (!env
) env
= GetEnvironmentStringsW();
1346 if (pipe2( fd
, O_CLOEXEC
) == -1)
1351 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1354 fcntl( fd
[0], F_SETFD
, FD_CLOEXEC
);
1355 fcntl( fd
[1], F_SETFD
, FD_CLOEXEC
);
1358 if (!(flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1360 HANDLE hstdin
, hstdout
;
1362 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1364 hstdin
= startup
->hStdInput
;
1365 hstdout
= startup
->hStdOutput
;
1369 hstdin
= GetStdHandle(STD_INPUT_HANDLE
);
1370 hstdout
= GetStdHandle(STD_OUTPUT_HANDLE
);
1373 if (is_console_handle( hstdin
))
1374 hstdin
= wine_server_ptr_handle( console_handle_unmap( hstdin
));
1375 if (is_console_handle( hstdout
))
1376 hstdout
= wine_server_ptr_handle( console_handle_unmap( hstdout
));
1377 wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1378 wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1381 argv
= build_argv( cmdline
, 0 );
1382 envp
= build_envp( env
);
1384 if (!(pid
= fork())) /* child */
1388 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1391 if (!(pid
= fork()))
1393 int fd
= open( "/dev/null", O_RDWR
);
1395 /* close stdin and stdout */
1403 else if (pid
!= -1) _exit(0); /* parent */
1409 dup2( stdin_fd
, 0 );
1412 if (stdout_fd
!= -1)
1414 dup2( stdout_fd
, 1 );
1419 /* Reset signals that we previously set to SIG_IGN */
1420 signal( SIGPIPE
, SIG_DFL
);
1421 signal( SIGCHLD
, SIG_DFL
);
1423 if (newdir
) chdir(newdir
);
1425 if (argv
&& envp
) execve( filename
, argv
, envp
);
1427 write( fd
[1], &err
, sizeof(err
) );
1430 HeapFree( GetProcessHeap(), 0, argv
);
1431 HeapFree( GetProcessHeap(), 0, envp
);
1432 if (stdin_fd
!= -1) close( stdin_fd
);
1433 if (stdout_fd
!= -1) close( stdout_fd
);
1435 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1440 if (pid
== -1) FILE_SetDosError();
1446 static inline DWORD
append_string( void **ptr
, const WCHAR
*str
)
1448 DWORD len
= strlenW( str
);
1449 memcpy( *ptr
, str
, len
* sizeof(WCHAR
) );
1450 *ptr
= (WCHAR
*)*ptr
+ len
;
1451 return len
* sizeof(WCHAR
);
1454 /***********************************************************************
1455 * create_startup_info
1457 static startup_info_t
*create_startup_info( LPCWSTR filename
, LPCWSTR cmdline
,
1458 LPCWSTR cur_dir
, LPWSTR env
, DWORD flags
,
1459 const STARTUPINFOW
*startup
, DWORD
*info_size
)
1461 const RTL_USER_PROCESS_PARAMETERS
*cur_params
;
1462 startup_info_t
*info
;
1465 UNICODE_STRING newdir
;
1466 WCHAR imagepath
[MAX_PATH
];
1467 HANDLE hstdin
, hstdout
, hstderr
;
1469 if(!GetLongPathNameW( filename
, imagepath
, MAX_PATH
))
1470 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1471 if(!GetFullPathNameW( imagepath
, MAX_PATH
, imagepath
, NULL
))
1472 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1474 cur_params
= NtCurrentTeb()->Peb
->ProcessParameters
;
1476 newdir
.Buffer
= NULL
;
1479 if (RtlDosPathNameToNtPathName_U( cur_dir
, &newdir
, NULL
, NULL
))
1480 cur_dir
= newdir
.Buffer
+ 4; /* skip \??\ prefix */
1486 if (NtCurrentTeb()->Tib
.SubSystemTib
) /* FIXME: hack */
1487 cur_dir
= ((WIN16_SUBSYSTEM_TIB
*)NtCurrentTeb()->Tib
.SubSystemTib
)->curdir
.DosPath
.Buffer
;
1489 cur_dir
= cur_params
->CurrentDirectory
.DosPath
.Buffer
;
1492 size
= sizeof(*info
);
1493 size
+= strlenW( cur_dir
) * sizeof(WCHAR
);
1494 size
+= cur_params
->DllPath
.Length
;
1495 size
+= strlenW( imagepath
) * sizeof(WCHAR
);
1496 size
+= strlenW( cmdline
) * sizeof(WCHAR
);
1497 if (startup
->lpTitle
) size
+= strlenW( startup
->lpTitle
) * sizeof(WCHAR
);
1498 if (startup
->lpDesktop
) size
+= strlenW( startup
->lpDesktop
) * sizeof(WCHAR
);
1499 /* FIXME: shellinfo */
1500 if (startup
->lpReserved2
&& startup
->cbReserved2
) size
+= startup
->cbReserved2
;
1501 size
= (size
+ 1) & ~1;
1504 if (!(info
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, size
))) goto done
;
1506 info
->console_flags
= cur_params
->ConsoleFlags
;
1507 if (flags
& CREATE_NEW_PROCESS_GROUP
) info
->console_flags
= 1;
1508 if (flags
& CREATE_NEW_CONSOLE
) info
->console
= (obj_handle_t
)1; /* FIXME: cf. kernel_main.c */
1510 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1512 hstdin
= startup
->hStdInput
;
1513 hstdout
= startup
->hStdOutput
;
1514 hstderr
= startup
->hStdError
;
1518 hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1519 hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1520 hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1522 info
->hstdin
= wine_server_obj_handle( hstdin
);
1523 info
->hstdout
= wine_server_obj_handle( hstdout
);
1524 info
->hstderr
= wine_server_obj_handle( hstderr
);
1525 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1527 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1528 if (is_console_handle(hstdin
)) info
->hstdin
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1529 if (is_console_handle(hstdout
)) info
->hstdout
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1530 if (is_console_handle(hstderr
)) info
->hstderr
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1534 if (is_console_handle(hstdin
)) info
->hstdin
= console_handle_unmap(hstdin
);
1535 if (is_console_handle(hstdout
)) info
->hstdout
= console_handle_unmap(hstdout
);
1536 if (is_console_handle(hstderr
)) info
->hstderr
= console_handle_unmap(hstderr
);
1539 info
->x
= startup
->dwX
;
1540 info
->y
= startup
->dwY
;
1541 info
->xsize
= startup
->dwXSize
;
1542 info
->ysize
= startup
->dwYSize
;
1543 info
->xchars
= startup
->dwXCountChars
;
1544 info
->ychars
= startup
->dwYCountChars
;
1545 info
->attribute
= startup
->dwFillAttribute
;
1546 info
->flags
= startup
->dwFlags
;
1547 info
->show
= startup
->wShowWindow
;
1550 info
->curdir_len
= append_string( &ptr
, cur_dir
);
1551 info
->dllpath_len
= cur_params
->DllPath
.Length
;
1552 memcpy( ptr
, cur_params
->DllPath
.Buffer
, cur_params
->DllPath
.Length
);
1553 ptr
= (char *)ptr
+ cur_params
->DllPath
.Length
;
1554 info
->imagepath_len
= append_string( &ptr
, imagepath
);
1555 info
->cmdline_len
= append_string( &ptr
, cmdline
);
1556 if (startup
->lpTitle
) info
->title_len
= append_string( &ptr
, startup
->lpTitle
);
1557 if (startup
->lpDesktop
) info
->desktop_len
= append_string( &ptr
, startup
->lpDesktop
);
1558 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1560 info
->runtime_len
= startup
->cbReserved2
;
1561 memcpy( ptr
, startup
->lpReserved2
, startup
->cbReserved2
);
1565 RtlFreeUnicodeString( &newdir
);
1569 /***********************************************************************
1570 * get_alternate_loader
1572 * Get the name of the alternate (32 or 64 bit) Wine loader.
1574 static const char *get_alternate_loader( char **ret_env
)
1577 const char *loader
= NULL
;
1578 const char *loader_env
= getenv( "WINELOADER" );
1582 if (wine_get_build_dir()) loader
= is_win64
? "loader/wine32" : "server/../loader/wine";
1586 int len
= strlen( loader_env
);
1589 if (!(env
= HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len
+ 2 ))) return NULL
;
1590 strcpy( env
, "WINELOADER=" );
1591 strcat( env
, loader_env
);
1592 strcat( env
, "32" );
1596 if (!(env
= HeapAlloc( GetProcessHeap(), 0, sizeof("WINELOADER=") + len
))) return NULL
;
1597 strcpy( env
, "WINELOADER=" );
1598 strcat( env
, loader_env
);
1599 len
+= sizeof("WINELOADER=") - 1;
1600 if (!strcmp( env
+ len
- 2, "32" )) env
[len
- 2] = 0;
1604 if ((loader
= strrchr( env
, '/' ))) loader
++;
1609 if (!loader
) loader
= is_win64
? "wine32" : "wine";
1613 /***********************************************************************
1616 * Create a new process. If hFile is a valid handle we have an exe
1617 * file, otherwise it is a Winelib app.
1619 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1620 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1621 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1622 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1623 const struct binary_info
*binary_info
, int exec_only
)
1625 BOOL ret
, success
= FALSE
;
1626 HANDLE process_info
;
1628 char *winedebug
= NULL
;
1629 char *wineloader
= NULL
;
1630 const char *loader
= NULL
;
1632 startup_info_t
*startup_info
;
1633 DWORD startup_info_size
;
1634 int socketfd
[2], stdin_fd
= -1, stdout_fd
= -1;
1638 if (!is_win64
&& !is_wow64
&& (binary_info
->flags
& BINARY_FLAG_64BIT
))
1640 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename
) );
1641 SetLastError( ERROR_BAD_EXE_FORMAT
);
1645 RtlAcquirePebLock();
1647 if (!(startup_info
= create_startup_info( filename
, cmd_line
, cur_dir
, env
, flags
, startup
,
1648 &startup_info_size
)))
1650 RtlReleasePebLock();
1653 if (!env
) env
= NtCurrentTeb()->Peb
->ProcessParameters
->Environment
;
1657 static const WCHAR WINEDEBUG
[] = {'W','I','N','E','D','E','B','U','G','=',0};
1658 if (!winedebug
&& !strncmpW( env_end
, WINEDEBUG
, sizeof(WINEDEBUG
)/sizeof(WCHAR
) - 1 ))
1660 DWORD len
= WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, NULL
, 0, NULL
, NULL
);
1661 if ((winedebug
= HeapAlloc( GetProcessHeap(), 0, len
)))
1662 WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, winedebug
, len
, NULL
, NULL
);
1664 env_end
+= strlenW(env_end
) + 1;
1668 /* create the socket for the new process */
1670 if (socketpair( PF_UNIX
, SOCK_STREAM
, 0, socketfd
) == -1)
1672 RtlReleasePebLock();
1673 HeapFree( GetProcessHeap(), 0, winedebug
);
1674 HeapFree( GetProcessHeap(), 0, startup_info
);
1675 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1678 wine_server_send_fd( socketfd
[1] );
1679 close( socketfd
[1] );
1681 /* create the process on the server side */
1683 SERVER_START_REQ( new_process
)
1685 req
->inherit_all
= inherit
;
1686 req
->create_flags
= flags
;
1687 req
->socket_fd
= socketfd
[1];
1688 req
->exe_file
= wine_server_obj_handle( hFile
);
1689 req
->process_access
= PROCESS_ALL_ACCESS
;
1690 req
->process_attr
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1691 req
->thread_access
= THREAD_ALL_ACCESS
;
1692 req
->thread_attr
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1693 req
->info_size
= startup_info_size
;
1695 wine_server_add_data( req
, startup_info
, startup_info_size
);
1696 wine_server_add_data( req
, env
, (env_end
- env
) * sizeof(WCHAR
) );
1697 if ((ret
= !wine_server_call_err( req
)))
1699 info
->dwProcessId
= (DWORD
)reply
->pid
;
1700 info
->dwThreadId
= (DWORD
)reply
->tid
;
1701 info
->hProcess
= wine_server_ptr_handle( reply
->phandle
);
1702 info
->hThread
= wine_server_ptr_handle( reply
->thandle
);
1704 process_info
= wine_server_ptr_handle( reply
->info
);
1708 RtlReleasePebLock();
1711 close( socketfd
[0] );
1712 HeapFree( GetProcessHeap(), 0, startup_info
);
1713 HeapFree( GetProcessHeap(), 0, winedebug
);
1717 if (!(flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1719 if (startup_info
->hstdin
)
1720 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdin
),
1721 FILE_READ_DATA
, &stdin_fd
, NULL
);
1722 if (startup_info
->hstdout
)
1723 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdout
),
1724 FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1726 HeapFree( GetProcessHeap(), 0, startup_info
);
1728 /* create the child process */
1729 argv
= build_argv( cmd_line
, 1 );
1731 if (!is_win64
^ !(binary_info
->flags
& BINARY_FLAG_64BIT
))
1732 loader
= get_alternate_loader( &wineloader
);
1734 if (exec_only
|| !(pid
= fork())) /* child */
1736 char preloader_reserve
[64], socket_env
[64];
1738 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1740 if (!(pid
= fork()))
1742 int fd
= open( "/dev/null", O_RDWR
);
1744 /* close stdin and stdout */
1752 else if (pid
!= -1) _exit(0); /* parent */
1756 if (stdin_fd
!= -1) dup2( stdin_fd
, 0 );
1757 if (stdout_fd
!= -1) dup2( stdout_fd
, 1 );
1760 if (stdin_fd
!= -1) close( stdin_fd
);
1761 if (stdout_fd
!= -1) close( stdout_fd
);
1763 /* Reset signals that we previously set to SIG_IGN */
1764 signal( SIGPIPE
, SIG_DFL
);
1765 signal( SIGCHLD
, SIG_DFL
);
1767 sprintf( socket_env
, "WINESERVERSOCKET=%u", socketfd
[0] );
1768 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx",
1769 (unsigned long)binary_info
->res_start
, (unsigned long)binary_info
->res_end
);
1771 putenv( preloader_reserve
);
1772 putenv( socket_env
);
1773 if (winedebug
) putenv( winedebug
);
1774 if (wineloader
) putenv( wineloader
);
1775 if (unixdir
) chdir(unixdir
);
1777 if (argv
) wine_exec_wine_binary( loader
, argv
, getenv("WINELOADER") );
1781 /* this is the parent */
1783 if (stdin_fd
!= -1) close( stdin_fd
);
1784 if (stdout_fd
!= -1) close( stdout_fd
);
1785 close( socketfd
[0] );
1786 HeapFree( GetProcessHeap(), 0, argv
);
1787 HeapFree( GetProcessHeap(), 0, winedebug
);
1788 HeapFree( GetProcessHeap(), 0, wineloader
);
1795 /* wait for the new process info to be ready */
1797 WaitForSingleObject( process_info
, INFINITE
);
1798 SERVER_START_REQ( get_new_process_info
)
1800 req
->info
= wine_server_obj_handle( process_info
);
1801 wine_server_call( req
);
1802 success
= reply
->success
;
1803 err
= reply
->exit_code
;
1809 SetLastError( err
? err
: ERROR_INTERNAL_ERROR
);
1812 CloseHandle( process_info
);
1816 CloseHandle( process_info
);
1817 CloseHandle( info
->hProcess
);
1818 CloseHandle( info
->hThread
);
1819 info
->hProcess
= info
->hThread
= 0;
1820 info
->dwProcessId
= info
->dwThreadId
= 0;
1825 /***********************************************************************
1826 * create_vdm_process
1828 * Create a new VDM process for a 16-bit or DOS application.
1830 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
1831 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1832 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1833 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1834 const struct binary_info
*binary_info
, int exec_only
)
1836 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1839 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
1840 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
1844 SetLastError( ERROR_OUTOFMEMORY
);
1847 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
1848 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
1849 flags
, startup
, info
, unixdir
, binary_info
, exec_only
);
1850 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
1855 /***********************************************************************
1856 * create_cmd_process
1858 * Create a new cmd shell process for a .BAT file.
1860 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
1861 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1862 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1863 LPPROCESS_INFORMATION info
)
1866 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
1867 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
1868 WCHAR comspec
[MAX_PATH
];
1872 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
1874 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
1875 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
1878 strcpyW( newcmdline
, comspec
);
1879 strcatW( newcmdline
, slashcW
);
1880 strcatW( newcmdline
, cmd_line
);
1881 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
1882 flags
, env
, cur_dir
, startup
, info
);
1883 HeapFree( GetProcessHeap(), 0, newcmdline
);
1888 /*************************************************************************
1891 * Helper for CreateProcess: retrieve the file name to load from the
1892 * app name and command line. Store the file name in buffer, and
1893 * return a possibly modified command line.
1894 * Also returns a handle to the opened file if it's a Windows binary.
1896 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
1897 int buflen
, HANDLE
*handle
, struct binary_info
*binary_info
)
1899 static const WCHAR quotesW
[] = {'"','%','s','"',0};
1901 WCHAR
*name
, *pos
, *first_space
, *ret
= NULL
;
1904 /* if we have an app name, everything is easy */
1908 /* use the unmodified app name as file name */
1909 lstrcpynW( buffer
, appname
, buflen
);
1910 *handle
= open_exe_file( buffer
, binary_info
);
1911 if (!(ret
= cmdline
) || !cmdline
[0])
1913 /* no command-line, create one */
1914 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
1915 sprintfW( ret
, quotesW
, appname
);
1920 /* first check for a quoted file name */
1922 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
1924 int len
= p
- cmdline
- 1;
1925 /* extract the quoted portion as file name */
1926 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1927 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
1930 if (!find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
1932 if (!get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
)) goto done
;
1935 ret
= cmdline
; /* no change necessary */
1939 /* now try the command-line word by word */
1941 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
1949 while (*p
&& *p
!= ' ' && *p
!= '\t') *pos
++ = *p
++;
1951 if (find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
1956 if (!first_space
) first_space
= pos
;
1957 if (!(*pos
++ = *p
++)) break;
1962 if (first_space
) *first_space
= 0; /* try only the first word as a builtin */
1963 if (get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
))
1968 else SetLastError( ERROR_FILE_NOT_FOUND
);
1970 else if (first_space
) /* build a new command-line with quotes */
1972 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
1974 sprintfW( ret
, quotesW
, name
);
1979 HeapFree( GetProcessHeap(), 0, name
);
1984 /**********************************************************************
1985 * CreateProcessA (KERNEL32.@)
1987 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1988 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
1989 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
1990 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
1993 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
1994 UNICODE_STRING desktopW
, titleW
;
1997 desktopW
.Buffer
= NULL
;
1998 titleW
.Buffer
= NULL
;
1999 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
2000 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
2001 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
2003 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
2004 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
2006 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
2007 infoW
.lpDesktop
= desktopW
.Buffer
;
2008 infoW
.lpTitle
= titleW
.Buffer
;
2010 if (startup_info
->lpReserved
)
2011 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2012 debugstr_a(startup_info
->lpReserved
));
2014 ret
= CreateProcessW( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
2015 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
2017 HeapFree( GetProcessHeap(), 0, app_nameW
);
2018 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
2019 HeapFree( GetProcessHeap(), 0, cur_dirW
);
2020 RtlFreeUnicodeString( &desktopW
);
2021 RtlFreeUnicodeString( &titleW
);
2026 /**********************************************************************
2027 * CreateProcessW (KERNEL32.@)
2029 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2030 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
2031 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
2032 LPPROCESS_INFORMATION info
)
2036 char *unixdir
= NULL
;
2037 WCHAR name
[MAX_PATH
];
2038 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
2039 struct binary_info binary_info
;
2041 /* Process the AppName and/or CmdLine to get module name and path */
2043 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
2045 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
)/sizeof(WCHAR
),
2046 &hFile
, &binary_info
)))
2048 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
2050 /* Warn if unsupported features are used */
2052 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
2053 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
2054 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
2055 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
2056 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name
), flags
);
2060 if (!(unixdir
= wine_get_unix_file_name( cur_dir
)))
2062 SetLastError(ERROR_DIRECTORY
);
2068 WCHAR buf
[MAX_PATH
];
2069 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
2072 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
2077 while (*p
) p
+= strlen(p
) + 1;
2078 p
++; /* final null */
2079 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
2080 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
2081 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
2082 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2085 info
->hThread
= info
->hProcess
= 0;
2086 info
->dwProcessId
= info
->dwThreadId
= 0;
2088 if (binary_info
.flags
& BINARY_FLAG_DLL
)
2090 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
2091 SetLastError( ERROR_BAD_EXE_FORMAT
);
2093 else switch (binary_info
.type
)
2096 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2097 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32,
2098 binary_info
.res_start
, binary_info
.res_end
);
2099 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2100 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2105 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2106 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2107 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2109 case BINARY_UNIX_LIB
:
2110 TRACE( "starting %s as %d-bit Winelib app\n",
2111 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32 );
2112 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2113 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2115 case BINARY_UNKNOWN
:
2116 /* check for .com or .bat extension */
2117 if ((p
= strrchrW( name
, '.' )))
2119 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
2121 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
2122 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2123 inherit
, flags
, startup_info
, info
, unixdir
,
2124 &binary_info
, FALSE
);
2127 if (!strcmpiW( p
, batW
) || !strcmpiW( p
, cmdW
) )
2129 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
2130 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2131 inherit
, flags
, startup_info
, info
);
2136 case BINARY_UNIX_EXE
:
2138 /* unknown file, try as unix executable */
2141 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
2143 if ((unix_name
= wine_get_unix_file_name( name
)))
2145 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
, flags
, startup_info
) != -1);
2146 HeapFree( GetProcessHeap(), 0, unix_name
);
2151 if (hFile
) CloseHandle( hFile
);
2154 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
2155 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
2156 HeapFree( GetProcessHeap(), 0, unixdir
);
2158 TRACE( "started process pid %04x tid %04x\n", info
->dwProcessId
, info
->dwThreadId
);
2163 /**********************************************************************
2166 static void exec_process( LPCWSTR name
)
2170 STARTUPINFOW startup_info
;
2171 PROCESS_INFORMATION info
;
2172 struct binary_info binary_info
;
2174 hFile
= open_exe_file( name
, &binary_info
);
2175 if (!hFile
|| hFile
== INVALID_HANDLE_VALUE
) return;
2177 memset( &startup_info
, 0, sizeof(startup_info
) );
2178 startup_info
.cb
= sizeof(startup_info
);
2180 /* Determine executable type */
2182 if (binary_info
.flags
& BINARY_FLAG_DLL
) return;
2183 switch (binary_info
.type
)
2186 TRACE( "starting %s as Win%d binary (%p-%p)\n",
2187 debugstr_w(name
), (binary_info
.flags
& BINARY_FLAG_64BIT
) ? 64 : 32,
2188 binary_info
.res_start
, binary_info
.res_end
);
2189 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2190 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2192 case BINARY_UNIX_LIB
:
2193 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
2194 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2195 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2197 case BINARY_UNKNOWN
:
2198 /* check for .com or .pif extension */
2199 if (!(p
= strrchrW( name
, '.' ))) break;
2200 if (strcmpiW( p
, comW
) && strcmpiW( p
, pifW
)) break;
2205 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2206 create_vdm_process( name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2207 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2212 CloseHandle( hFile
);
2216 /***********************************************************************
2219 * Wrapper to call WaitForInputIdle USER function
2221 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2223 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2225 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2228 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2229 if (ptr
) return ptr( process
, timeout
);
2235 /***********************************************************************
2236 * WinExec (KERNEL32.@)
2238 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2240 PROCESS_INFORMATION info
;
2241 STARTUPINFOA startup
;
2245 memset( &startup
, 0, sizeof(startup
) );
2246 startup
.cb
= sizeof(startup
);
2247 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2248 startup
.wShowWindow
= nCmdShow
;
2250 /* cmdline needs to be writable for CreateProcess */
2251 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2252 strcpy( cmdline
, lpCmdLine
);
2254 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2255 0, NULL
, NULL
, &startup
, &info
))
2257 /* Give 30 seconds to the app to come up */
2258 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2259 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2261 /* Close off the handles */
2262 CloseHandle( info
.hThread
);
2263 CloseHandle( info
.hProcess
);
2265 else if ((ret
= GetLastError()) >= 32)
2267 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2270 HeapFree( GetProcessHeap(), 0, cmdline
);
2275 /**********************************************************************
2276 * LoadModule (KERNEL32.@)
2278 HINSTANCE WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2280 LOADPARMS32
*params
= paramBlock
;
2281 PROCESS_INFORMATION info
;
2282 STARTUPINFOA startup
;
2283 HINSTANCE hInstance
;
2285 char filename
[MAX_PATH
];
2288 if (!name
) return (HINSTANCE
)ERROR_FILE_NOT_FOUND
;
2290 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2291 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2292 return ULongToHandle(GetLastError());
2294 len
= (BYTE
)params
->lpCmdLine
[0];
2295 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2296 return (HINSTANCE
)ERROR_NOT_ENOUGH_MEMORY
;
2298 strcpy( cmdline
, filename
);
2299 p
= cmdline
+ strlen(cmdline
);
2301 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2304 memset( &startup
, 0, sizeof(startup
) );
2305 startup
.cb
= sizeof(startup
);
2306 if (params
->lpCmdShow
)
2308 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2309 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2312 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2313 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2315 /* Give 30 seconds to the app to come up */
2316 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2317 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2318 hInstance
= (HINSTANCE
)33;
2319 /* Close off the handles */
2320 CloseHandle( info
.hThread
);
2321 CloseHandle( info
.hProcess
);
2323 else if ((hInstance
= ULongToHandle(GetLastError())) >= (HINSTANCE
)32)
2325 FIXME("Strange error set by CreateProcess: %p\n", hInstance
);
2326 hInstance
= (HINSTANCE
)11;
2329 HeapFree( GetProcessHeap(), 0, cmdline
);
2334 /******************************************************************************
2335 * TerminateProcess (KERNEL32.@)
2337 * Terminates a process.
2340 * handle [I] Process to terminate.
2341 * exit_code [I] Exit code.
2345 * Failure: FALSE, check GetLastError().
2347 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2349 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2350 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2354 /***********************************************************************
2355 * ExitProcess (KERNEL32.@)
2357 * Exits the current process.
2360 * status [I] Status code to exit with.
2366 __ASM_STDCALL_FUNC( ExitProcess
, 4, /* Shrinker depend on this particular ExitProcess implementation */
2368 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2369 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2370 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2372 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2376 void WINAPI
process_ExitProcess( DWORD status
)
2378 LdrShutdownProcess();
2379 NtTerminateProcess(GetCurrentProcess(), status
);
2385 void WINAPI
ExitProcess( DWORD status
)
2387 LdrShutdownProcess();
2388 NtTerminateProcess(GetCurrentProcess(), status
);
2394 /***********************************************************************
2395 * GetExitCodeProcess [KERNEL32.@]
2397 * Gets termination status of specified process.
2400 * hProcess [in] Handle to the process.
2401 * lpExitCode [out] Address to receive termination status.
2407 BOOL WINAPI
GetExitCodeProcess( HANDLE hProcess
, LPDWORD lpExitCode
)
2410 PROCESS_BASIC_INFORMATION pbi
;
2412 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2414 if (status
== STATUS_SUCCESS
)
2416 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2419 SetLastError( RtlNtStatusToDosError(status
) );
2424 /***********************************************************************
2425 * SetErrorMode (KERNEL32.@)
2427 UINT WINAPI
SetErrorMode( UINT mode
)
2429 UINT old
= process_error_mode
;
2430 process_error_mode
= mode
;
2434 /***********************************************************************
2435 * GetErrorMode (KERNEL32.@)
2437 UINT WINAPI
GetErrorMode( void )
2439 return process_error_mode
;
2442 /**********************************************************************
2443 * TlsAlloc [KERNEL32.@]
2445 * Allocates a thread local storage index.
2448 * Success: TLS index.
2449 * Failure: 0xFFFFFFFF
2451 DWORD WINAPI
TlsAlloc( void )
2454 PEB
* const peb
= NtCurrentTeb()->Peb
;
2456 RtlAcquirePebLock();
2457 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 0 );
2458 if (index
!= ~0U) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2461 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2464 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2465 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2466 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2468 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2470 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2474 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2475 index
+= TLS_MINIMUM_AVAILABLE
;
2478 else SetLastError( ERROR_NO_MORE_ITEMS
);
2480 RtlReleasePebLock();
2485 /**********************************************************************
2486 * TlsFree [KERNEL32.@]
2488 * Releases a thread local storage index, making it available for reuse.
2491 * index [in] TLS index to free.
2497 BOOL WINAPI
TlsFree( DWORD index
)
2501 RtlAcquirePebLock();
2502 if (index
>= TLS_MINIMUM_AVAILABLE
)
2504 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2505 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2509 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2510 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2512 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2513 else SetLastError( ERROR_INVALID_PARAMETER
);
2514 RtlReleasePebLock();
2519 /**********************************************************************
2520 * TlsGetValue [KERNEL32.@]
2522 * Gets value in a thread's TLS slot.
2525 * index [in] TLS index to retrieve value for.
2528 * Success: Value stored in calling thread's TLS slot for index.
2529 * Failure: 0 and GetLastError() returns NO_ERROR.
2531 LPVOID WINAPI
TlsGetValue( DWORD index
)
2535 if (index
< TLS_MINIMUM_AVAILABLE
)
2537 ret
= NtCurrentTeb()->TlsSlots
[index
];
2541 index
-= TLS_MINIMUM_AVAILABLE
;
2542 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2544 SetLastError( ERROR_INVALID_PARAMETER
);
2547 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2548 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2550 SetLastError( ERROR_SUCCESS
);
2555 /**********************************************************************
2556 * TlsSetValue [KERNEL32.@]
2558 * Stores a value in the thread's TLS slot.
2561 * index [in] TLS index to set value for.
2562 * value [in] Value to be stored.
2568 BOOL WINAPI
TlsSetValue( DWORD index
, LPVOID value
)
2570 if (index
< TLS_MINIMUM_AVAILABLE
)
2572 NtCurrentTeb()->TlsSlots
[index
] = value
;
2576 index
-= TLS_MINIMUM_AVAILABLE
;
2577 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2579 SetLastError( ERROR_INVALID_PARAMETER
);
2582 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2583 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2584 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2586 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2589 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2595 /***********************************************************************
2596 * GetProcessFlags (KERNEL32.@)
2598 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2600 IMAGE_NT_HEADERS
*nt
;
2603 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2605 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2607 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2608 flags
|= PDB32_CONSOLE_PROC
;
2610 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2611 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2616 /***********************************************************************
2617 * GetProcessDword (KERNEL32.18)
2619 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
2621 FIXME( "(%d, %d): not supported\n", dwProcessID
, offset
);
2626 /*********************************************************************
2627 * OpenProcess (KERNEL32.@)
2629 * Opens a handle to a process.
2632 * access [I] Desired access rights assigned to the returned handle.
2633 * inherit [I] Determines whether or not child processes will inherit the handle.
2634 * id [I] Process identifier of the process to get a handle to.
2637 * Success: Valid handle to the specified process.
2638 * Failure: NULL, check GetLastError().
2640 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2644 OBJECT_ATTRIBUTES attr
;
2647 cid
.UniqueProcess
= ULongToHandle(id
);
2648 cid
.UniqueThread
= 0; /* FIXME ? */
2650 attr
.Length
= sizeof(OBJECT_ATTRIBUTES
);
2651 attr
.RootDirectory
= NULL
;
2652 attr
.Attributes
= inherit
? OBJ_INHERIT
: 0;
2653 attr
.SecurityDescriptor
= NULL
;
2654 attr
.SecurityQualityOfService
= NULL
;
2655 attr
.ObjectName
= NULL
;
2657 if (GetVersion() & 0x80000000) access
= PROCESS_ALL_ACCESS
;
2659 status
= NtOpenProcess(&handle
, access
, &attr
, &cid
);
2660 if (status
!= STATUS_SUCCESS
)
2662 SetLastError( RtlNtStatusToDosError(status
) );
2669 /*********************************************************************
2670 * GetProcessId (KERNEL32.@)
2672 * Gets the a unique identifier of a process.
2675 * hProcess [I] Handle to the process.
2679 * Failure: FALSE, check GetLastError().
2683 * The identifier is unique only on the machine and only until the process
2684 * exits (including system shutdown).
2686 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2689 PROCESS_BASIC_INFORMATION pbi
;
2691 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2693 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2694 SetLastError( RtlNtStatusToDosError(status
) );
2699 /*********************************************************************
2700 * CloseHandle (KERNEL32.@)
2705 * handle [I] Handle to close.
2709 * Failure: FALSE, check GetLastError().
2711 BOOL WINAPI
CloseHandle( HANDLE handle
)
2715 /* stdio handles need special treatment */
2716 if ((handle
== (HANDLE
)STD_INPUT_HANDLE
) ||
2717 (handle
== (HANDLE
)STD_OUTPUT_HANDLE
) ||
2718 (handle
== (HANDLE
)STD_ERROR_HANDLE
))
2719 handle
= GetStdHandle( HandleToULong(handle
) );
2721 if (is_console_handle(handle
))
2722 return CloseConsoleHandle(handle
);
2724 status
= NtClose( handle
);
2725 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2730 /*********************************************************************
2731 * GetHandleInformation (KERNEL32.@)
2733 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2735 OBJECT_DATA_INFORMATION info
;
2736 NTSTATUS status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
);
2738 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2742 if (info
.InheritHandle
) *flags
|= HANDLE_FLAG_INHERIT
;
2743 if (info
.ProtectFromClose
) *flags
|= HANDLE_FLAG_PROTECT_FROM_CLOSE
;
2749 /*********************************************************************
2750 * SetHandleInformation (KERNEL32.@)
2752 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2754 OBJECT_DATA_INFORMATION info
;
2757 /* if not setting both fields, retrieve current value first */
2758 if ((mask
& (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
)) !=
2759 (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
))
2761 if ((status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
)))
2763 SetLastError( RtlNtStatusToDosError(status
) );
2767 if (mask
& HANDLE_FLAG_INHERIT
)
2768 info
.InheritHandle
= (flags
& HANDLE_FLAG_INHERIT
) != 0;
2769 if (mask
& HANDLE_FLAG_PROTECT_FROM_CLOSE
)
2770 info
.ProtectFromClose
= (flags
& HANDLE_FLAG_PROTECT_FROM_CLOSE
) != 0;
2772 status
= NtSetInformationObject( handle
, ObjectDataInformation
, &info
, sizeof(info
) );
2773 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2778 /*********************************************************************
2779 * DuplicateHandle (KERNEL32.@)
2781 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2782 HANDLE dest_process
, HANDLE
*dest
,
2783 DWORD access
, BOOL inherit
, DWORD options
)
2787 if (is_console_handle(source
))
2789 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2790 if (source_process
!= dest_process
||
2791 source_process
!= GetCurrentProcess())
2793 SetLastError(ERROR_INVALID_PARAMETER
);
2796 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2797 return (*dest
!= INVALID_HANDLE_VALUE
);
2799 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2800 access
, inherit
? OBJ_INHERIT
: 0, options
);
2801 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2806 /***********************************************************************
2807 * ConvertToGlobalHandle (KERNEL32.@)
2809 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
2811 HANDLE ret
= INVALID_HANDLE_VALUE
;
2812 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
2813 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
2818 /***********************************************************************
2819 * SetHandleContext (KERNEL32.@)
2821 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
2823 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2824 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
2825 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2830 /***********************************************************************
2831 * GetHandleContext (KERNEL32.@)
2833 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
2835 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2836 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
2837 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2842 /***********************************************************************
2843 * CreateSocketHandle (KERNEL32.@)
2845 HANDLE WINAPI
CreateSocketHandle(void)
2847 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2848 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2849 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2850 return INVALID_HANDLE_VALUE
;
2854 /***********************************************************************
2855 * SetPriorityClass (KERNEL32.@)
2857 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
2860 PROCESS_PRIORITY_CLASS ppc
;
2862 ppc
.Foreground
= FALSE
;
2863 switch (priorityclass
)
2865 case IDLE_PRIORITY_CLASS
:
2866 ppc
.PriorityClass
= PROCESS_PRIOCLASS_IDLE
; break;
2867 case BELOW_NORMAL_PRIORITY_CLASS
:
2868 ppc
.PriorityClass
= PROCESS_PRIOCLASS_BELOW_NORMAL
; break;
2869 case NORMAL_PRIORITY_CLASS
:
2870 ppc
.PriorityClass
= PROCESS_PRIOCLASS_NORMAL
; break;
2871 case ABOVE_NORMAL_PRIORITY_CLASS
:
2872 ppc
.PriorityClass
= PROCESS_PRIOCLASS_ABOVE_NORMAL
; break;
2873 case HIGH_PRIORITY_CLASS
:
2874 ppc
.PriorityClass
= PROCESS_PRIOCLASS_HIGH
; break;
2875 case REALTIME_PRIORITY_CLASS
:
2876 ppc
.PriorityClass
= PROCESS_PRIOCLASS_REALTIME
; break;
2878 SetLastError(ERROR_INVALID_PARAMETER
);
2882 status
= NtSetInformationProcess(hprocess
, ProcessPriorityClass
,
2885 if (status
!= STATUS_SUCCESS
)
2887 SetLastError( RtlNtStatusToDosError(status
) );
2894 /***********************************************************************
2895 * GetPriorityClass (KERNEL32.@)
2897 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
2900 PROCESS_BASIC_INFORMATION pbi
;
2902 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2904 if (status
!= STATUS_SUCCESS
)
2906 SetLastError( RtlNtStatusToDosError(status
) );
2909 switch (pbi
.BasePriority
)
2911 case PROCESS_PRIOCLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
2912 case PROCESS_PRIOCLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
2913 case PROCESS_PRIOCLASS_NORMAL
: return NORMAL_PRIORITY_CLASS
;
2914 case PROCESS_PRIOCLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
2915 case PROCESS_PRIOCLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
2916 case PROCESS_PRIOCLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
2918 SetLastError( ERROR_INVALID_PARAMETER
);
2923 /***********************************************************************
2924 * SetProcessAffinityMask (KERNEL32.@)
2926 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
2930 status
= NtSetInformationProcess(hProcess
, ProcessAffinityMask
,
2931 &affmask
, sizeof(DWORD_PTR
));
2934 SetLastError( RtlNtStatusToDosError(status
) );
2941 /**********************************************************************
2942 * GetProcessAffinityMask (KERNEL32.@)
2944 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
2945 PDWORD_PTR lpProcessAffinityMask
,
2946 PDWORD_PTR lpSystemAffinityMask
)
2948 PROCESS_BASIC_INFORMATION pbi
;
2951 status
= NtQueryInformationProcess(hProcess
,
2952 ProcessBasicInformation
,
2953 &pbi
, sizeof(pbi
), NULL
);
2956 SetLastError( RtlNtStatusToDosError(status
) );
2959 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= pbi
.AffinityMask
;
2960 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= (1 << NtCurrentTeb()->Peb
->NumberOfProcessors
) - 1;
2965 /***********************************************************************
2966 * GetProcessVersion (KERNEL32.@)
2968 DWORD WINAPI
GetProcessVersion( DWORD pid
)
2972 PROCESS_BASIC_INFORMATION pbi
;
2975 IMAGE_DOS_HEADER dos
;
2976 IMAGE_NT_HEADERS nt
;
2979 if (!pid
|| pid
== GetCurrentProcessId())
2981 IMAGE_NT_HEADERS
*nt
;
2983 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2984 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
2985 nt
->OptionalHeader
.MinorSubsystemVersion
);
2989 process
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
2990 if (!process
) return 0;
2992 status
= NtQueryInformationProcess(process
, ProcessBasicInformation
, &pbi
, sizeof(pbi
), NULL
);
2993 if (status
) goto err
;
2995 status
= NtReadVirtualMemory(process
, pbi
.PebBaseAddress
, &peb
, sizeof(peb
), &count
);
2996 if (status
|| count
!= sizeof(peb
)) goto err
;
2998 memset(&dos
, 0, sizeof(dos
));
2999 status
= NtReadVirtualMemory(process
, peb
.ImageBaseAddress
, &dos
, sizeof(dos
), &count
);
3000 if (status
|| count
!= sizeof(dos
)) goto err
;
3001 if (dos
.e_magic
!= IMAGE_DOS_SIGNATURE
) goto err
;
3003 memset(&nt
, 0, sizeof(nt
));
3004 status
= NtReadVirtualMemory(process
, (char *)peb
.ImageBaseAddress
+ dos
.e_lfanew
, &nt
, sizeof(nt
), &count
);
3005 if (status
|| count
!= sizeof(nt
)) goto err
;
3006 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) goto err
;
3008 ver
= MAKELONG(nt
.OptionalHeader
.MinorSubsystemVersion
, nt
.OptionalHeader
.MajorSubsystemVersion
);
3011 CloseHandle(process
);
3013 if (status
!= STATUS_SUCCESS
)
3014 SetLastError(RtlNtStatusToDosError(status
));
3020 /***********************************************************************
3021 * SetProcessWorkingSetSize [KERNEL32.@]
3022 * Sets the min/max working set sizes for a specified process.
3025 * hProcess [I] Handle to the process of interest
3026 * minset [I] Specifies minimum working set size
3027 * maxset [I] Specifies maximum working set size
3033 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
3036 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
3037 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
3038 /* Trim the working set to zero */
3039 /* Swap the process out of physical RAM */
3044 /***********************************************************************
3045 * GetProcessWorkingSetSize (KERNEL32.@)
3047 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
3050 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
3051 /* 32 MB working set size */
3052 if (minset
) *minset
= 32*1024*1024;
3053 if (maxset
) *maxset
= 32*1024*1024;
3058 /***********************************************************************
3059 * SetProcessShutdownParameters (KERNEL32.@)
3061 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
3063 FIXME("(%08x, %08x): partial stub.\n", level
, flags
);
3064 shutdown_flags
= flags
;
3065 shutdown_priority
= level
;
3070 /***********************************************************************
3071 * GetProcessShutdownParameters (KERNEL32.@)
3074 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
3076 *lpdwLevel
= shutdown_priority
;
3077 *lpdwFlags
= shutdown_flags
;
3082 /***********************************************************************
3083 * GetProcessPriorityBoost (KERNEL32.@)
3085 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
3087 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
3089 /* Report that no boost is present.. */
3090 *pDisablePriorityBoost
= FALSE
;
3095 /***********************************************************************
3096 * SetProcessPriorityBoost (KERNEL32.@)
3098 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
3100 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
3101 /* Say we can do it. I doubt the program will notice that we don't. */
3106 /***********************************************************************
3107 * ReadProcessMemory (KERNEL32.@)
3109 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
3110 SIZE_T
*bytes_read
)
3112 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
3113 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3118 /***********************************************************************
3119 * WriteProcessMemory (KERNEL32.@)
3121 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
3122 SIZE_T
*bytes_written
)
3124 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
3125 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3130 /****************************************************************************
3131 * FlushInstructionCache (KERNEL32.@)
3133 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
3136 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
3137 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3142 /******************************************************************
3143 * GetProcessIoCounters (KERNEL32.@)
3145 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
3149 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
3150 ioc
, sizeof(*ioc
), NULL
);
3151 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3155 /******************************************************************
3156 * GetProcessHandleCount (KERNEL32.@)
3158 BOOL WINAPI
GetProcessHandleCount(HANDLE hProcess
, DWORD
*cnt
)
3162 status
= NtQueryInformationProcess(hProcess
, ProcessHandleCount
,
3163 cnt
, sizeof(*cnt
), NULL
);
3164 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3168 /******************************************************************
3169 * QueryFullProcessImageNameA (KERNEL32.@)
3171 BOOL WINAPI
QueryFullProcessImageNameA(HANDLE hProcess
, DWORD dwFlags
, LPSTR lpExeName
, PDWORD pdwSize
)
3174 DWORD pdwSizeW
= *pdwSize
;
3175 LPWSTR lpExeNameW
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, *pdwSize
* sizeof(WCHAR
));
3177 retval
= QueryFullProcessImageNameW(hProcess
, dwFlags
, lpExeNameW
, &pdwSizeW
);
3180 retval
= (0 != WideCharToMultiByte(CP_ACP
, 0, lpExeNameW
, -1,
3181 lpExeName
, *pdwSize
, NULL
, NULL
));
3183 *pdwSize
= strlen(lpExeName
);
3185 HeapFree(GetProcessHeap(), 0, lpExeNameW
);
3189 /******************************************************************
3190 * QueryFullProcessImageNameW (KERNEL32.@)
3192 BOOL WINAPI
QueryFullProcessImageNameW(HANDLE hProcess
, DWORD dwFlags
, LPWSTR lpExeName
, PDWORD pdwSize
)
3194 BYTE buffer
[sizeof(UNICODE_STRING
) + MAX_PATH
*sizeof(WCHAR
)]; /* this buffer should be enough */
3195 UNICODE_STRING
*dynamic_buffer
= NULL
;
3196 UNICODE_STRING nt_path
;
3197 UNICODE_STRING
*result
= NULL
;
3201 RtlInitUnicodeStringEx(&nt_path
, NULL
);
3202 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3203 * as this is on Wine. */
3204 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, buffer
,
3205 sizeof(buffer
) - sizeof(WCHAR
), &needed
);
3206 if (status
== STATUS_INFO_LENGTH_MISMATCH
)
3208 dynamic_buffer
= HeapAlloc(GetProcessHeap(), 0, needed
+ sizeof(WCHAR
));
3209 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, (LPBYTE
)dynamic_buffer
, needed
, &needed
);
3210 result
= dynamic_buffer
;
3213 result
= (PUNICODE_STRING
)buffer
;
3215 if (status
) goto cleanup
;
3217 if (dwFlags
& PROCESS_NAME_NATIVE
)
3219 result
->Buffer
[result
->Length
/ sizeof(WCHAR
)] = 0;
3220 if (!RtlDosPathNameToNtPathName_U(result
->Buffer
, &nt_path
, NULL
, NULL
))
3222 status
= STATUS_OBJECT_PATH_NOT_FOUND
;
3228 if (result
->Length
/sizeof(WCHAR
) + 1 > *pdwSize
)
3230 status
= STATUS_BUFFER_TOO_SMALL
;
3234 *pdwSize
= result
->Length
/sizeof(WCHAR
);
3235 memcpy( lpExeName
, result
->Buffer
, result
->Length
);
3236 lpExeName
[*pdwSize
] = 0;
3239 HeapFree(GetProcessHeap(), 0, dynamic_buffer
);
3240 RtlFreeUnicodeString(&nt_path
);
3241 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3245 /***********************************************************************
3246 * ProcessIdToSessionId (KERNEL32.@)
3247 * This function is available on Terminal Server 4SP4 and Windows 2000
3249 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
3251 /* According to MSDN, if the calling process is not in a terminal
3252 * services environment, then the sessionid returned is zero.
3259 /***********************************************************************
3260 * RegisterServiceProcess (KERNEL32.@)
3262 * A service process calls this function to ensure that it continues to run
3263 * even after a user logged off.
3265 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
3267 /* I don't think that Wine needs to do anything in this function */
3268 return 1; /* success */
3272 /**********************************************************************
3273 * IsWow64Process (KERNEL32.@)
3275 BOOL WINAPI
IsWow64Process(HANDLE hProcess
, PBOOL Wow64Process
)
3280 status
= NtQueryInformationProcess( hProcess
, ProcessWow64Information
, &pbi
, sizeof(pbi
), NULL
);
3282 if (status
!= STATUS_SUCCESS
)
3284 SetLastError( RtlNtStatusToDosError( status
) );
3287 *Wow64Process
= (pbi
!= 0);
3292 /***********************************************************************
3293 * GetCurrentProcess (KERNEL32.@)
3295 * Get a handle to the current process.
3301 * A handle representing the current process.
3303 #undef GetCurrentProcess
3304 HANDLE WINAPI
GetCurrentProcess(void)
3306 return (HANDLE
)~(ULONG_PTR
)0;
3309 /***********************************************************************
3310 * CmdBatNotification (KERNEL32.@)
3312 * Notifies the system that a batch file has started or finished.
3315 * bBatchRunning [I] TRUE if a batch file has started or
3316 * FALSE if a batch file has finished executing.
3321 BOOL WINAPI
CmdBatNotification( BOOL bBatchRunning
)
3323 FIXME("%d\n", bBatchRunning
);
3328 /***********************************************************************
3329 * RegisterApplicationRestart (KERNEL32.@)
3331 HRESULT WINAPI
RegisterApplicationRestart(PCWSTR pwzCommandLine
, DWORD dwFlags
)
3333 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine
), dwFlags
);
3338 /**********************************************************************
3339 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3341 DWORD WINAPI
WTSGetActiveConsoleSessionId(void)