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"
30 #ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
39 #ifdef HAVE_SYS_PRCTL_H
40 # include <sys/prctl.h>
42 #include <sys/types.h>
45 #define WIN32_NO_STATUS
46 #include "wine/winbase16.h"
47 #include "wine/winuser16.h"
49 #include "kernel_private.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;
79 HMODULE kernel32_handle
= 0;
81 const WCHAR
*DIR_Windows
= NULL
;
82 const WCHAR
*DIR_System
= NULL
;
83 const WCHAR
*DIR_SysWow64
= NULL
;
86 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
87 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
88 #define PDB32_DOS_PROC 0x0010 /* Dos process */
89 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
90 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
91 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
93 static const WCHAR comW
[] = {'.','c','o','m',0};
94 static const WCHAR batW
[] = {'.','b','a','t',0};
95 static const WCHAR cmdW
[] = {'.','c','m','d',0};
96 static const WCHAR pifW
[] = {'.','p','i','f',0};
97 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
99 static void exec_process( LPCWSTR name
);
101 extern void SHELL_LoadRegistry(void);
104 /***********************************************************************
107 static inline int contains_path( LPCWSTR name
)
109 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
113 /***********************************************************************
116 * Check if an environment variable needs to be handled specially when
117 * passed through the Unix environment (i.e. prefixed with "WINE").
119 static inline int is_special_env_var( const char *var
)
121 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
122 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
123 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
124 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
128 /***********************************************************************
131 static inline unsigned int is_path_prefix( const WCHAR
*prefix
, const WCHAR
*filename
)
133 unsigned int len
= strlenW( prefix
);
135 if (strncmpiW( filename
, prefix
, len
) || filename
[len
] != '\\') return 0;
136 while (filename
[len
] == '\\') len
++;
141 /***************************************************************************
144 * Get the path of a builtin module when the native file does not exist.
146 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
,
147 UINT size
, struct binary_info
*binary_info
)
151 void *redir_disabled
= 0;
152 unsigned int flags
= (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT
: 0);
154 if (is_wow64
&& Wow64DisableWow64FsRedirection( &redir_disabled
))
155 Wow64RevertWow64FsRedirection( redir_disabled
);
157 if (contains_path( libname
))
159 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
160 filename
, &file_part
) > size
* sizeof(WCHAR
))
161 return FALSE
; /* too long */
163 if ((len
= is_path_prefix( DIR_System
, filename
)))
165 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
167 else if (DIR_SysWow64
&& (len
= is_path_prefix( DIR_SysWow64
, filename
)))
173 if (filename
+ len
!= file_part
) return FALSE
;
177 len
= strlenW( DIR_System
);
178 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
179 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
180 file_part
= filename
+ len
;
181 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
182 strcpyW( file_part
, libname
);
183 if (is_wow64
&& redir_disabled
) flags
= BINARY_FLAG_64BIT
;
185 if (ext
&& !strchrW( file_part
, '.' ))
187 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
188 return FALSE
; /* too long */
189 strcatW( file_part
, ext
);
191 binary_info
->type
= BINARY_UNIX_LIB
;
192 binary_info
->flags
= flags
;
193 binary_info
->res_start
= NULL
;
194 binary_info
->res_end
= NULL
;
199 /***********************************************************************
200 * open_builtin_exe_file
202 * Open an exe file for a builtin exe.
204 static void *open_builtin_exe_file( const WCHAR
*name
, char *error
, int error_size
,
205 int test_only
, int *file_exists
)
207 char exename
[MAX_PATH
];
212 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
213 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
215 /* we don't want to depend on the current codepage here */
216 len
= strlenW( name
) + 1;
217 if (len
>= sizeof(exename
)) return NULL
;
218 for (i
= 0; i
< len
; i
++)
220 if (name
[i
] > 127) return NULL
;
221 exename
[i
] = (char)name
[i
];
222 if (exename
[i
] >= 'A' && exename
[i
] <= 'Z') exename
[i
] += 'a' - 'A';
224 return wine_dll_load_main_exe( exename
, error
, error_size
, test_only
, file_exists
);
228 /***********************************************************************
231 * Open a specific exe file, taking load order into account.
232 * Returns the file handle or 0 for a builtin exe.
234 static HANDLE
open_exe_file( const WCHAR
*name
, struct binary_info
*binary_info
)
238 TRACE("looking for %s\n", debugstr_w(name
) );
240 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
241 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
243 WCHAR buffer
[MAX_PATH
];
244 /* file doesn't exist, check for builtin */
245 if (contains_path( name
) && get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
), binary_info
))
248 else MODULE_get_binary_info( handle
, binary_info
);
254 /***********************************************************************
257 * Open an exe file, and return the full name and file handle.
258 * Returns FALSE if file could not be found.
259 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
260 * If file is a builtin exe, returns TRUE and sets handle to 0.
262 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
,
263 HANDLE
*handle
, struct binary_info
*binary_info
)
265 static const WCHAR exeW
[] = {'.','e','x','e',0};
268 TRACE("looking for %s\n", debugstr_w(name
) );
270 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
))
272 if (get_builtin_path( name
, exeW
, buffer
, buflen
, binary_info
))
274 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer
) );
275 open_builtin_exe_file( buffer
, NULL
, 0, 1, &file_exists
);
284 /* no builtin found, try native without extension in case it is a Unix app */
286 if (!SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
)) return FALSE
;
289 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
290 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
291 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
293 MODULE_get_binary_info( *handle
, binary_info
);
300 /***********************************************************************
301 * build_initial_environment
303 * Build the Win32 environment from the Unix environment
305 static BOOL
build_initial_environment(void)
311 char **env
= __wine_get_main_environment();
313 /* Compute the total size of the Unix environment */
314 for (e
= env
; *e
; e
++)
316 if (is_special_env_var( *e
)) continue;
317 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
319 size
*= sizeof(WCHAR
);
321 /* Now allocate the environment */
323 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
324 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
327 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
328 endptr
= p
+ size
/ sizeof(WCHAR
);
330 /* And fill it with the Unix environment */
331 for (e
= env
; *e
; e
++)
335 /* skip Unix special variables and use the Wine variants instead */
336 if (!strncmp( str
, "WINE", 4 ))
338 if (is_special_env_var( str
+ 4 )) str
+= 4;
339 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
341 else if (is_special_env_var( str
)) continue; /* skip it */
343 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
351 /***********************************************************************
352 * set_registry_variables
354 * Set environment variables by enumerating the values of a key;
355 * helper for set_registry_environment().
356 * Note that Windows happily truncates the value if it's too big.
358 static void set_registry_variables( HANDLE hkey
, ULONG type
)
360 UNICODE_STRING env_name
, env_value
;
364 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
365 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
367 for (index
= 0; ; index
++)
369 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
370 buffer
, sizeof(buffer
), &size
);
371 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
373 if (info
->Type
!= type
)
375 env_name
.Buffer
= info
->Name
;
376 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
377 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
378 env_value
.Length
= env_value
.MaximumLength
= info
->DataLength
;
379 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
380 env_value
.Length
-= sizeof(WCHAR
); /* don't count terminating null if any */
381 if (info
->Type
== REG_EXPAND_SZ
)
383 WCHAR buf_expanded
[1024];
384 UNICODE_STRING env_expanded
;
385 env_expanded
.Length
= env_expanded
.MaximumLength
= sizeof(buf_expanded
);
386 env_expanded
.Buffer
=buf_expanded
;
387 status
= RtlExpandEnvironmentStrings_U(NULL
, &env_value
, &env_expanded
, NULL
);
388 if (status
== STATUS_SUCCESS
|| status
== STATUS_BUFFER_OVERFLOW
)
389 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_expanded
);
393 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
399 /***********************************************************************
400 * set_registry_environment
402 * Set the environment variables specified in the registry.
404 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
405 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
406 * on the order in which the variables are processed. But on Windows it
407 * does not really matter since they only use %SystemDrive% and
408 * %SystemRoot% which are predefined. But Wine defines these in the
409 * registry, so we need two passes.
411 static BOOL
set_registry_environment(void)
413 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
414 'S','y','s','t','e','m','\\',
415 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
416 'C','o','n','t','r','o','l','\\',
417 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
418 'E','n','v','i','r','o','n','m','e','n','t',0};
419 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
421 OBJECT_ATTRIBUTES attr
;
422 UNICODE_STRING nameW
;
426 attr
.Length
= sizeof(attr
);
427 attr
.RootDirectory
= 0;
428 attr
.ObjectName
= &nameW
;
430 attr
.SecurityDescriptor
= NULL
;
431 attr
.SecurityQualityOfService
= NULL
;
433 /* first the system environment variables */
434 RtlInitUnicodeString( &nameW
, env_keyW
);
435 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
437 set_registry_variables( hkey
, REG_SZ
);
438 set_registry_variables( hkey
, REG_EXPAND_SZ
);
443 /* then the ones for the current user */
444 if (RtlOpenCurrentUser( KEY_ALL_ACCESS
, &attr
.RootDirectory
) != STATUS_SUCCESS
) return ret
;
445 RtlInitUnicodeString( &nameW
, envW
);
446 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
448 set_registry_variables( hkey
, REG_SZ
);
449 set_registry_variables( hkey
, REG_EXPAND_SZ
);
452 NtClose( attr
.RootDirectory
);
457 /***********************************************************************
460 static WCHAR
*get_reg_value( HKEY hkey
, const WCHAR
*name
)
462 char buffer
[1024 * sizeof(WCHAR
) + sizeof(KEY_VALUE_PARTIAL_INFORMATION
)];
463 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
464 DWORD len
, size
= sizeof(buffer
);
466 UNICODE_STRING nameW
;
468 RtlInitUnicodeString( &nameW
, name
);
469 if (NtQueryValueKey( hkey
, &nameW
, KeyValuePartialInformation
, buffer
, size
, &size
))
472 if (size
<= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) return NULL
;
473 len
= (size
- FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) / sizeof(WCHAR
);
475 if (info
->Type
== REG_EXPAND_SZ
)
477 UNICODE_STRING value
, expanded
;
479 value
.MaximumLength
= len
* sizeof(WCHAR
);
480 value
.Buffer
= (WCHAR
*)info
->Data
;
481 if (!value
.Buffer
[len
- 1]) len
--; /* don't count terminating null if any */
482 value
.Length
= len
* sizeof(WCHAR
);
483 expanded
.Length
= expanded
.MaximumLength
= 1024 * sizeof(WCHAR
);
484 if (!(expanded
.Buffer
= HeapAlloc( GetProcessHeap(), 0, expanded
.MaximumLength
))) return NULL
;
485 if (!RtlExpandEnvironmentStrings_U( NULL
, &value
, &expanded
, NULL
)) ret
= expanded
.Buffer
;
486 else RtlFreeUnicodeString( &expanded
);
488 else if (info
->Type
== REG_SZ
)
490 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
492 memcpy( ret
, info
->Data
, len
* sizeof(WCHAR
) );
500 /***********************************************************************
501 * set_additional_environment
503 * Set some additional environment variables not specified in the registry.
505 static void set_additional_environment(void)
507 static const WCHAR profile_keyW
[] = {'M','a','c','h','i','n','e','\\',
508 'S','o','f','t','w','a','r','e','\\',
509 'M','i','c','r','o','s','o','f','t','\\',
510 'W','i','n','d','o','w','s',' ','N','T','\\',
511 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
512 'P','r','o','f','i','l','e','L','i','s','t',0};
513 static const WCHAR profiles_valueW
[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
514 static const WCHAR all_users_valueW
[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
515 static const WCHAR usernameW
[] = {'U','S','E','R','N','A','M','E',0};
516 static const WCHAR userprofileW
[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
517 static const WCHAR allusersW
[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
518 OBJECT_ATTRIBUTES attr
;
519 UNICODE_STRING nameW
;
520 WCHAR
*user_name
= NULL
, *profile_dir
= NULL
, *all_users_dir
= NULL
;
522 const char *name
= wine_get_user_name();
525 /* set the USERNAME variable */
527 len
= MultiByteToWideChar( CP_UNIXCP
, 0, name
, -1, NULL
, 0 );
530 user_name
= HeapAlloc( GetProcessHeap(), 0, len
*sizeof(WCHAR
) );
531 MultiByteToWideChar( CP_UNIXCP
, 0, name
, -1, user_name
, len
);
532 SetEnvironmentVariableW( usernameW
, user_name
);
534 else WARN( "user name %s not convertible.\n", debugstr_a(name
) );
536 /* set the USERPROFILE and ALLUSERSPROFILE variables */
538 attr
.Length
= sizeof(attr
);
539 attr
.RootDirectory
= 0;
540 attr
.ObjectName
= &nameW
;
542 attr
.SecurityDescriptor
= NULL
;
543 attr
.SecurityQualityOfService
= NULL
;
544 RtlInitUnicodeString( &nameW
, profile_keyW
);
545 if (!NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
))
547 profile_dir
= get_reg_value( hkey
, profiles_valueW
);
548 all_users_dir
= get_reg_value( hkey
, all_users_valueW
);
556 if (all_users_dir
) len
= max( len
, strlenW(all_users_dir
) + 1 );
557 len
+= strlenW(profile_dir
) + 1;
558 value
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
559 strcpyW( value
, profile_dir
);
560 p
= value
+ strlenW(value
);
561 if (p
> value
&& p
[-1] != '\\') *p
++ = '\\';
563 strcpyW( p
, user_name
);
564 SetEnvironmentVariableW( userprofileW
, value
);
568 strcpyW( p
, all_users_dir
);
569 SetEnvironmentVariableW( allusersW
, value
);
571 HeapFree( GetProcessHeap(), 0, value
);
574 HeapFree( GetProcessHeap(), 0, all_users_dir
);
575 HeapFree( GetProcessHeap(), 0, profile_dir
);
576 HeapFree( GetProcessHeap(), 0, user_name
);
579 /***********************************************************************
582 * Set the Wine library Unicode argv global variables.
584 static void set_library_wargv( char **argv
)
592 for (argc
= 0; argv
[argc
]; argc
++)
593 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
595 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
596 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
597 p
= (WCHAR
*)(wargv
+ argc
+ 1);
598 for (argc
= 0; argv
[argc
]; argc
++)
600 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
607 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
609 for (argc
= 0; wargv
[argc
]; argc
++)
610 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
612 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
613 q
= (char *)(argv
+ argc
+ 1);
614 for (argc
= 0; wargv
[argc
]; argc
++)
616 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
623 __wine_main_argc
= argc
;
624 __wine_main_argv
= argv
;
625 __wine_main_wargv
= wargv
;
629 /***********************************************************************
630 * update_library_argv0
632 * Update the argv[0] global variable with the binary we have found.
634 static void update_library_argv0( const WCHAR
*argv0
)
636 DWORD len
= strlenW( argv0
);
638 if (len
> strlenW( __wine_main_wargv
[0] ))
640 __wine_main_wargv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
642 strcpyW( __wine_main_wargv
[0], argv0
);
644 len
= WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, NULL
, 0, NULL
, NULL
);
645 if (len
> strlen( __wine_main_argv
[0] ) + 1)
647 __wine_main_argv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, len
);
649 WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, __wine_main_argv
[0], len
, NULL
, NULL
);
653 /***********************************************************************
656 * Build the command line of a process from the argv array.
658 * Note that it does NOT necessarily include the file name.
659 * Sometimes we don't even have any command line options at all.
661 * We must quote and escape characters so that the argv array can be rebuilt
662 * from the command line:
663 * - spaces and tabs must be quoted
665 * - quotes must be escaped
667 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
668 * resulting in an odd number of '\' followed by a '"'
671 * - '\'s that are not followed by a '"' can be left as is
675 static BOOL
build_command_line( WCHAR
**argv
)
680 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
682 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
685 for (arg
= argv
; *arg
; arg
++)
687 int has_space
,bcount
;
693 if( !*a
) has_space
=1;
698 if (*a
==' ' || *a
=='\t') {
700 } else if (*a
=='"') {
701 /* doubling of '\' preceding a '"',
702 * plus escaping of said '"'
710 len
+=(a
-*arg
)+1 /* for the separating space */;
712 len
+=2; /* for the quotes */
715 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
718 p
= rupp
->CommandLine
.Buffer
;
719 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
720 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
721 for (arg
= argv
; *arg
; arg
++)
723 int has_space
,has_quote
;
726 /* Check for quotes and spaces in this argument */
727 has_space
=has_quote
=0;
729 if( !*a
) has_space
=1;
731 if (*a
==' ' || *a
=='\t') {
735 } else if (*a
=='"') {
743 /* Now transfer it to the command line */
760 /* Double all the '\\' preceding this '"', plus one */
761 for (i
=0;i
<=bcount
;i
++)
773 while ((*p
=*x
++)) p
++;
779 if (p
> rupp
->CommandLine
.Buffer
)
780 p
--; /* remove last space */
787 /***********************************************************************
788 * init_current_directory
790 * Initialize the current directory from the Unix cwd or the parent info.
792 static void init_current_directory( CURDIR
*cur_dir
)
794 UNICODE_STRING dir_str
;
799 /* if we received a cur dir from the parent, try this first */
801 if (cur_dir
->DosPath
.Length
)
803 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
806 /* now try to get it from the Unix cwd */
808 for (size
= 256; ; size
*= 2)
810 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
811 if (getcwd( cwd
, size
)) break;
812 HeapFree( GetProcessHeap(), 0, cwd
);
813 if (errno
== ERANGE
) continue;
818 /* try to use PWD if it is valid, so that we don't resolve symlinks */
820 pwd
= getenv( "PWD" );
823 struct stat st1
, st2
;
825 if (!pwd
|| stat( pwd
, &st1
) == -1 ||
826 (!stat( cwd
, &st2
) && (st1
.st_dev
!= st2
.st_dev
|| st1
.st_ino
!= st2
.st_ino
)))
833 int lenW
= MultiByteToWideChar( CP_UNIXCP
, 0, pwd
, -1, NULL
, 0 );
834 if ((dirW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) )))
836 MultiByteToWideChar( CP_UNIXCP
, 0, pwd
, -1, dirW
, lenW
);
837 RtlInitUnicodeString( &dir_str
, dirW
);
838 RtlSetCurrentDirectory_U( &dir_str
);
839 RtlFreeUnicodeString( &dir_str
);
843 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
845 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
846 "starting in the Windows directory.\n", cwd
? cwd
: "" );
847 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
848 RtlSetCurrentDirectory_U( &dir_str
);
850 HeapFree( GetProcessHeap(), 0, cwd
);
853 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
854 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
858 /***********************************************************************
861 * Initialize the windows and system directories from the environment.
863 static void init_windows_dirs(void)
865 extern void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
867 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
868 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
869 static const WCHAR default_windirW
[] = {'C',':','\\','w','i','n','d','o','w','s',0};
870 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m','3','2',0};
871 static const WCHAR default_syswow64W
[] = {'\\','s','y','s','w','o','w','6','4',0};
876 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
878 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
879 GetEnvironmentVariableW( windirW
, buffer
, len
);
880 DIR_Windows
= buffer
;
882 else DIR_Windows
= default_windirW
;
884 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
886 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
887 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
892 len
= strlenW( DIR_Windows
);
893 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
894 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
895 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
899 if (!CreateDirectoryW( DIR_Windows
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
900 ERR( "directory %s could not be created, error %u\n",
901 debugstr_w(DIR_Windows
), GetLastError() );
902 if (!CreateDirectoryW( DIR_System
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
903 ERR( "directory %s could not be created, error %u\n",
904 debugstr_w(DIR_System
), GetLastError() );
906 #ifndef _WIN64 /* SysWow64 is always defined on 64-bit */
910 len
= strlenW( DIR_Windows
);
911 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_syswow64W
) );
912 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
913 memcpy( buffer
+ len
, default_syswow64W
, sizeof(default_syswow64W
) );
914 DIR_SysWow64
= buffer
;
915 if (!CreateDirectoryW( DIR_SysWow64
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
916 ERR( "directory %s could not be created, error %u\n",
917 debugstr_w(DIR_SysWow64
), GetLastError() );
920 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
921 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
923 /* set the directories in ntdll too */
924 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
928 /***********************************************************************
931 * Start the wineboot process if necessary. Return the handles to wait on.
933 static void start_wineboot( HANDLE handles
[2] )
935 static const WCHAR wineboot_eventW
[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
938 if (!(handles
[0] = CreateEventW( NULL
, TRUE
, FALSE
, wineboot_eventW
)))
940 ERR( "failed to create wineboot event, expect trouble\n" );
943 if (GetLastError() != ERROR_ALREADY_EXISTS
) /* we created it */
945 static const WCHAR wineboot
[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
946 static const WCHAR args
[] = {' ','-','-','i','n','i','t',0};
947 const DWORD expected_type
= (sizeof(void*) > sizeof(int) || is_wow64
) ?
948 SCS_64BIT_BINARY
: SCS_32BIT_BINARY
;
950 PROCESS_INFORMATION pi
;
954 WCHAR cmdline
[MAX_PATH
+ (sizeof(wineboot
) + sizeof(args
)) / sizeof(WCHAR
)];
956 memset( &si
, 0, sizeof(si
) );
958 si
.dwFlags
= STARTF_USESTDHANDLES
;
961 si
.hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
963 GetSystemDirectoryW( app
, MAX_PATH
- sizeof(wineboot
)/sizeof(WCHAR
) );
964 lstrcatW( app
, wineboot
);
966 Wow64DisableWow64FsRedirection( &redir
);
967 if (GetBinaryTypeW( app
, &type
) && type
!= expected_type
)
969 if (type
== SCS_64BIT_BINARY
)
970 MESSAGE( "wine: '%s' is a 64-bit prefix, it cannot be used with 32-bit Wine.\n",
971 wine_get_config_dir() );
973 MESSAGE( "wine: '%s' is a 32-bit prefix, it cannot be used with %s Wine.\n",
974 wine_get_config_dir(), is_wow64
? "wow64" : "64-bit" );
978 strcpyW( cmdline
, app
);
979 strcatW( cmdline
, args
);
980 if (CreateProcessW( app
, cmdline
, NULL
, NULL
, FALSE
, DETACHED_PROCESS
, NULL
, NULL
, &si
, &pi
))
982 TRACE( "started wineboot pid %04x tid %04x\n", pi
.dwProcessId
, pi
.dwThreadId
);
983 CloseHandle( pi
.hThread
);
984 handles
[1] = pi
.hProcess
;
988 ERR( "failed to start wineboot, err %u\n", GetLastError() );
989 CloseHandle( handles
[0] );
992 Wow64RevertWow64FsRedirection( redir
);
997 /***********************************************************************
1000 * Startup routine of a new process. Runs on the new process stack.
1002 static DWORD WINAPI
start_process( PEB
*peb
)
1004 IMAGE_NT_HEADERS
*nt
;
1005 LPTHREAD_START_ROUTINE entry
;
1007 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1008 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
1009 nt
->OptionalHeader
.AddressOfEntryPoint
);
1011 if (!nt
->OptionalHeader
.AddressOfEntryPoint
)
1013 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1014 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
) );
1018 if (TRACE_ON(relay
))
1019 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1020 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
1022 SetLastError( 0 ); /* clear error code */
1023 if (peb
->BeingDebugged
) DbgBreakPoint();
1024 return entry( peb
);
1028 /***********************************************************************
1031 * Change the process name in the ps output.
1033 static void set_process_name( int argc
, char *argv
[] )
1035 #ifdef HAVE_SETPROCTITLE
1036 setproctitle("-%s", argv
[1]);
1041 char *p
, *prctl_name
= argv
[1];
1042 char *end
= argv
[argc
-1] + strlen(argv
[argc
-1]) + 1;
1045 # define PR_SET_NAME 15
1048 if ((p
= strrchr( prctl_name
, '\\' ))) prctl_name
= p
+ 1;
1049 if ((p
= strrchr( prctl_name
, '/' ))) prctl_name
= p
+ 1;
1051 if (prctl( PR_SET_NAME
, prctl_name
) != -1)
1053 offset
= argv
[1] - argv
[0];
1054 memmove( argv
[1] - offset
, argv
[1], end
- argv
[1] );
1055 memset( end
- offset
, 0, offset
);
1056 for (i
= 1; i
< argc
; i
++) argv
[i
-1] = argv
[i
] - offset
;
1060 #endif /* HAVE_PRCTL */
1062 /* remove argv[0] */
1063 memmove( argv
, argv
+ 1, argc
* sizeof(argv
[0]) );
1068 /***********************************************************************
1069 * __wine_kernel_init
1071 * Wine initialisation: load and start the main exe file.
1073 void CDECL
__wine_kernel_init(void)
1075 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
1076 static const WCHAR dotW
[] = {'.',0};
1077 static const WCHAR exeW
[] = {'.','e','x','e',0};
1079 WCHAR
*p
, main_exe_name
[MAX_PATH
+1];
1080 PEB
*peb
= NtCurrentTeb()->Peb
;
1081 RTL_USER_PROCESS_PARAMETERS
*params
= peb
->ProcessParameters
;
1082 HANDLE boot_events
[2];
1083 BOOL got_environment
= TRUE
;
1085 /* Initialize everything */
1087 setbuf(stdout
,NULL
);
1088 setbuf(stderr
,NULL
);
1089 kernel32_handle
= GetModuleHandleW(kernel32W
);
1090 IsWow64Process( GetCurrentProcess(), &is_wow64
);
1094 if (!params
->Environment
)
1096 /* Copy the parent environment */
1097 if (!build_initial_environment()) exit(1);
1099 /* convert old configuration to new format */
1100 convert_old_config();
1102 got_environment
= set_registry_environment();
1103 set_additional_environment();
1106 init_windows_dirs();
1107 init_current_directory( ¶ms
->CurrentDirectory
);
1109 set_process_name( __wine_main_argc
, __wine_main_argv
);
1110 set_library_wargv( __wine_main_argv
);
1111 boot_events
[0] = boot_events
[1] = 0;
1113 if (peb
->ProcessParameters
->ImagePathName
.Buffer
)
1115 strcpyW( main_exe_name
, peb
->ProcessParameters
->ImagePathName
.Buffer
);
1119 struct binary_info binary_info
;
1121 if (!SearchPathW( NULL
, __wine_main_wargv
[0], exeW
, MAX_PATH
, main_exe_name
, NULL
) &&
1122 !get_builtin_path( __wine_main_wargv
[0], exeW
, main_exe_name
, MAX_PATH
, &binary_info
))
1124 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1125 ExitProcess( GetLastError() );
1127 update_library_argv0( main_exe_name
);
1128 if (!build_command_line( __wine_main_wargv
)) goto error
;
1129 start_wineboot( boot_events
);
1132 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1133 p
= strrchrW( main_exe_name
, '.' );
1134 if (!p
|| strchrW( p
, '/' ) || strchrW( p
, '\\' )) strcatW( main_exe_name
, dotW
);
1136 TRACE( "starting process name=%s argv[0]=%s\n",
1137 debugstr_w(main_exe_name
), debugstr_w(__wine_main_wargv
[0]) );
1139 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1140 MODULE_get_dll_load_path(main_exe_name
) );
1144 DWORD timeout
= 30000, count
= 1;
1146 if (boot_events
[1]) count
++;
1147 if (!got_environment
) timeout
= 300000; /* initial prefix creation can take longer */
1148 if (WaitForMultipleObjects( count
, boot_events
, FALSE
, timeout
) == WAIT_TIMEOUT
)
1149 ERR( "boot event wait timed out\n" );
1150 CloseHandle( boot_events
[0] );
1151 if (boot_events
[1]) CloseHandle( boot_events
[1] );
1152 /* if we didn't find environment section, try again now that wineboot has run */
1153 if (!got_environment
)
1155 set_registry_environment();
1156 set_additional_environment();
1160 if (!(peb
->ImageBaseAddress
= LoadLibraryExW( main_exe_name
, 0, DONT_RESOLVE_DLL_REFERENCES
)))
1163 DWORD error
= GetLastError();
1165 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1166 if (error
== ERROR_BAD_EXE_FORMAT
||
1167 error
== ERROR_INVALID_ADDRESS
||
1168 error
== ERROR_NOT_ENOUGH_MEMORY
)
1170 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name
);
1171 /* if we get back here, it failed */
1173 else if (error
== ERROR_MOD_NOT_FOUND
)
1175 if ((p
= strrchrW( main_exe_name
, '\\' ))) p
++;
1176 else p
= main_exe_name
;
1177 if (!strcmpiW( p
, winevdmW
) && __wine_main_argc
> 3)
1179 /* args 1 and 2 are --app-name full_path */
1180 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1181 debugstr_w(__wine_main_wargv
[3]) );
1182 ExitProcess( ERROR_BAD_EXE_FORMAT
);
1185 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, error
, 0, msg
, sizeof(msg
), NULL
);
1186 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name
), msg
);
1187 ExitProcess( error
);
1190 LdrInitializeThunk( start_process
, 0, 0, 0 );
1193 ExitProcess( GetLastError() );
1197 /***********************************************************************
1200 * Build an argv array from a command-line.
1201 * 'reserved' is the number of args to reserve before the first one.
1203 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1207 char *arg
,*s
,*d
,*cmdline
;
1208 int in_quotes
,bcount
,len
;
1210 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1211 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, len
))) return NULL
;
1212 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1219 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1222 /* skip the remaining spaces */
1223 while (*s
==' ' || *s
=='\t') {
1230 } else if (*s
=='\\') {
1231 /* '\', count them */
1233 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1235 in_quotes
=!in_quotes
;
1238 /* a regular character */
1243 if (!(argv
= HeapAlloc( GetProcessHeap(), 0, argc
*sizeof(*argv
) + len
)))
1245 HeapFree( GetProcessHeap(), 0, cmdline
);
1249 arg
= d
= s
= (char *)(argv
+ argc
);
1250 memcpy( d
, cmdline
, len
);
1255 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1256 /* Close the argument and copy it */
1260 /* skip the remaining spaces */
1263 } while (*s
==' ' || *s
=='\t');
1265 /* Start with a new argument */
1268 } else if (*s
=='\\') {
1272 } else if (*s
=='"') {
1274 if ((bcount
& 1)==0) {
1275 /* Preceded by an even number of '\', this is half that
1276 * number of '\', plus a '"' which we discard.
1280 in_quotes
=!in_quotes
;
1282 /* Preceded by an odd number of '\', this is half that
1283 * number of '\' followed by a '"'
1291 /* a regular character */
1302 HeapFree( GetProcessHeap(), 0, cmdline
);
1307 /***********************************************************************
1310 * Build the environment of a new child process.
1312 static char **build_envp( const WCHAR
*envW
)
1314 static const char * const unix_vars
[] = { "PATH", "TEMP", "TMP", "HOME" };
1319 int count
= 1, length
;
1322 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1324 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1325 if (!(env
= HeapAlloc( GetProcessHeap(), 0, length
))) return NULL
;
1326 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1328 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1329 if (is_special_env_var( p
)) length
+= 4; /* prefix it with "WINE" */
1331 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1333 if (!(p
= getenv(unix_vars
[i
]))) continue;
1334 length
+= strlen(unix_vars
[i
]) + strlen(p
) + 2;
1338 if ((envp
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*envp
) + length
)))
1340 char **envptr
= envp
;
1341 char *dst
= (char *)(envp
+ count
);
1343 /* some variables must not be modified, so we get them directly from the unix env */
1344 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1346 if (!(p
= getenv(unix_vars
[i
]))) continue;
1347 *envptr
++ = strcpy( dst
, unix_vars
[i
] );
1350 dst
+= strlen(dst
) + 1;
1353 /* now put the Windows environment strings */
1354 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1356 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1357 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1358 if (!strncmp( p
, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1359 if (!strncmp( p
, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1360 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1362 *envptr
++ = strcpy( dst
, "WINE" );
1367 *envptr
++ = strcpy( dst
, p
);
1369 dst
+= strlen(dst
) + 1;
1373 HeapFree( GetProcessHeap(), 0, env
);
1378 /***********************************************************************
1381 * Fork and exec a new Unix binary, checking for errors.
1383 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
, const WCHAR
*env
,
1384 const char *newdir
, DWORD flags
, STARTUPINFOW
*startup
)
1386 int fd
[2], stdin_fd
= -1, stdout_fd
= -1;
1388 char **argv
, **envp
;
1390 if (!env
) env
= GetEnvironmentStringsW();
1393 if (pipe2( fd
, O_CLOEXEC
) == -1)
1398 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1401 fcntl( fd
[0], F_SETFD
, FD_CLOEXEC
);
1402 fcntl( fd
[1], F_SETFD
, FD_CLOEXEC
);
1405 if (!(flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1407 HANDLE hstdin
, hstdout
;
1409 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1411 hstdin
= startup
->hStdInput
;
1412 hstdout
= startup
->hStdOutput
;
1416 hstdin
= GetStdHandle(STD_INPUT_HANDLE
);
1417 hstdout
= GetStdHandle(STD_OUTPUT_HANDLE
);
1420 if (is_console_handle( hstdin
))
1421 hstdin
= wine_server_ptr_handle( console_handle_unmap( hstdin
));
1422 if (is_console_handle( hstdout
))
1423 hstdout
= wine_server_ptr_handle( console_handle_unmap( hstdout
));
1424 wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1425 wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1428 argv
= build_argv( cmdline
, 0 );
1429 envp
= build_envp( env
);
1431 if (!(pid
= fork())) /* child */
1435 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1438 if (!(pid
= fork()))
1440 int fd
= open( "/dev/null", O_RDWR
);
1442 /* close stdin and stdout */
1450 else if (pid
!= -1) _exit(0); /* parent */
1456 dup2( stdin_fd
, 0 );
1459 if (stdout_fd
!= -1)
1461 dup2( stdout_fd
, 1 );
1466 /* Reset signals that we previously set to SIG_IGN */
1467 signal( SIGPIPE
, SIG_DFL
);
1468 signal( SIGCHLD
, SIG_DFL
);
1470 if (newdir
) chdir(newdir
);
1472 if (argv
&& envp
) execve( filename
, argv
, envp
);
1474 write( fd
[1], &err
, sizeof(err
) );
1477 HeapFree( GetProcessHeap(), 0, argv
);
1478 HeapFree( GetProcessHeap(), 0, envp
);
1479 if (stdin_fd
!= -1) close( stdin_fd
);
1480 if (stdout_fd
!= -1) close( stdout_fd
);
1482 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1487 if (pid
== -1) FILE_SetDosError();
1493 static inline DWORD
append_string( void **ptr
, const WCHAR
*str
)
1495 DWORD len
= strlenW( str
);
1496 memcpy( *ptr
, str
, len
* sizeof(WCHAR
) );
1497 *ptr
= (WCHAR
*)*ptr
+ len
;
1498 return len
* sizeof(WCHAR
);
1501 /***********************************************************************
1502 * create_startup_info
1504 static startup_info_t
*create_startup_info( LPCWSTR filename
, LPCWSTR cmdline
,
1505 LPCWSTR cur_dir
, LPWSTR env
, DWORD flags
,
1506 const STARTUPINFOW
*startup
, DWORD
*info_size
)
1508 const RTL_USER_PROCESS_PARAMETERS
*cur_params
;
1509 startup_info_t
*info
;
1512 UNICODE_STRING newdir
;
1513 WCHAR imagepath
[MAX_PATH
];
1514 HANDLE hstdin
, hstdout
, hstderr
;
1516 if(!GetLongPathNameW( filename
, imagepath
, MAX_PATH
))
1517 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1518 if(!GetFullPathNameW( imagepath
, MAX_PATH
, imagepath
, NULL
))
1519 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1521 cur_params
= NtCurrentTeb()->Peb
->ProcessParameters
;
1523 newdir
.Buffer
= NULL
;
1526 if (RtlDosPathNameToNtPathName_U( cur_dir
, &newdir
, NULL
, NULL
))
1527 cur_dir
= newdir
.Buffer
+ 4; /* skip \??\ prefix */
1533 if (NtCurrentTeb()->Tib
.SubSystemTib
) /* FIXME: hack */
1534 cur_dir
= ((WIN16_SUBSYSTEM_TIB
*)NtCurrentTeb()->Tib
.SubSystemTib
)->curdir
.DosPath
.Buffer
;
1536 cur_dir
= cur_params
->CurrentDirectory
.DosPath
.Buffer
;
1539 size
= sizeof(*info
);
1540 size
+= strlenW( cur_dir
) * sizeof(WCHAR
);
1541 size
+= cur_params
->DllPath
.Length
;
1542 size
+= strlenW( imagepath
) * sizeof(WCHAR
);
1543 size
+= strlenW( cmdline
) * sizeof(WCHAR
);
1544 if (startup
->lpTitle
) size
+= strlenW( startup
->lpTitle
) * sizeof(WCHAR
);
1545 if (startup
->lpDesktop
) size
+= strlenW( startup
->lpDesktop
) * sizeof(WCHAR
);
1546 /* FIXME: shellinfo */
1547 if (startup
->lpReserved2
&& startup
->cbReserved2
) size
+= startup
->cbReserved2
;
1548 size
= (size
+ 1) & ~1;
1551 if (!(info
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, size
))) goto done
;
1553 info
->console_flags
= cur_params
->ConsoleFlags
;
1554 if (flags
& CREATE_NEW_PROCESS_GROUP
) info
->console_flags
= 1;
1555 if (flags
& CREATE_NEW_CONSOLE
) info
->console
= (obj_handle_t
)1; /* FIXME: cf. kernel_main.c */
1557 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1559 hstdin
= startup
->hStdInput
;
1560 hstdout
= startup
->hStdOutput
;
1561 hstderr
= startup
->hStdError
;
1565 hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1566 hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1567 hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1569 info
->hstdin
= wine_server_obj_handle( hstdin
);
1570 info
->hstdout
= wine_server_obj_handle( hstdout
);
1571 info
->hstderr
= wine_server_obj_handle( hstderr
);
1572 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1574 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1575 if (is_console_handle(hstdin
)) info
->hstdin
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1576 if (is_console_handle(hstdout
)) info
->hstdout
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1577 if (is_console_handle(hstderr
)) info
->hstderr
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1581 if (is_console_handle(hstdin
)) info
->hstdin
= console_handle_unmap(hstdin
);
1582 if (is_console_handle(hstdout
)) info
->hstdout
= console_handle_unmap(hstdout
);
1583 if (is_console_handle(hstderr
)) info
->hstderr
= console_handle_unmap(hstderr
);
1586 info
->x
= startup
->dwX
;
1587 info
->y
= startup
->dwY
;
1588 info
->xsize
= startup
->dwXSize
;
1589 info
->ysize
= startup
->dwYSize
;
1590 info
->xchars
= startup
->dwXCountChars
;
1591 info
->ychars
= startup
->dwYCountChars
;
1592 info
->attribute
= startup
->dwFillAttribute
;
1593 info
->flags
= startup
->dwFlags
;
1594 info
->show
= startup
->wShowWindow
;
1597 info
->curdir_len
= append_string( &ptr
, cur_dir
);
1598 info
->dllpath_len
= cur_params
->DllPath
.Length
;
1599 memcpy( ptr
, cur_params
->DllPath
.Buffer
, cur_params
->DllPath
.Length
);
1600 ptr
= (char *)ptr
+ cur_params
->DllPath
.Length
;
1601 info
->imagepath_len
= append_string( &ptr
, imagepath
);
1602 info
->cmdline_len
= append_string( &ptr
, cmdline
);
1603 if (startup
->lpTitle
) info
->title_len
= append_string( &ptr
, startup
->lpTitle
);
1604 if (startup
->lpDesktop
) info
->desktop_len
= append_string( &ptr
, startup
->lpDesktop
);
1605 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1607 info
->runtime_len
= startup
->cbReserved2
;
1608 memcpy( ptr
, startup
->lpReserved2
, startup
->cbReserved2
);
1612 RtlFreeUnicodeString( &newdir
);
1617 /***********************************************************************
1620 * Create a new process. If hFile is a valid handle we have an exe
1621 * file, otherwise it is a Winelib app.
1623 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1624 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1625 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1626 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1627 const struct binary_info
*binary_info
, int exec_only
)
1629 BOOL ret
, success
= FALSE
;
1630 HANDLE process_info
;
1632 char *winedebug
= NULL
;
1634 startup_info_t
*startup_info
;
1635 DWORD startup_info_size
;
1636 int socketfd
[2], stdin_fd
= -1, stdout_fd
= -1;
1640 if (sizeof(void *) == sizeof(int) && !is_wow64
&& (binary_info
->flags
& BINARY_FLAG_64BIT
))
1642 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename
) );
1643 SetLastError( ERROR_BAD_EXE_FORMAT
);
1647 RtlAcquirePebLock();
1649 if (!(startup_info
= create_startup_info( filename
, cmd_line
, cur_dir
, env
, flags
, startup
,
1650 &startup_info_size
)))
1652 RtlReleasePebLock();
1655 if (!env
) env
= NtCurrentTeb()->Peb
->ProcessParameters
->Environment
;
1659 static const WCHAR WINEDEBUG
[] = {'W','I','N','E','D','E','B','U','G','=',0};
1660 if (!winedebug
&& !strncmpW( env_end
, WINEDEBUG
, sizeof(WINEDEBUG
)/sizeof(WCHAR
) - 1 ))
1662 DWORD len
= WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, NULL
, 0, NULL
, NULL
);
1663 if ((winedebug
= HeapAlloc( GetProcessHeap(), 0, len
)))
1664 WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, winedebug
, len
, NULL
, NULL
);
1666 env_end
+= strlenW(env_end
) + 1;
1670 /* create the socket for the new process */
1672 if (socketpair( PF_UNIX
, SOCK_STREAM
, 0, socketfd
) == -1)
1674 RtlReleasePebLock();
1675 HeapFree( GetProcessHeap(), 0, winedebug
);
1676 HeapFree( GetProcessHeap(), 0, startup_info
);
1677 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1680 wine_server_send_fd( socketfd
[1] );
1681 close( socketfd
[1] );
1683 /* create the process on the server side */
1685 SERVER_START_REQ( new_process
)
1687 req
->inherit_all
= inherit
;
1688 req
->create_flags
= flags
;
1689 req
->socket_fd
= socketfd
[1];
1690 req
->exe_file
= wine_server_obj_handle( hFile
);
1691 req
->process_access
= PROCESS_ALL_ACCESS
;
1692 req
->process_attr
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1693 req
->thread_access
= THREAD_ALL_ACCESS
;
1694 req
->thread_attr
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1695 req
->info_size
= startup_info_size
;
1697 wine_server_add_data( req
, startup_info
, startup_info_size
);
1698 wine_server_add_data( req
, env
, (env_end
- env
) * sizeof(WCHAR
) );
1699 if ((ret
= !wine_server_call_err( req
)))
1701 info
->dwProcessId
= (DWORD
)reply
->pid
;
1702 info
->dwThreadId
= (DWORD
)reply
->tid
;
1703 info
->hProcess
= wine_server_ptr_handle( reply
->phandle
);
1704 info
->hThread
= wine_server_ptr_handle( reply
->thandle
);
1706 process_info
= wine_server_ptr_handle( reply
->info
);
1710 RtlReleasePebLock();
1713 close( socketfd
[0] );
1714 HeapFree( GetProcessHeap(), 0, startup_info
);
1715 HeapFree( GetProcessHeap(), 0, winedebug
);
1719 if (!(flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1721 if (startup_info
->hstdin
)
1722 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdin
),
1723 FILE_READ_DATA
, &stdin_fd
, NULL
);
1724 if (startup_info
->hstdout
)
1725 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdout
),
1726 FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1728 HeapFree( GetProcessHeap(), 0, startup_info
);
1730 /* create the child process */
1731 argv
= build_argv( cmd_line
, 1 );
1733 if (exec_only
|| !(pid
= fork())) /* child */
1735 char preloader_reserve
[64], socket_env
[64];
1737 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1739 if (!(pid
= fork()))
1741 int fd
= open( "/dev/null", O_RDWR
);
1743 /* close stdin and stdout */
1751 else if (pid
!= -1) _exit(0); /* parent */
1755 if (stdin_fd
!= -1) dup2( stdin_fd
, 0 );
1756 if (stdout_fd
!= -1) dup2( stdout_fd
, 1 );
1759 if (stdin_fd
!= -1) close( stdin_fd
);
1760 if (stdout_fd
!= -1) close( stdout_fd
);
1762 /* Reset signals that we previously set to SIG_IGN */
1763 signal( SIGPIPE
, SIG_DFL
);
1764 signal( SIGCHLD
, SIG_DFL
);
1766 sprintf( socket_env
, "WINESERVERSOCKET=%u", socketfd
[0] );
1767 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx",
1768 (unsigned long)binary_info
->res_start
, (unsigned long)binary_info
->res_end
);
1770 putenv( preloader_reserve
);
1771 putenv( socket_env
);
1772 if (winedebug
) putenv( winedebug
);
1773 if (unixdir
) chdir(unixdir
);
1775 if (argv
) wine_exec_wine_binary( NULL
, argv
, getenv("WINELOADER") );
1779 /* this is the parent */
1781 if (stdin_fd
!= -1) close( stdin_fd
);
1782 if (stdout_fd
!= -1) close( stdout_fd
);
1783 close( socketfd
[0] );
1784 HeapFree( GetProcessHeap(), 0, argv
);
1785 HeapFree( GetProcessHeap(), 0, winedebug
);
1792 /* wait for the new process info to be ready */
1794 WaitForSingleObject( process_info
, INFINITE
);
1795 SERVER_START_REQ( get_new_process_info
)
1797 req
->info
= wine_server_obj_handle( process_info
);
1798 wine_server_call( req
);
1799 success
= reply
->success
;
1800 err
= reply
->exit_code
;
1806 SetLastError( err
? err
: ERROR_INTERNAL_ERROR
);
1809 CloseHandle( process_info
);
1813 CloseHandle( process_info
);
1814 CloseHandle( info
->hProcess
);
1815 CloseHandle( info
->hThread
);
1816 info
->hProcess
= info
->hThread
= 0;
1817 info
->dwProcessId
= info
->dwThreadId
= 0;
1822 /***********************************************************************
1823 * create_vdm_process
1825 * Create a new VDM process for a 16-bit or DOS application.
1827 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
1828 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1829 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1830 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1831 const struct binary_info
*binary_info
, int exec_only
)
1833 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1836 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
1837 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
1841 SetLastError( ERROR_OUTOFMEMORY
);
1844 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
1845 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
1846 flags
, startup
, info
, unixdir
, binary_info
, exec_only
);
1847 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
1852 /***********************************************************************
1853 * create_cmd_process
1855 * Create a new cmd shell process for a .BAT file.
1857 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
1858 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1859 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1860 LPPROCESS_INFORMATION info
)
1863 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
1864 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
1865 WCHAR comspec
[MAX_PATH
];
1869 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
1871 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
1872 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
1875 strcpyW( newcmdline
, comspec
);
1876 strcatW( newcmdline
, slashcW
);
1877 strcatW( newcmdline
, cmd_line
);
1878 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
1879 flags
, env
, cur_dir
, startup
, info
);
1880 HeapFree( GetProcessHeap(), 0, newcmdline
);
1885 /*************************************************************************
1888 * Helper for CreateProcess: retrieve the file name to load from the
1889 * app name and command line. Store the file name in buffer, and
1890 * return a possibly modified command line.
1891 * Also returns a handle to the opened file if it's a Windows binary.
1893 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
1894 int buflen
, HANDLE
*handle
, struct binary_info
*binary_info
)
1896 static const WCHAR quotesW
[] = {'"','%','s','"',0};
1898 WCHAR
*name
, *pos
, *ret
= NULL
;
1902 /* if we have an app name, everything is easy */
1906 /* use the unmodified app name as file name */
1907 lstrcpynW( buffer
, appname
, buflen
);
1908 *handle
= open_exe_file( buffer
, binary_info
);
1909 if (!(ret
= cmdline
) || !cmdline
[0])
1911 /* no command-line, create one */
1912 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
1913 sprintfW( ret
, quotesW
, appname
);
1918 /* first check for a quoted file name */
1920 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
1922 int len
= p
- cmdline
- 1;
1923 /* extract the quoted portion as file name */
1924 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1925 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
1928 if (find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
1929 ret
= cmdline
; /* no change necessary */
1933 /* now try the command-line word by word */
1935 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
1943 do *pos
++ = *p
++; while (*p
&& *p
!= ' ' && *p
!= '\t');
1945 if (find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
1950 if (*p
) got_space
= TRUE
;
1953 if (ret
&& got_space
) /* now build a new command-line with quotes */
1955 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
1957 sprintfW( ret
, quotesW
, name
);
1960 else if (!ret
) SetLastError( ERROR_FILE_NOT_FOUND
);
1963 HeapFree( GetProcessHeap(), 0, name
);
1968 /**********************************************************************
1969 * CreateProcessA (KERNEL32.@)
1971 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1972 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
1973 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
1974 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
1977 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
1978 UNICODE_STRING desktopW
, titleW
;
1981 desktopW
.Buffer
= NULL
;
1982 titleW
.Buffer
= NULL
;
1983 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
1984 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
1985 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
1987 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
1988 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
1990 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
1991 infoW
.lpDesktop
= desktopW
.Buffer
;
1992 infoW
.lpTitle
= titleW
.Buffer
;
1994 if (startup_info
->lpReserved
)
1995 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1996 debugstr_a(startup_info
->lpReserved
));
1998 ret
= CreateProcessW( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
1999 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
2001 HeapFree( GetProcessHeap(), 0, app_nameW
);
2002 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
2003 HeapFree( GetProcessHeap(), 0, cur_dirW
);
2004 RtlFreeUnicodeString( &desktopW
);
2005 RtlFreeUnicodeString( &titleW
);
2010 /**********************************************************************
2011 * CreateProcessW (KERNEL32.@)
2013 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2014 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
2015 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
2016 LPPROCESS_INFORMATION info
)
2020 char *unixdir
= NULL
;
2021 WCHAR name
[MAX_PATH
];
2022 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
2023 struct binary_info binary_info
;
2025 /* Process the AppName and/or CmdLine to get module name and path */
2027 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
2029 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
)/sizeof(WCHAR
),
2030 &hFile
, &binary_info
)))
2032 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
2034 /* Warn if unsupported features are used */
2036 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
2037 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
2038 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
2039 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
2040 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name
), flags
);
2044 if (!(unixdir
= wine_get_unix_file_name( cur_dir
)))
2046 SetLastError(ERROR_DIRECTORY
);
2052 WCHAR buf
[MAX_PATH
];
2053 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
2056 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
2061 while (*p
) p
+= strlen(p
) + 1;
2062 p
++; /* final null */
2063 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
2064 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
2065 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
2066 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2069 info
->hThread
= info
->hProcess
= 0;
2070 info
->dwProcessId
= info
->dwThreadId
= 0;
2072 if (binary_info
.flags
& BINARY_FLAG_DLL
)
2074 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
2075 SetLastError( ERROR_BAD_EXE_FORMAT
);
2077 else switch (binary_info
.type
)
2080 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2081 debugstr_w(name
), binary_info
.res_start
, binary_info
.res_end
);
2082 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2083 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2088 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2089 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2090 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2092 case BINARY_UNIX_LIB
:
2093 TRACE( "starting %s as Winelib app\n", debugstr_w(name
) );
2094 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2095 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2097 case BINARY_UNKNOWN
:
2098 /* check for .com or .bat extension */
2099 if ((p
= strrchrW( name
, '.' )))
2101 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
2103 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
2104 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2105 inherit
, flags
, startup_info
, info
, unixdir
,
2106 &binary_info
, FALSE
);
2109 if (!strcmpiW( p
, batW
) || !strcmpiW( p
, cmdW
) )
2111 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
2112 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2113 inherit
, flags
, startup_info
, info
);
2118 case BINARY_UNIX_EXE
:
2120 /* unknown file, try as unix executable */
2123 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
2125 if ((unix_name
= wine_get_unix_file_name( name
)))
2127 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
, flags
, startup_info
) != -1);
2128 HeapFree( GetProcessHeap(), 0, unix_name
);
2133 if (hFile
) CloseHandle( hFile
);
2136 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
2137 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
2138 HeapFree( GetProcessHeap(), 0, unixdir
);
2140 TRACE( "started process pid %04x tid %04x\n", info
->dwProcessId
, info
->dwThreadId
);
2145 /**********************************************************************
2148 static void exec_process( LPCWSTR name
)
2152 STARTUPINFOW startup_info
;
2153 PROCESS_INFORMATION info
;
2154 struct binary_info binary_info
;
2156 hFile
= open_exe_file( name
, &binary_info
);
2157 if (!hFile
|| hFile
== INVALID_HANDLE_VALUE
) return;
2159 memset( &startup_info
, 0, sizeof(startup_info
) );
2160 startup_info
.cb
= sizeof(startup_info
);
2162 /* Determine executable type */
2164 if (binary_info
.flags
& BINARY_FLAG_DLL
) return;
2165 switch (binary_info
.type
)
2168 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2169 debugstr_w(name
), binary_info
.res_start
, binary_info
.res_end
);
2170 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2171 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2173 case BINARY_UNIX_LIB
:
2174 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
2175 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2176 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2178 case BINARY_UNKNOWN
:
2179 /* check for .com or .pif extension */
2180 if (!(p
= strrchrW( name
, '.' ))) break;
2181 if (strcmpiW( p
, comW
) && strcmpiW( p
, pifW
)) break;
2186 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2187 create_vdm_process( name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2188 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2193 CloseHandle( hFile
);
2197 /***********************************************************************
2200 * Wrapper to call WaitForInputIdle USER function
2202 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2204 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2206 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2209 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2210 if (ptr
) return ptr( process
, timeout
);
2216 /***********************************************************************
2217 * WinExec (KERNEL32.@)
2219 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2221 PROCESS_INFORMATION info
;
2222 STARTUPINFOA startup
;
2226 memset( &startup
, 0, sizeof(startup
) );
2227 startup
.cb
= sizeof(startup
);
2228 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2229 startup
.wShowWindow
= nCmdShow
;
2231 /* cmdline needs to be writable for CreateProcess */
2232 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2233 strcpy( cmdline
, lpCmdLine
);
2235 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2236 0, NULL
, NULL
, &startup
, &info
))
2238 /* Give 30 seconds to the app to come up */
2239 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2240 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2242 /* Close off the handles */
2243 CloseHandle( info
.hThread
);
2244 CloseHandle( info
.hProcess
);
2246 else if ((ret
= GetLastError()) >= 32)
2248 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2251 HeapFree( GetProcessHeap(), 0, cmdline
);
2256 /**********************************************************************
2257 * LoadModule (KERNEL32.@)
2259 HINSTANCE WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2261 LOADPARMS32
*params
= paramBlock
;
2262 PROCESS_INFORMATION info
;
2263 STARTUPINFOA startup
;
2264 HINSTANCE hInstance
;
2266 char filename
[MAX_PATH
];
2269 if (!name
) return (HINSTANCE
)ERROR_FILE_NOT_FOUND
;
2271 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2272 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2273 return ULongToHandle(GetLastError());
2275 len
= (BYTE
)params
->lpCmdLine
[0];
2276 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2277 return (HINSTANCE
)ERROR_NOT_ENOUGH_MEMORY
;
2279 strcpy( cmdline
, filename
);
2280 p
= cmdline
+ strlen(cmdline
);
2282 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2285 memset( &startup
, 0, sizeof(startup
) );
2286 startup
.cb
= sizeof(startup
);
2287 if (params
->lpCmdShow
)
2289 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2290 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2293 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2294 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2296 /* Give 30 seconds to the app to come up */
2297 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2298 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2299 hInstance
= (HINSTANCE
)33;
2300 /* Close off the handles */
2301 CloseHandle( info
.hThread
);
2302 CloseHandle( info
.hProcess
);
2304 else if ((hInstance
= ULongToHandle(GetLastError())) >= (HINSTANCE
)32)
2306 FIXME("Strange error set by CreateProcess: %p\n", hInstance
);
2307 hInstance
= (HINSTANCE
)11;
2310 HeapFree( GetProcessHeap(), 0, cmdline
);
2315 /******************************************************************************
2316 * TerminateProcess (KERNEL32.@)
2318 * Terminates a process.
2321 * handle [I] Process to terminate.
2322 * exit_code [I] Exit code.
2326 * Failure: FALSE, check GetLastError().
2328 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2330 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2331 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2335 /***********************************************************************
2336 * ExitProcess (KERNEL32.@)
2338 * Exits the current process.
2341 * status [I] Status code to exit with.
2347 __ASM_STDCALL_FUNC( ExitProcess
, 4, /* Shrinker depend on this particular ExitProcess implementation */
2349 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2350 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2351 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2353 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2357 void WINAPI
process_ExitProcess( DWORD status
)
2359 LdrShutdownProcess();
2360 NtTerminateProcess(GetCurrentProcess(), status
);
2366 void WINAPI
ExitProcess( DWORD status
)
2368 LdrShutdownProcess();
2369 NtTerminateProcess(GetCurrentProcess(), status
);
2375 /***********************************************************************
2376 * GetExitCodeProcess [KERNEL32.@]
2378 * Gets termination status of specified process.
2381 * hProcess [in] Handle to the process.
2382 * lpExitCode [out] Address to receive termination status.
2388 BOOL WINAPI
GetExitCodeProcess( HANDLE hProcess
, LPDWORD lpExitCode
)
2391 PROCESS_BASIC_INFORMATION pbi
;
2393 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2395 if (status
== STATUS_SUCCESS
)
2397 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2400 SetLastError( RtlNtStatusToDosError(status
) );
2405 /***********************************************************************
2406 * SetErrorMode (KERNEL32.@)
2408 UINT WINAPI
SetErrorMode( UINT mode
)
2410 UINT old
= process_error_mode
;
2411 process_error_mode
= mode
;
2415 /***********************************************************************
2416 * GetErrorMode (KERNEL32.@)
2418 UINT WINAPI
GetErrorMode( void )
2420 return process_error_mode
;
2423 /**********************************************************************
2424 * TlsAlloc [KERNEL32.@]
2426 * Allocates a thread local storage index.
2429 * Success: TLS index.
2430 * Failure: 0xFFFFFFFF
2432 DWORD WINAPI
TlsAlloc( void )
2435 PEB
* const peb
= NtCurrentTeb()->Peb
;
2437 RtlAcquirePebLock();
2438 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 0 );
2439 if (index
!= ~0U) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2442 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2445 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2446 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2447 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2449 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2451 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2455 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2456 index
+= TLS_MINIMUM_AVAILABLE
;
2459 else SetLastError( ERROR_NO_MORE_ITEMS
);
2461 RtlReleasePebLock();
2466 /**********************************************************************
2467 * TlsFree [KERNEL32.@]
2469 * Releases a thread local storage index, making it available for reuse.
2472 * index [in] TLS index to free.
2478 BOOL WINAPI
TlsFree( DWORD index
)
2482 RtlAcquirePebLock();
2483 if (index
>= TLS_MINIMUM_AVAILABLE
)
2485 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2486 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2490 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2491 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2493 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2494 else SetLastError( ERROR_INVALID_PARAMETER
);
2495 RtlReleasePebLock();
2500 /**********************************************************************
2501 * TlsGetValue [KERNEL32.@]
2503 * Gets value in a thread's TLS slot.
2506 * index [in] TLS index to retrieve value for.
2509 * Success: Value stored in calling thread's TLS slot for index.
2510 * Failure: 0 and GetLastError() returns NO_ERROR.
2512 LPVOID WINAPI
TlsGetValue( DWORD index
)
2516 if (index
< TLS_MINIMUM_AVAILABLE
)
2518 ret
= NtCurrentTeb()->TlsSlots
[index
];
2522 index
-= TLS_MINIMUM_AVAILABLE
;
2523 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2525 SetLastError( ERROR_INVALID_PARAMETER
);
2528 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2529 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2531 SetLastError( ERROR_SUCCESS
);
2536 /**********************************************************************
2537 * TlsSetValue [KERNEL32.@]
2539 * Stores a value in the thread's TLS slot.
2542 * index [in] TLS index to set value for.
2543 * value [in] Value to be stored.
2549 BOOL WINAPI
TlsSetValue( DWORD index
, LPVOID value
)
2551 if (index
< TLS_MINIMUM_AVAILABLE
)
2553 NtCurrentTeb()->TlsSlots
[index
] = value
;
2557 index
-= TLS_MINIMUM_AVAILABLE
;
2558 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2560 SetLastError( ERROR_INVALID_PARAMETER
);
2563 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2564 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2565 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2567 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2570 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2576 /***********************************************************************
2577 * GetProcessFlags (KERNEL32.@)
2579 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2581 IMAGE_NT_HEADERS
*nt
;
2584 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2586 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2588 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2589 flags
|= PDB32_CONSOLE_PROC
;
2591 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2592 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2597 /***********************************************************************
2598 * GetProcessDword (KERNEL32.18)
2600 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
2602 FIXME( "(%d, %d): not supported\n", dwProcessID
, offset
);
2607 /*********************************************************************
2608 * OpenProcess (KERNEL32.@)
2610 * Opens a handle to a process.
2613 * access [I] Desired access rights assigned to the returned handle.
2614 * inherit [I] Determines whether or not child processes will inherit the handle.
2615 * id [I] Process identifier of the process to get a handle to.
2618 * Success: Valid handle to the specified process.
2619 * Failure: NULL, check GetLastError().
2621 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2625 OBJECT_ATTRIBUTES attr
;
2628 cid
.UniqueProcess
= ULongToHandle(id
);
2629 cid
.UniqueThread
= 0; /* FIXME ? */
2631 attr
.Length
= sizeof(OBJECT_ATTRIBUTES
);
2632 attr
.RootDirectory
= NULL
;
2633 attr
.Attributes
= inherit
? OBJ_INHERIT
: 0;
2634 attr
.SecurityDescriptor
= NULL
;
2635 attr
.SecurityQualityOfService
= NULL
;
2636 attr
.ObjectName
= NULL
;
2638 if (GetVersion() & 0x80000000) access
= PROCESS_ALL_ACCESS
;
2640 status
= NtOpenProcess(&handle
, access
, &attr
, &cid
);
2641 if (status
!= STATUS_SUCCESS
)
2643 SetLastError( RtlNtStatusToDosError(status
) );
2650 /*********************************************************************
2651 * GetProcessId (KERNEL32.@)
2653 * Gets the a unique identifier of a process.
2656 * hProcess [I] Handle to the process.
2660 * Failure: FALSE, check GetLastError().
2664 * The identifier is unique only on the machine and only until the process
2665 * exits (including system shutdown).
2667 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2670 PROCESS_BASIC_INFORMATION pbi
;
2672 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2674 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2675 SetLastError( RtlNtStatusToDosError(status
) );
2680 /*********************************************************************
2681 * CloseHandle (KERNEL32.@)
2686 * handle [I] Handle to close.
2690 * Failure: FALSE, check GetLastError().
2692 BOOL WINAPI
CloseHandle( HANDLE handle
)
2696 /* stdio handles need special treatment */
2697 if ((handle
== (HANDLE
)STD_INPUT_HANDLE
) ||
2698 (handle
== (HANDLE
)STD_OUTPUT_HANDLE
) ||
2699 (handle
== (HANDLE
)STD_ERROR_HANDLE
))
2700 handle
= GetStdHandle( HandleToULong(handle
) );
2702 if (is_console_handle(handle
))
2703 return CloseConsoleHandle(handle
);
2705 status
= NtClose( handle
);
2706 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2711 /*********************************************************************
2712 * GetHandleInformation (KERNEL32.@)
2714 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2716 OBJECT_DATA_INFORMATION info
;
2717 NTSTATUS status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
);
2719 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2723 if (info
.InheritHandle
) *flags
|= HANDLE_FLAG_INHERIT
;
2724 if (info
.ProtectFromClose
) *flags
|= HANDLE_FLAG_PROTECT_FROM_CLOSE
;
2730 /*********************************************************************
2731 * SetHandleInformation (KERNEL32.@)
2733 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2735 OBJECT_DATA_INFORMATION info
;
2738 /* if not setting both fields, retrieve current value first */
2739 if ((mask
& (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
)) !=
2740 (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
))
2742 if ((status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
)))
2744 SetLastError( RtlNtStatusToDosError(status
) );
2748 if (mask
& HANDLE_FLAG_INHERIT
)
2749 info
.InheritHandle
= (flags
& HANDLE_FLAG_INHERIT
) != 0;
2750 if (mask
& HANDLE_FLAG_PROTECT_FROM_CLOSE
)
2751 info
.ProtectFromClose
= (flags
& HANDLE_FLAG_PROTECT_FROM_CLOSE
) != 0;
2753 status
= NtSetInformationObject( handle
, ObjectDataInformation
, &info
, sizeof(info
) );
2754 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2759 /*********************************************************************
2760 * DuplicateHandle (KERNEL32.@)
2762 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2763 HANDLE dest_process
, HANDLE
*dest
,
2764 DWORD access
, BOOL inherit
, DWORD options
)
2768 if (is_console_handle(source
))
2770 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2771 if (source_process
!= dest_process
||
2772 source_process
!= GetCurrentProcess())
2774 SetLastError(ERROR_INVALID_PARAMETER
);
2777 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2778 return (*dest
!= INVALID_HANDLE_VALUE
);
2780 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2781 access
, inherit
? OBJ_INHERIT
: 0, options
);
2782 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2787 /***********************************************************************
2788 * ConvertToGlobalHandle (KERNEL32.@)
2790 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
2792 HANDLE ret
= INVALID_HANDLE_VALUE
;
2793 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
2794 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
2799 /***********************************************************************
2800 * SetHandleContext (KERNEL32.@)
2802 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
2804 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2805 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
2806 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2811 /***********************************************************************
2812 * GetHandleContext (KERNEL32.@)
2814 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
2816 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2817 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
2818 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2823 /***********************************************************************
2824 * CreateSocketHandle (KERNEL32.@)
2826 HANDLE WINAPI
CreateSocketHandle(void)
2828 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2829 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2830 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2831 return INVALID_HANDLE_VALUE
;
2835 /***********************************************************************
2836 * SetPriorityClass (KERNEL32.@)
2838 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
2841 PROCESS_PRIORITY_CLASS ppc
;
2843 ppc
.Foreground
= FALSE
;
2844 switch (priorityclass
)
2846 case IDLE_PRIORITY_CLASS
:
2847 ppc
.PriorityClass
= PROCESS_PRIOCLASS_IDLE
; break;
2848 case BELOW_NORMAL_PRIORITY_CLASS
:
2849 ppc
.PriorityClass
= PROCESS_PRIOCLASS_BELOW_NORMAL
; break;
2850 case NORMAL_PRIORITY_CLASS
:
2851 ppc
.PriorityClass
= PROCESS_PRIOCLASS_NORMAL
; break;
2852 case ABOVE_NORMAL_PRIORITY_CLASS
:
2853 ppc
.PriorityClass
= PROCESS_PRIOCLASS_ABOVE_NORMAL
; break;
2854 case HIGH_PRIORITY_CLASS
:
2855 ppc
.PriorityClass
= PROCESS_PRIOCLASS_HIGH
; break;
2856 case REALTIME_PRIORITY_CLASS
:
2857 ppc
.PriorityClass
= PROCESS_PRIOCLASS_REALTIME
; break;
2859 SetLastError(ERROR_INVALID_PARAMETER
);
2863 status
= NtSetInformationProcess(hprocess
, ProcessPriorityClass
,
2866 if (status
!= STATUS_SUCCESS
)
2868 SetLastError( RtlNtStatusToDosError(status
) );
2875 /***********************************************************************
2876 * GetPriorityClass (KERNEL32.@)
2878 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
2881 PROCESS_BASIC_INFORMATION pbi
;
2883 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2885 if (status
!= STATUS_SUCCESS
)
2887 SetLastError( RtlNtStatusToDosError(status
) );
2890 switch (pbi
.BasePriority
)
2892 case PROCESS_PRIOCLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
2893 case PROCESS_PRIOCLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
2894 case PROCESS_PRIOCLASS_NORMAL
: return NORMAL_PRIORITY_CLASS
;
2895 case PROCESS_PRIOCLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
2896 case PROCESS_PRIOCLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
2897 case PROCESS_PRIOCLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
2899 SetLastError( ERROR_INVALID_PARAMETER
);
2904 /***********************************************************************
2905 * SetProcessAffinityMask (KERNEL32.@)
2907 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
2911 status
= NtSetInformationProcess(hProcess
, ProcessAffinityMask
,
2912 &affmask
, sizeof(DWORD_PTR
));
2915 SetLastError( RtlNtStatusToDosError(status
) );
2922 /**********************************************************************
2923 * GetProcessAffinityMask (KERNEL32.@)
2925 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
2926 PDWORD_PTR lpProcessAffinityMask
,
2927 PDWORD_PTR lpSystemAffinityMask
)
2929 PROCESS_BASIC_INFORMATION pbi
;
2932 status
= NtQueryInformationProcess(hProcess
,
2933 ProcessBasicInformation
,
2934 &pbi
, sizeof(pbi
), NULL
);
2937 SetLastError( RtlNtStatusToDosError(status
) );
2940 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= pbi
.AffinityMask
;
2941 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= (1 << NtCurrentTeb()->Peb
->NumberOfProcessors
) - 1;
2946 /***********************************************************************
2947 * GetProcessVersion (KERNEL32.@)
2949 DWORD WINAPI
GetProcessVersion( DWORD pid
)
2953 PROCESS_BASIC_INFORMATION pbi
;
2956 IMAGE_DOS_HEADER dos
;
2957 IMAGE_NT_HEADERS nt
;
2960 if (!pid
|| pid
== GetCurrentProcessId())
2962 IMAGE_NT_HEADERS
*nt
;
2964 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2965 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
2966 nt
->OptionalHeader
.MinorSubsystemVersion
);
2970 process
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
2971 if (!process
) return 0;
2973 status
= NtQueryInformationProcess(process
, ProcessBasicInformation
, &pbi
, sizeof(pbi
), NULL
);
2974 if (status
) goto err
;
2976 status
= NtReadVirtualMemory(process
, pbi
.PebBaseAddress
, &peb
, sizeof(peb
), &count
);
2977 if (status
|| count
!= sizeof(peb
)) goto err
;
2979 memset(&dos
, 0, sizeof(dos
));
2980 status
= NtReadVirtualMemory(process
, peb
.ImageBaseAddress
, &dos
, sizeof(dos
), &count
);
2981 if (status
|| count
!= sizeof(dos
)) goto err
;
2982 if (dos
.e_magic
!= IMAGE_DOS_SIGNATURE
) goto err
;
2984 memset(&nt
, 0, sizeof(nt
));
2985 status
= NtReadVirtualMemory(process
, (char *)peb
.ImageBaseAddress
+ dos
.e_lfanew
, &nt
, sizeof(nt
), &count
);
2986 if (status
|| count
!= sizeof(nt
)) goto err
;
2987 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) goto err
;
2989 ver
= MAKELONG(nt
.OptionalHeader
.MinorSubsystemVersion
, nt
.OptionalHeader
.MajorSubsystemVersion
);
2992 CloseHandle(process
);
2994 if (status
!= STATUS_SUCCESS
)
2995 SetLastError(RtlNtStatusToDosError(status
));
3001 /***********************************************************************
3002 * SetProcessWorkingSetSize [KERNEL32.@]
3003 * Sets the min/max working set sizes for a specified process.
3006 * hProcess [I] Handle to the process of interest
3007 * minset [I] Specifies minimum working set size
3008 * maxset [I] Specifies maximum working set size
3014 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
3017 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
3018 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
3019 /* Trim the working set to zero */
3020 /* Swap the process out of physical RAM */
3025 /***********************************************************************
3026 * GetProcessWorkingSetSize (KERNEL32.@)
3028 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
3031 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
3032 /* 32 MB working set size */
3033 if (minset
) *minset
= 32*1024*1024;
3034 if (maxset
) *maxset
= 32*1024*1024;
3039 /***********************************************************************
3040 * SetProcessShutdownParameters (KERNEL32.@)
3042 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
3044 FIXME("(%08x, %08x): partial stub.\n", level
, flags
);
3045 shutdown_flags
= flags
;
3046 shutdown_priority
= level
;
3051 /***********************************************************************
3052 * GetProcessShutdownParameters (KERNEL32.@)
3055 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
3057 *lpdwLevel
= shutdown_priority
;
3058 *lpdwFlags
= shutdown_flags
;
3063 /***********************************************************************
3064 * GetProcessPriorityBoost (KERNEL32.@)
3066 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
3068 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
3070 /* Report that no boost is present.. */
3071 *pDisablePriorityBoost
= FALSE
;
3076 /***********************************************************************
3077 * SetProcessPriorityBoost (KERNEL32.@)
3079 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
3081 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
3082 /* Say we can do it. I doubt the program will notice that we don't. */
3087 /***********************************************************************
3088 * ReadProcessMemory (KERNEL32.@)
3090 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
3091 SIZE_T
*bytes_read
)
3093 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
3094 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3099 /***********************************************************************
3100 * WriteProcessMemory (KERNEL32.@)
3102 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
3103 SIZE_T
*bytes_written
)
3105 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
3106 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3111 /****************************************************************************
3112 * FlushInstructionCache (KERNEL32.@)
3114 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
3117 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
3118 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3123 /******************************************************************
3124 * GetProcessIoCounters (KERNEL32.@)
3126 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
3130 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
3131 ioc
, sizeof(*ioc
), NULL
);
3132 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3136 /******************************************************************
3137 * GetProcessHandleCount (KERNEL32.@)
3139 BOOL WINAPI
GetProcessHandleCount(HANDLE hProcess
, DWORD
*cnt
)
3143 status
= NtQueryInformationProcess(hProcess
, ProcessHandleCount
,
3144 cnt
, sizeof(*cnt
), NULL
);
3145 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3149 /******************************************************************
3150 * QueryFullProcessImageNameA (KERNEL32.@)
3152 BOOL WINAPI
QueryFullProcessImageNameA(HANDLE hProcess
, DWORD dwFlags
, LPSTR lpExeName
, PDWORD pdwSize
)
3155 DWORD pdwSizeW
= *pdwSize
;
3156 LPWSTR lpExeNameW
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, *pdwSize
* sizeof(WCHAR
));
3158 retval
= QueryFullProcessImageNameW(hProcess
, dwFlags
, lpExeNameW
, &pdwSizeW
);
3161 retval
= (0 != WideCharToMultiByte(CP_ACP
, 0, lpExeNameW
, -1,
3162 lpExeName
, *pdwSize
, NULL
, NULL
));
3164 *pdwSize
= strlen(lpExeName
);
3166 HeapFree(GetProcessHeap(), 0, lpExeNameW
);
3170 /******************************************************************
3171 * QueryFullProcessImageNameW (KERNEL32.@)
3173 BOOL WINAPI
QueryFullProcessImageNameW(HANDLE hProcess
, DWORD dwFlags
, LPWSTR lpExeName
, PDWORD pdwSize
)
3175 BYTE buffer
[sizeof(UNICODE_STRING
) + MAX_PATH
*sizeof(WCHAR
)]; /* this buffer should be enough */
3176 UNICODE_STRING
*dynamic_buffer
= NULL
;
3177 UNICODE_STRING nt_path
;
3178 UNICODE_STRING
*result
= NULL
;
3182 RtlInitUnicodeStringEx(&nt_path
, NULL
);
3183 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3184 * as this is on Wine. */
3185 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, buffer
,
3186 sizeof(buffer
) - sizeof(WCHAR
), &needed
);
3187 if (status
== STATUS_INFO_LENGTH_MISMATCH
)
3189 dynamic_buffer
= HeapAlloc(GetProcessHeap(), 0, needed
+ sizeof(WCHAR
));
3190 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, (LPBYTE
)dynamic_buffer
, needed
, &needed
);
3191 result
= dynamic_buffer
;
3194 result
= (PUNICODE_STRING
)buffer
;
3196 if (status
) goto cleanup
;
3198 if (dwFlags
& PROCESS_NAME_NATIVE
)
3200 result
->Buffer
[result
->Length
/ sizeof(WCHAR
)] = 0;
3201 if (!RtlDosPathNameToNtPathName_U(result
->Buffer
, &nt_path
, NULL
, NULL
))
3203 status
= STATUS_OBJECT_PATH_NOT_FOUND
;
3209 if (result
->Length
/sizeof(WCHAR
) + 1 > *pdwSize
)
3211 status
= STATUS_BUFFER_TOO_SMALL
;
3215 *pdwSize
= result
->Length
/sizeof(WCHAR
);
3216 memcpy( lpExeName
, result
->Buffer
, result
->Length
);
3217 lpExeName
[*pdwSize
] = 0;
3220 HeapFree(GetProcessHeap(), 0, dynamic_buffer
);
3221 RtlFreeUnicodeString(&nt_path
);
3222 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3226 /***********************************************************************
3227 * ProcessIdToSessionId (KERNEL32.@)
3228 * This function is available on Terminal Server 4SP4 and Windows 2000
3230 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
3232 /* According to MSDN, if the calling process is not in a terminal
3233 * services environment, then the sessionid returned is zero.
3240 /***********************************************************************
3241 * RegisterServiceProcess (KERNEL32.@)
3243 * A service process calls this function to ensure that it continues to run
3244 * even after a user logged off.
3246 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
3248 /* I don't think that Wine needs to do anything in this function */
3249 return 1; /* success */
3253 /**********************************************************************
3254 * IsWow64Process (KERNEL32.@)
3256 BOOL WINAPI
IsWow64Process(HANDLE hProcess
, PBOOL Wow64Process
)
3261 status
= NtQueryInformationProcess( hProcess
, ProcessWow64Information
, &pbi
, sizeof(pbi
), NULL
);
3263 if (status
!= STATUS_SUCCESS
)
3265 SetLastError( RtlNtStatusToDosError( status
) );
3268 *Wow64Process
= (pbi
!= 0);
3273 /***********************************************************************
3274 * GetCurrentProcess (KERNEL32.@)
3276 * Get a handle to the current process.
3282 * A handle representing the current process.
3284 #undef GetCurrentProcess
3285 HANDLE WINAPI
GetCurrentProcess(void)
3287 return (HANDLE
)~(ULONG_PTR
)0;
3290 /***********************************************************************
3291 * CmdBatNotification (KERNEL32.@)
3293 * Notifies the system that a batch file has started or finished.
3296 * bBatchRunning [I] TRUE if a batch file has started or
3297 * FALSE if a batch file has finished executing.
3302 BOOL WINAPI
CmdBatNotification( BOOL bBatchRunning
)
3304 FIXME("%d\n", bBatchRunning
);
3309 /***********************************************************************
3310 * RegisterApplicationRestart (KERNEL32.@)
3312 HRESULT WINAPI
RegisterApplicationRestart(PCWSTR pwzCommandLine
, DWORD dwFlags
)
3314 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine
), dwFlags
);
3319 /**********************************************************************
3320 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3322 DWORD WINAPI
WTSGetActiveConsoleSessionId(void)