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_READ
, &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_READ
, &attr
.RootDirectory
) != STATUS_SUCCESS
) return ret
;
445 RtlInitUnicodeString( &nameW
, envW
);
446 if (NtOpenKey( &hkey
, KEY_READ
, &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_READ
, &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
)))
832 ANSI_STRING unix_name
;
833 UNICODE_STRING nt_name
;
834 RtlInitAnsiString( &unix_name
, pwd
);
835 if (!wine_unix_to_nt_file_name( &unix_name
, &nt_name
))
837 UNICODE_STRING dos_path
;
838 /* skip the \??\ prefix, nt_name is 0 terminated */
839 RtlInitUnicodeString( &dos_path
, nt_name
.Buffer
+ 4 );
840 RtlSetCurrentDirectory_U( &dos_path
);
841 RtlFreeUnicodeString( &nt_name
);
845 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
847 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
848 "starting in the Windows directory.\n", cwd
? cwd
: "" );
849 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
850 RtlSetCurrentDirectory_U( &dir_str
);
852 HeapFree( GetProcessHeap(), 0, cwd
);
855 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
856 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
860 /***********************************************************************
863 * Initialize the windows and system directories from the environment.
865 static void init_windows_dirs(void)
867 extern void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
869 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
870 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
871 static const WCHAR default_windirW
[] = {'C',':','\\','w','i','n','d','o','w','s',0};
872 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m','3','2',0};
873 static const WCHAR default_syswow64W
[] = {'\\','s','y','s','w','o','w','6','4',0};
878 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
880 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
881 GetEnvironmentVariableW( windirW
, buffer
, len
);
882 DIR_Windows
= buffer
;
884 else DIR_Windows
= default_windirW
;
886 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
888 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
889 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
894 len
= strlenW( DIR_Windows
);
895 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
896 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
897 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
901 if (!CreateDirectoryW( DIR_Windows
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
902 ERR( "directory %s could not be created, error %u\n",
903 debugstr_w(DIR_Windows
), GetLastError() );
904 if (!CreateDirectoryW( DIR_System
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
905 ERR( "directory %s could not be created, error %u\n",
906 debugstr_w(DIR_System
), GetLastError() );
908 #ifndef _WIN64 /* SysWow64 is always defined on 64-bit */
912 len
= strlenW( DIR_Windows
);
913 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_syswow64W
) );
914 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
915 memcpy( buffer
+ len
, default_syswow64W
, sizeof(default_syswow64W
) );
916 DIR_SysWow64
= buffer
;
917 if (!CreateDirectoryW( DIR_SysWow64
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
918 ERR( "directory %s could not be created, error %u\n",
919 debugstr_w(DIR_SysWow64
), GetLastError() );
922 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
923 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
925 /* set the directories in ntdll too */
926 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
930 /***********************************************************************
933 * Start the wineboot process if necessary. Return the handles to wait on.
935 static void start_wineboot( HANDLE handles
[2] )
937 static const WCHAR wineboot_eventW
[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
940 if (!(handles
[0] = CreateEventW( NULL
, TRUE
, FALSE
, wineboot_eventW
)))
942 ERR( "failed to create wineboot event, expect trouble\n" );
945 if (GetLastError() != ERROR_ALREADY_EXISTS
) /* we created it */
947 static const WCHAR wineboot
[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
948 static const WCHAR args
[] = {' ','-','-','i','n','i','t',0};
949 const DWORD expected_type
= (sizeof(void*) > sizeof(int) || is_wow64
) ?
950 SCS_64BIT_BINARY
: SCS_32BIT_BINARY
;
952 PROCESS_INFORMATION pi
;
956 WCHAR cmdline
[MAX_PATH
+ (sizeof(wineboot
) + sizeof(args
)) / sizeof(WCHAR
)];
958 memset( &si
, 0, sizeof(si
) );
960 si
.dwFlags
= STARTF_USESTDHANDLES
;
963 si
.hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
965 GetSystemDirectoryW( app
, MAX_PATH
- sizeof(wineboot
)/sizeof(WCHAR
) );
966 lstrcatW( app
, wineboot
);
968 Wow64DisableWow64FsRedirection( &redir
);
969 if (GetBinaryTypeW( app
, &type
) && type
!= expected_type
)
971 if (type
== SCS_64BIT_BINARY
)
972 MESSAGE( "wine: '%s' is a 64-bit prefix, it cannot be used with 32-bit Wine.\n",
973 wine_get_config_dir() );
975 MESSAGE( "wine: '%s' is a 32-bit prefix, it cannot be used with %s Wine.\n",
976 wine_get_config_dir(), is_wow64
? "wow64" : "64-bit" );
980 strcpyW( cmdline
, app
);
981 strcatW( cmdline
, args
);
982 if (CreateProcessW( app
, cmdline
, NULL
, NULL
, FALSE
, DETACHED_PROCESS
, NULL
, NULL
, &si
, &pi
))
984 TRACE( "started wineboot pid %04x tid %04x\n", pi
.dwProcessId
, pi
.dwThreadId
);
985 CloseHandle( pi
.hThread
);
986 handles
[1] = pi
.hProcess
;
990 ERR( "failed to start wineboot, err %u\n", GetLastError() );
991 CloseHandle( handles
[0] );
994 Wow64RevertWow64FsRedirection( redir
);
999 /***********************************************************************
1002 * Startup routine of a new process. Runs on the new process stack.
1004 static DWORD WINAPI
start_process( PEB
*peb
)
1006 IMAGE_NT_HEADERS
*nt
;
1007 LPTHREAD_START_ROUTINE entry
;
1009 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1010 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
1011 nt
->OptionalHeader
.AddressOfEntryPoint
);
1013 if (!nt
->OptionalHeader
.AddressOfEntryPoint
)
1015 ERR( "%s doesn't have an entry point, it cannot be executed\n",
1016 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
) );
1020 if (TRACE_ON(relay
))
1021 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1022 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
1024 SetLastError( 0 ); /* clear error code */
1025 if (peb
->BeingDebugged
) DbgBreakPoint();
1026 return entry( peb
);
1030 /***********************************************************************
1033 * Change the process name in the ps output.
1035 static void set_process_name( int argc
, char *argv
[] )
1037 #ifdef HAVE_SETPROCTITLE
1038 setproctitle("-%s", argv
[1]);
1043 char *p
, *prctl_name
= argv
[1];
1044 char *end
= argv
[argc
-1] + strlen(argv
[argc
-1]) + 1;
1047 # define PR_SET_NAME 15
1050 if ((p
= strrchr( prctl_name
, '\\' ))) prctl_name
= p
+ 1;
1051 if ((p
= strrchr( prctl_name
, '/' ))) prctl_name
= p
+ 1;
1053 if (prctl( PR_SET_NAME
, prctl_name
) != -1)
1055 offset
= argv
[1] - argv
[0];
1056 memmove( argv
[1] - offset
, argv
[1], end
- argv
[1] );
1057 memset( end
- offset
, 0, offset
);
1058 for (i
= 1; i
< argc
; i
++) argv
[i
-1] = argv
[i
] - offset
;
1062 #endif /* HAVE_PRCTL */
1064 /* remove argv[0] */
1065 memmove( argv
, argv
+ 1, argc
* sizeof(argv
[0]) );
1070 /***********************************************************************
1071 * __wine_kernel_init
1073 * Wine initialisation: load and start the main exe file.
1075 void CDECL
__wine_kernel_init(void)
1077 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
1078 static const WCHAR dotW
[] = {'.',0};
1079 static const WCHAR exeW
[] = {'.','e','x','e',0};
1081 WCHAR
*p
, main_exe_name
[MAX_PATH
+1];
1082 PEB
*peb
= NtCurrentTeb()->Peb
;
1083 RTL_USER_PROCESS_PARAMETERS
*params
= peb
->ProcessParameters
;
1084 HANDLE boot_events
[2];
1085 BOOL got_environment
= TRUE
;
1087 /* Initialize everything */
1089 setbuf(stdout
,NULL
);
1090 setbuf(stderr
,NULL
);
1091 kernel32_handle
= GetModuleHandleW(kernel32W
);
1092 IsWow64Process( GetCurrentProcess(), &is_wow64
);
1096 if (!params
->Environment
)
1098 /* Copy the parent environment */
1099 if (!build_initial_environment()) exit(1);
1101 /* convert old configuration to new format */
1102 convert_old_config();
1104 got_environment
= set_registry_environment();
1105 set_additional_environment();
1108 init_windows_dirs();
1109 init_current_directory( ¶ms
->CurrentDirectory
);
1111 set_process_name( __wine_main_argc
, __wine_main_argv
);
1112 set_library_wargv( __wine_main_argv
);
1113 boot_events
[0] = boot_events
[1] = 0;
1115 if (peb
->ProcessParameters
->ImagePathName
.Buffer
)
1117 strcpyW( main_exe_name
, peb
->ProcessParameters
->ImagePathName
.Buffer
);
1121 struct binary_info binary_info
;
1123 if (!SearchPathW( NULL
, __wine_main_wargv
[0], exeW
, MAX_PATH
, main_exe_name
, NULL
) &&
1124 !get_builtin_path( __wine_main_wargv
[0], exeW
, main_exe_name
, MAX_PATH
, &binary_info
))
1126 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1127 ExitProcess( GetLastError() );
1129 update_library_argv0( main_exe_name
);
1130 if (!build_command_line( __wine_main_wargv
)) goto error
;
1131 start_wineboot( boot_events
);
1134 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1135 p
= strrchrW( main_exe_name
, '.' );
1136 if (!p
|| strchrW( p
, '/' ) || strchrW( p
, '\\' )) strcatW( main_exe_name
, dotW
);
1138 TRACE( "starting process name=%s argv[0]=%s\n",
1139 debugstr_w(main_exe_name
), debugstr_w(__wine_main_wargv
[0]) );
1141 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1142 MODULE_get_dll_load_path(main_exe_name
) );
1146 DWORD timeout
= 30000, count
= 1;
1148 if (boot_events
[1]) count
++;
1149 if (!got_environment
) timeout
= 300000; /* initial prefix creation can take longer */
1150 if (WaitForMultipleObjects( count
, boot_events
, FALSE
, timeout
) == WAIT_TIMEOUT
)
1151 ERR( "boot event wait timed out\n" );
1152 CloseHandle( boot_events
[0] );
1153 if (boot_events
[1]) CloseHandle( boot_events
[1] );
1154 /* if we didn't find environment section, try again now that wineboot has run */
1155 if (!got_environment
)
1157 set_registry_environment();
1158 set_additional_environment();
1162 if (!(peb
->ImageBaseAddress
= LoadLibraryExW( main_exe_name
, 0, DONT_RESOLVE_DLL_REFERENCES
)))
1167 DWORD error
= GetLastError();
1169 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1170 if (error
== ERROR_BAD_EXE_FORMAT
||
1171 error
== ERROR_INVALID_ADDRESS
||
1172 error
== ERROR_NOT_ENOUGH_MEMORY
)
1174 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name
);
1175 /* if we get back here, it failed */
1177 else if (error
== ERROR_MOD_NOT_FOUND
)
1179 if ((p
= strrchrW( main_exe_name
, '\\' ))) p
++;
1180 else p
= main_exe_name
;
1181 if (!strcmpiW( p
, winevdmW
) && __wine_main_argc
> 3)
1183 /* args 1 and 2 are --app-name full_path */
1184 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1185 debugstr_w(__wine_main_wargv
[3]) );
1186 ExitProcess( ERROR_BAD_EXE_FORMAT
);
1189 args
[0] = (DWORD_PTR
)main_exe_name
;
1190 FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ARGUMENT_ARRAY
,
1191 NULL
, error
, 0, msgW
, sizeof(msgW
)/sizeof(WCHAR
), (__ms_va_list
*)args
);
1192 WideCharToMultiByte( CP_ACP
, 0, msgW
, -1, msg
, sizeof(msg
), NULL
, NULL
);
1193 MESSAGE( "wine: %s", msg
);
1194 ExitProcess( error
);
1197 LdrInitializeThunk( start_process
, 0, 0, 0 );
1200 ExitProcess( GetLastError() );
1204 /***********************************************************************
1207 * Build an argv array from a command-line.
1208 * 'reserved' is the number of args to reserve before the first one.
1210 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1214 char *arg
,*s
,*d
,*cmdline
;
1215 int in_quotes
,bcount
,len
;
1217 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1218 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, len
))) return NULL
;
1219 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1226 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1229 /* skip the remaining spaces */
1230 while (*s
==' ' || *s
=='\t') {
1237 } else if (*s
=='\\') {
1238 /* '\', count them */
1240 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1242 in_quotes
=!in_quotes
;
1245 /* a regular character */
1250 if (!(argv
= HeapAlloc( GetProcessHeap(), 0, argc
*sizeof(*argv
) + len
)))
1252 HeapFree( GetProcessHeap(), 0, cmdline
);
1256 arg
= d
= s
= (char *)(argv
+ argc
);
1257 memcpy( d
, cmdline
, len
);
1262 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1263 /* Close the argument and copy it */
1267 /* skip the remaining spaces */
1270 } while (*s
==' ' || *s
=='\t');
1272 /* Start with a new argument */
1275 } else if (*s
=='\\') {
1279 } else if (*s
=='"') {
1281 if ((bcount
& 1)==0) {
1282 /* Preceded by an even number of '\', this is half that
1283 * number of '\', plus a '"' which we discard.
1287 in_quotes
=!in_quotes
;
1289 /* Preceded by an odd number of '\', this is half that
1290 * number of '\' followed by a '"'
1298 /* a regular character */
1309 HeapFree( GetProcessHeap(), 0, cmdline
);
1314 /***********************************************************************
1317 * Build the environment of a new child process.
1319 static char **build_envp( const WCHAR
*envW
)
1321 static const char * const unix_vars
[] = { "PATH", "TEMP", "TMP", "HOME" };
1326 int count
= 1, length
;
1329 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1331 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1332 if (!(env
= HeapAlloc( GetProcessHeap(), 0, length
))) return NULL
;
1333 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1335 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1336 if (is_special_env_var( p
)) length
+= 4; /* prefix it with "WINE" */
1338 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1340 if (!(p
= getenv(unix_vars
[i
]))) continue;
1341 length
+= strlen(unix_vars
[i
]) + strlen(p
) + 2;
1345 if ((envp
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*envp
) + length
)))
1347 char **envptr
= envp
;
1348 char *dst
= (char *)(envp
+ count
);
1350 /* some variables must not be modified, so we get them directly from the unix env */
1351 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1353 if (!(p
= getenv(unix_vars
[i
]))) continue;
1354 *envptr
++ = strcpy( dst
, unix_vars
[i
] );
1357 dst
+= strlen(dst
) + 1;
1360 /* now put the Windows environment strings */
1361 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1363 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1364 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1365 if (!strncmp( p
, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1366 if (!strncmp( p
, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1367 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1369 *envptr
++ = strcpy( dst
, "WINE" );
1374 *envptr
++ = strcpy( dst
, p
);
1376 dst
+= strlen(dst
) + 1;
1380 HeapFree( GetProcessHeap(), 0, env
);
1385 /***********************************************************************
1388 * Fork and exec a new Unix binary, checking for errors.
1390 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
, const WCHAR
*env
,
1391 const char *newdir
, DWORD flags
, STARTUPINFOW
*startup
)
1393 int fd
[2], stdin_fd
= -1, stdout_fd
= -1;
1395 char **argv
, **envp
;
1397 if (!env
) env
= GetEnvironmentStringsW();
1400 if (pipe2( fd
, O_CLOEXEC
) == -1)
1405 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1408 fcntl( fd
[0], F_SETFD
, FD_CLOEXEC
);
1409 fcntl( fd
[1], F_SETFD
, FD_CLOEXEC
);
1412 if (!(flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1414 HANDLE hstdin
, hstdout
;
1416 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1418 hstdin
= startup
->hStdInput
;
1419 hstdout
= startup
->hStdOutput
;
1423 hstdin
= GetStdHandle(STD_INPUT_HANDLE
);
1424 hstdout
= GetStdHandle(STD_OUTPUT_HANDLE
);
1427 if (is_console_handle( hstdin
))
1428 hstdin
= wine_server_ptr_handle( console_handle_unmap( hstdin
));
1429 if (is_console_handle( hstdout
))
1430 hstdout
= wine_server_ptr_handle( console_handle_unmap( hstdout
));
1431 wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1432 wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1435 argv
= build_argv( cmdline
, 0 );
1436 envp
= build_envp( env
);
1438 if (!(pid
= fork())) /* child */
1442 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1445 if (!(pid
= fork()))
1447 int fd
= open( "/dev/null", O_RDWR
);
1449 /* close stdin and stdout */
1457 else if (pid
!= -1) _exit(0); /* parent */
1463 dup2( stdin_fd
, 0 );
1466 if (stdout_fd
!= -1)
1468 dup2( stdout_fd
, 1 );
1473 /* Reset signals that we previously set to SIG_IGN */
1474 signal( SIGPIPE
, SIG_DFL
);
1475 signal( SIGCHLD
, SIG_DFL
);
1477 if (newdir
) chdir(newdir
);
1479 if (argv
&& envp
) execve( filename
, argv
, envp
);
1481 write( fd
[1], &err
, sizeof(err
) );
1484 HeapFree( GetProcessHeap(), 0, argv
);
1485 HeapFree( GetProcessHeap(), 0, envp
);
1486 if (stdin_fd
!= -1) close( stdin_fd
);
1487 if (stdout_fd
!= -1) close( stdout_fd
);
1489 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1494 if (pid
== -1) FILE_SetDosError();
1500 static inline DWORD
append_string( void **ptr
, const WCHAR
*str
)
1502 DWORD len
= strlenW( str
);
1503 memcpy( *ptr
, str
, len
* sizeof(WCHAR
) );
1504 *ptr
= (WCHAR
*)*ptr
+ len
;
1505 return len
* sizeof(WCHAR
);
1508 /***********************************************************************
1509 * create_startup_info
1511 static startup_info_t
*create_startup_info( LPCWSTR filename
, LPCWSTR cmdline
,
1512 LPCWSTR cur_dir
, LPWSTR env
, DWORD flags
,
1513 const STARTUPINFOW
*startup
, DWORD
*info_size
)
1515 const RTL_USER_PROCESS_PARAMETERS
*cur_params
;
1516 startup_info_t
*info
;
1519 UNICODE_STRING newdir
;
1520 WCHAR imagepath
[MAX_PATH
];
1521 HANDLE hstdin
, hstdout
, hstderr
;
1523 if(!GetLongPathNameW( filename
, imagepath
, MAX_PATH
))
1524 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1525 if(!GetFullPathNameW( imagepath
, MAX_PATH
, imagepath
, NULL
))
1526 lstrcpynW( imagepath
, filename
, MAX_PATH
);
1528 cur_params
= NtCurrentTeb()->Peb
->ProcessParameters
;
1530 newdir
.Buffer
= NULL
;
1533 if (RtlDosPathNameToNtPathName_U( cur_dir
, &newdir
, NULL
, NULL
))
1534 cur_dir
= newdir
.Buffer
+ 4; /* skip \??\ prefix */
1540 if (NtCurrentTeb()->Tib
.SubSystemTib
) /* FIXME: hack */
1541 cur_dir
= ((WIN16_SUBSYSTEM_TIB
*)NtCurrentTeb()->Tib
.SubSystemTib
)->curdir
.DosPath
.Buffer
;
1543 cur_dir
= cur_params
->CurrentDirectory
.DosPath
.Buffer
;
1546 size
= sizeof(*info
);
1547 size
+= strlenW( cur_dir
) * sizeof(WCHAR
);
1548 size
+= cur_params
->DllPath
.Length
;
1549 size
+= strlenW( imagepath
) * sizeof(WCHAR
);
1550 size
+= strlenW( cmdline
) * sizeof(WCHAR
);
1551 if (startup
->lpTitle
) size
+= strlenW( startup
->lpTitle
) * sizeof(WCHAR
);
1552 if (startup
->lpDesktop
) size
+= strlenW( startup
->lpDesktop
) * sizeof(WCHAR
);
1553 /* FIXME: shellinfo */
1554 if (startup
->lpReserved2
&& startup
->cbReserved2
) size
+= startup
->cbReserved2
;
1555 size
= (size
+ 1) & ~1;
1558 if (!(info
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, size
))) goto done
;
1560 info
->console_flags
= cur_params
->ConsoleFlags
;
1561 if (flags
& CREATE_NEW_PROCESS_GROUP
) info
->console_flags
= 1;
1562 if (flags
& CREATE_NEW_CONSOLE
) info
->console
= (obj_handle_t
)1; /* FIXME: cf. kernel_main.c */
1564 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1566 hstdin
= startup
->hStdInput
;
1567 hstdout
= startup
->hStdOutput
;
1568 hstderr
= startup
->hStdError
;
1572 hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1573 hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1574 hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1576 info
->hstdin
= wine_server_obj_handle( hstdin
);
1577 info
->hstdout
= wine_server_obj_handle( hstdout
);
1578 info
->hstderr
= wine_server_obj_handle( hstderr
);
1579 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1581 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1582 if (is_console_handle(hstdin
)) info
->hstdin
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1583 if (is_console_handle(hstdout
)) info
->hstdout
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1584 if (is_console_handle(hstderr
)) info
->hstderr
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1588 if (is_console_handle(hstdin
)) info
->hstdin
= console_handle_unmap(hstdin
);
1589 if (is_console_handle(hstdout
)) info
->hstdout
= console_handle_unmap(hstdout
);
1590 if (is_console_handle(hstderr
)) info
->hstderr
= console_handle_unmap(hstderr
);
1593 info
->x
= startup
->dwX
;
1594 info
->y
= startup
->dwY
;
1595 info
->xsize
= startup
->dwXSize
;
1596 info
->ysize
= startup
->dwYSize
;
1597 info
->xchars
= startup
->dwXCountChars
;
1598 info
->ychars
= startup
->dwYCountChars
;
1599 info
->attribute
= startup
->dwFillAttribute
;
1600 info
->flags
= startup
->dwFlags
;
1601 info
->show
= startup
->wShowWindow
;
1604 info
->curdir_len
= append_string( &ptr
, cur_dir
);
1605 info
->dllpath_len
= cur_params
->DllPath
.Length
;
1606 memcpy( ptr
, cur_params
->DllPath
.Buffer
, cur_params
->DllPath
.Length
);
1607 ptr
= (char *)ptr
+ cur_params
->DllPath
.Length
;
1608 info
->imagepath_len
= append_string( &ptr
, imagepath
);
1609 info
->cmdline_len
= append_string( &ptr
, cmdline
);
1610 if (startup
->lpTitle
) info
->title_len
= append_string( &ptr
, startup
->lpTitle
);
1611 if (startup
->lpDesktop
) info
->desktop_len
= append_string( &ptr
, startup
->lpDesktop
);
1612 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1614 info
->runtime_len
= startup
->cbReserved2
;
1615 memcpy( ptr
, startup
->lpReserved2
, startup
->cbReserved2
);
1619 RtlFreeUnicodeString( &newdir
);
1624 /***********************************************************************
1627 * Create a new process. If hFile is a valid handle we have an exe
1628 * file, otherwise it is a Winelib app.
1630 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1631 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1632 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1633 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1634 const struct binary_info
*binary_info
, int exec_only
)
1636 BOOL ret
, success
= FALSE
;
1637 HANDLE process_info
;
1639 char *winedebug
= NULL
;
1641 startup_info_t
*startup_info
;
1642 DWORD startup_info_size
;
1643 int socketfd
[2], stdin_fd
= -1, stdout_fd
= -1;
1647 if (sizeof(void *) == sizeof(int) && !is_wow64
&& (binary_info
->flags
& BINARY_FLAG_64BIT
))
1649 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename
) );
1650 SetLastError( ERROR_BAD_EXE_FORMAT
);
1654 RtlAcquirePebLock();
1656 if (!(startup_info
= create_startup_info( filename
, cmd_line
, cur_dir
, env
, flags
, startup
,
1657 &startup_info_size
)))
1659 RtlReleasePebLock();
1662 if (!env
) env
= NtCurrentTeb()->Peb
->ProcessParameters
->Environment
;
1666 static const WCHAR WINEDEBUG
[] = {'W','I','N','E','D','E','B','U','G','=',0};
1667 if (!winedebug
&& !strncmpW( env_end
, WINEDEBUG
, sizeof(WINEDEBUG
)/sizeof(WCHAR
) - 1 ))
1669 DWORD len
= WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, NULL
, 0, NULL
, NULL
);
1670 if ((winedebug
= HeapAlloc( GetProcessHeap(), 0, len
)))
1671 WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, winedebug
, len
, NULL
, NULL
);
1673 env_end
+= strlenW(env_end
) + 1;
1677 /* create the socket for the new process */
1679 if (socketpair( PF_UNIX
, SOCK_STREAM
, 0, socketfd
) == -1)
1681 RtlReleasePebLock();
1682 HeapFree( GetProcessHeap(), 0, winedebug
);
1683 HeapFree( GetProcessHeap(), 0, startup_info
);
1684 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1687 wine_server_send_fd( socketfd
[1] );
1688 close( socketfd
[1] );
1690 /* create the process on the server side */
1692 SERVER_START_REQ( new_process
)
1694 req
->inherit_all
= inherit
;
1695 req
->create_flags
= flags
;
1696 req
->socket_fd
= socketfd
[1];
1697 req
->exe_file
= wine_server_obj_handle( hFile
);
1698 req
->process_access
= PROCESS_ALL_ACCESS
;
1699 req
->process_attr
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1700 req
->thread_access
= THREAD_ALL_ACCESS
;
1701 req
->thread_attr
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1702 req
->info_size
= startup_info_size
;
1704 wine_server_add_data( req
, startup_info
, startup_info_size
);
1705 wine_server_add_data( req
, env
, (env_end
- env
) * sizeof(WCHAR
) );
1706 if ((ret
= !wine_server_call_err( req
)))
1708 info
->dwProcessId
= (DWORD
)reply
->pid
;
1709 info
->dwThreadId
= (DWORD
)reply
->tid
;
1710 info
->hProcess
= wine_server_ptr_handle( reply
->phandle
);
1711 info
->hThread
= wine_server_ptr_handle( reply
->thandle
);
1713 process_info
= wine_server_ptr_handle( reply
->info
);
1717 RtlReleasePebLock();
1720 close( socketfd
[0] );
1721 HeapFree( GetProcessHeap(), 0, startup_info
);
1722 HeapFree( GetProcessHeap(), 0, winedebug
);
1726 if (!(flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1728 if (startup_info
->hstdin
)
1729 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdin
),
1730 FILE_READ_DATA
, &stdin_fd
, NULL
);
1731 if (startup_info
->hstdout
)
1732 wine_server_handle_to_fd( wine_server_ptr_handle(startup_info
->hstdout
),
1733 FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1735 HeapFree( GetProcessHeap(), 0, startup_info
);
1737 /* create the child process */
1738 argv
= build_argv( cmd_line
, 1 );
1740 if (exec_only
|| !(pid
= fork())) /* child */
1742 char preloader_reserve
[64], socket_env
[64];
1744 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1746 if (!(pid
= fork()))
1748 int fd
= open( "/dev/null", O_RDWR
);
1750 /* close stdin and stdout */
1758 else if (pid
!= -1) _exit(0); /* parent */
1762 if (stdin_fd
!= -1) dup2( stdin_fd
, 0 );
1763 if (stdout_fd
!= -1) dup2( stdout_fd
, 1 );
1766 if (stdin_fd
!= -1) close( stdin_fd
);
1767 if (stdout_fd
!= -1) close( stdout_fd
);
1769 /* Reset signals that we previously set to SIG_IGN */
1770 signal( SIGPIPE
, SIG_DFL
);
1771 signal( SIGCHLD
, SIG_DFL
);
1773 sprintf( socket_env
, "WINESERVERSOCKET=%u", socketfd
[0] );
1774 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx",
1775 (unsigned long)binary_info
->res_start
, (unsigned long)binary_info
->res_end
);
1777 putenv( preloader_reserve
);
1778 putenv( socket_env
);
1779 if (winedebug
) putenv( winedebug
);
1780 if (unixdir
) chdir(unixdir
);
1782 if (argv
) wine_exec_wine_binary( NULL
, argv
, getenv("WINELOADER") );
1786 /* this is the parent */
1788 if (stdin_fd
!= -1) close( stdin_fd
);
1789 if (stdout_fd
!= -1) close( stdout_fd
);
1790 close( socketfd
[0] );
1791 HeapFree( GetProcessHeap(), 0, argv
);
1792 HeapFree( GetProcessHeap(), 0, winedebug
);
1799 /* wait for the new process info to be ready */
1801 WaitForSingleObject( process_info
, INFINITE
);
1802 SERVER_START_REQ( get_new_process_info
)
1804 req
->info
= wine_server_obj_handle( process_info
);
1805 wine_server_call( req
);
1806 success
= reply
->success
;
1807 err
= reply
->exit_code
;
1813 SetLastError( err
? err
: ERROR_INTERNAL_ERROR
);
1816 CloseHandle( process_info
);
1820 CloseHandle( process_info
);
1821 CloseHandle( info
->hProcess
);
1822 CloseHandle( info
->hThread
);
1823 info
->hProcess
= info
->hThread
= 0;
1824 info
->dwProcessId
= info
->dwThreadId
= 0;
1829 /***********************************************************************
1830 * create_vdm_process
1832 * Create a new VDM process for a 16-bit or DOS application.
1834 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
1835 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1836 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1837 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1838 const struct binary_info
*binary_info
, int exec_only
)
1840 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1843 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
1844 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
1848 SetLastError( ERROR_OUTOFMEMORY
);
1851 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
1852 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
1853 flags
, startup
, info
, unixdir
, binary_info
, exec_only
);
1854 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
1859 /***********************************************************************
1860 * create_cmd_process
1862 * Create a new cmd shell process for a .BAT file.
1864 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
1865 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1866 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1867 LPPROCESS_INFORMATION info
)
1870 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
1871 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
1872 WCHAR comspec
[MAX_PATH
];
1876 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
1878 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
1879 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
1882 strcpyW( newcmdline
, comspec
);
1883 strcatW( newcmdline
, slashcW
);
1884 strcatW( newcmdline
, cmd_line
);
1885 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
1886 flags
, env
, cur_dir
, startup
, info
);
1887 HeapFree( GetProcessHeap(), 0, newcmdline
);
1892 /*************************************************************************
1895 * Helper for CreateProcess: retrieve the file name to load from the
1896 * app name and command line. Store the file name in buffer, and
1897 * return a possibly modified command line.
1898 * Also returns a handle to the opened file if it's a Windows binary.
1900 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
1901 int buflen
, HANDLE
*handle
, struct binary_info
*binary_info
)
1903 static const WCHAR quotesW
[] = {'"','%','s','"',0};
1905 WCHAR
*name
, *pos
, *ret
= NULL
;
1909 /* if we have an app name, everything is easy */
1913 /* use the unmodified app name as file name */
1914 lstrcpynW( buffer
, appname
, buflen
);
1915 *handle
= open_exe_file( buffer
, binary_info
);
1916 if (!(ret
= cmdline
) || !cmdline
[0])
1918 /* no command-line, create one */
1919 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
1920 sprintfW( ret
, quotesW
, appname
);
1925 /* first check for a quoted file name */
1927 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
1929 int len
= p
- cmdline
- 1;
1930 /* extract the quoted portion as file name */
1931 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1932 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
1935 if (find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
1936 ret
= cmdline
; /* no change necessary */
1940 /* now try the command-line word by word */
1942 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
1950 do *pos
++ = *p
++; while (*p
&& *p
!= ' ' && *p
!= '\t');
1952 if (find_exe_file( name
, buffer
, buflen
, handle
, binary_info
))
1957 if (*p
) got_space
= TRUE
;
1960 if (ret
&& got_space
) /* now build a new command-line with quotes */
1962 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
1964 sprintfW( ret
, quotesW
, name
);
1967 else if (!ret
) SetLastError( ERROR_FILE_NOT_FOUND
);
1970 HeapFree( GetProcessHeap(), 0, name
);
1975 /**********************************************************************
1976 * CreateProcessA (KERNEL32.@)
1978 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1979 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
1980 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
1981 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
1984 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
1985 UNICODE_STRING desktopW
, titleW
;
1988 desktopW
.Buffer
= NULL
;
1989 titleW
.Buffer
= NULL
;
1990 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
1991 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
1992 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
1994 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
1995 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
1997 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
1998 infoW
.lpDesktop
= desktopW
.Buffer
;
1999 infoW
.lpTitle
= titleW
.Buffer
;
2001 if (startup_info
->lpReserved
)
2002 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
2003 debugstr_a(startup_info
->lpReserved
));
2005 ret
= CreateProcessW( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
2006 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
2008 HeapFree( GetProcessHeap(), 0, app_nameW
);
2009 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
2010 HeapFree( GetProcessHeap(), 0, cur_dirW
);
2011 RtlFreeUnicodeString( &desktopW
);
2012 RtlFreeUnicodeString( &titleW
);
2017 /**********************************************************************
2018 * CreateProcessW (KERNEL32.@)
2020 BOOL WINAPI DECLSPEC_HOTPATCH
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
2021 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
2022 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
2023 LPPROCESS_INFORMATION info
)
2027 char *unixdir
= NULL
;
2028 WCHAR name
[MAX_PATH
];
2029 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
2030 struct binary_info binary_info
;
2032 /* Process the AppName and/or CmdLine to get module name and path */
2034 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
2036 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
)/sizeof(WCHAR
),
2037 &hFile
, &binary_info
)))
2039 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
2041 /* Warn if unsupported features are used */
2043 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
2044 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
2045 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
2046 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
2047 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name
), flags
);
2051 if (!(unixdir
= wine_get_unix_file_name( cur_dir
)))
2053 SetLastError(ERROR_DIRECTORY
);
2059 WCHAR buf
[MAX_PATH
];
2060 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
2063 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
2068 while (*p
) p
+= strlen(p
) + 1;
2069 p
++; /* final null */
2070 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
2071 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
2072 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
2073 flags
|= CREATE_UNICODE_ENVIRONMENT
;
2076 info
->hThread
= info
->hProcess
= 0;
2077 info
->dwProcessId
= info
->dwThreadId
= 0;
2079 if (binary_info
.flags
& BINARY_FLAG_DLL
)
2081 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
2082 SetLastError( ERROR_BAD_EXE_FORMAT
);
2084 else switch (binary_info
.type
)
2087 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2088 debugstr_w(name
), binary_info
.res_start
, binary_info
.res_end
);
2089 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2090 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2095 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2096 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2097 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2099 case BINARY_UNIX_LIB
:
2100 TRACE( "starting %s as Winelib app\n", debugstr_w(name
) );
2101 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2102 inherit
, flags
, startup_info
, info
, unixdir
, &binary_info
, FALSE
);
2104 case BINARY_UNKNOWN
:
2105 /* check for .com or .bat extension */
2106 if ((p
= strrchrW( name
, '.' )))
2108 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
2110 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
2111 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2112 inherit
, flags
, startup_info
, info
, unixdir
,
2113 &binary_info
, FALSE
);
2116 if (!strcmpiW( p
, batW
) || !strcmpiW( p
, cmdW
) )
2118 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
2119 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
2120 inherit
, flags
, startup_info
, info
);
2125 case BINARY_UNIX_EXE
:
2127 /* unknown file, try as unix executable */
2130 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
2132 if ((unix_name
= wine_get_unix_file_name( name
)))
2134 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
, flags
, startup_info
) != -1);
2135 HeapFree( GetProcessHeap(), 0, unix_name
);
2140 if (hFile
) CloseHandle( hFile
);
2143 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
2144 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
2145 HeapFree( GetProcessHeap(), 0, unixdir
);
2147 TRACE( "started process pid %04x tid %04x\n", info
->dwProcessId
, info
->dwThreadId
);
2152 /**********************************************************************
2155 static void exec_process( LPCWSTR name
)
2159 STARTUPINFOW startup_info
;
2160 PROCESS_INFORMATION info
;
2161 struct binary_info binary_info
;
2163 hFile
= open_exe_file( name
, &binary_info
);
2164 if (!hFile
|| hFile
== INVALID_HANDLE_VALUE
) return;
2166 memset( &startup_info
, 0, sizeof(startup_info
) );
2167 startup_info
.cb
= sizeof(startup_info
);
2169 /* Determine executable type */
2171 if (binary_info
.flags
& BINARY_FLAG_DLL
) return;
2172 switch (binary_info
.type
)
2175 TRACE( "starting %s as Win32 binary (%p-%p)\n",
2176 debugstr_w(name
), binary_info
.res_start
, binary_info
.res_end
);
2177 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2178 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2180 case BINARY_UNIX_LIB
:
2181 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
2182 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2183 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2185 case BINARY_UNKNOWN
:
2186 /* check for .com or .pif extension */
2187 if (!(p
= strrchrW( name
, '.' ))) break;
2188 if (strcmpiW( p
, comW
) && strcmpiW( p
, pifW
)) break;
2193 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2194 create_vdm_process( name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2195 FALSE
, 0, &startup_info
, &info
, NULL
, &binary_info
, TRUE
);
2200 CloseHandle( hFile
);
2204 /***********************************************************************
2207 * Wrapper to call WaitForInputIdle USER function
2209 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2211 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2213 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2216 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2217 if (ptr
) return ptr( process
, timeout
);
2223 /***********************************************************************
2224 * WinExec (KERNEL32.@)
2226 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2228 PROCESS_INFORMATION info
;
2229 STARTUPINFOA startup
;
2233 memset( &startup
, 0, sizeof(startup
) );
2234 startup
.cb
= sizeof(startup
);
2235 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2236 startup
.wShowWindow
= nCmdShow
;
2238 /* cmdline needs to be writable for CreateProcess */
2239 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2240 strcpy( cmdline
, lpCmdLine
);
2242 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2243 0, NULL
, NULL
, &startup
, &info
))
2245 /* Give 30 seconds to the app to come up */
2246 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2247 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2249 /* Close off the handles */
2250 CloseHandle( info
.hThread
);
2251 CloseHandle( info
.hProcess
);
2253 else if ((ret
= GetLastError()) >= 32)
2255 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2258 HeapFree( GetProcessHeap(), 0, cmdline
);
2263 /**********************************************************************
2264 * LoadModule (KERNEL32.@)
2266 HINSTANCE WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2268 LOADPARMS32
*params
= paramBlock
;
2269 PROCESS_INFORMATION info
;
2270 STARTUPINFOA startup
;
2271 HINSTANCE hInstance
;
2273 char filename
[MAX_PATH
];
2276 if (!name
) return (HINSTANCE
)ERROR_FILE_NOT_FOUND
;
2278 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2279 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2280 return ULongToHandle(GetLastError());
2282 len
= (BYTE
)params
->lpCmdLine
[0];
2283 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2284 return (HINSTANCE
)ERROR_NOT_ENOUGH_MEMORY
;
2286 strcpy( cmdline
, filename
);
2287 p
= cmdline
+ strlen(cmdline
);
2289 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2292 memset( &startup
, 0, sizeof(startup
) );
2293 startup
.cb
= sizeof(startup
);
2294 if (params
->lpCmdShow
)
2296 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2297 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2300 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2301 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2303 /* Give 30 seconds to the app to come up */
2304 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2305 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2306 hInstance
= (HINSTANCE
)33;
2307 /* Close off the handles */
2308 CloseHandle( info
.hThread
);
2309 CloseHandle( info
.hProcess
);
2311 else if ((hInstance
= ULongToHandle(GetLastError())) >= (HINSTANCE
)32)
2313 FIXME("Strange error set by CreateProcess: %p\n", hInstance
);
2314 hInstance
= (HINSTANCE
)11;
2317 HeapFree( GetProcessHeap(), 0, cmdline
);
2322 /******************************************************************************
2323 * TerminateProcess (KERNEL32.@)
2325 * Terminates a process.
2328 * handle [I] Process to terminate.
2329 * exit_code [I] Exit code.
2333 * Failure: FALSE, check GetLastError().
2335 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2337 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2338 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2342 /***********************************************************************
2343 * ExitProcess (KERNEL32.@)
2345 * Exits the current process.
2348 * status [I] Status code to exit with.
2354 __ASM_STDCALL_FUNC( ExitProcess
, 4, /* Shrinker depend on this particular ExitProcess implementation */
2356 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2357 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2358 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2360 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2364 void WINAPI
process_ExitProcess( DWORD status
)
2366 LdrShutdownProcess();
2367 NtTerminateProcess(GetCurrentProcess(), status
);
2373 void WINAPI
ExitProcess( DWORD status
)
2375 LdrShutdownProcess();
2376 NtTerminateProcess(GetCurrentProcess(), status
);
2382 /***********************************************************************
2383 * GetExitCodeProcess [KERNEL32.@]
2385 * Gets termination status of specified process.
2388 * hProcess [in] Handle to the process.
2389 * lpExitCode [out] Address to receive termination status.
2395 BOOL WINAPI
GetExitCodeProcess( HANDLE hProcess
, LPDWORD lpExitCode
)
2398 PROCESS_BASIC_INFORMATION pbi
;
2400 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2402 if (status
== STATUS_SUCCESS
)
2404 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2407 SetLastError( RtlNtStatusToDosError(status
) );
2412 /***********************************************************************
2413 * SetErrorMode (KERNEL32.@)
2415 UINT WINAPI
SetErrorMode( UINT mode
)
2417 UINT old
= process_error_mode
;
2418 process_error_mode
= mode
;
2422 /***********************************************************************
2423 * GetErrorMode (KERNEL32.@)
2425 UINT WINAPI
GetErrorMode( void )
2427 return process_error_mode
;
2430 /**********************************************************************
2431 * TlsAlloc [KERNEL32.@]
2433 * Allocates a thread local storage index.
2436 * Success: TLS index.
2437 * Failure: 0xFFFFFFFF
2439 DWORD WINAPI
TlsAlloc( void )
2442 PEB
* const peb
= NtCurrentTeb()->Peb
;
2444 RtlAcquirePebLock();
2445 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 0 );
2446 if (index
!= ~0U) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2449 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2452 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2453 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2454 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2456 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2458 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2462 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2463 index
+= TLS_MINIMUM_AVAILABLE
;
2466 else SetLastError( ERROR_NO_MORE_ITEMS
);
2468 RtlReleasePebLock();
2473 /**********************************************************************
2474 * TlsFree [KERNEL32.@]
2476 * Releases a thread local storage index, making it available for reuse.
2479 * index [in] TLS index to free.
2485 BOOL WINAPI
TlsFree( DWORD index
)
2489 RtlAcquirePebLock();
2490 if (index
>= TLS_MINIMUM_AVAILABLE
)
2492 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2493 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2497 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2498 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2500 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2501 else SetLastError( ERROR_INVALID_PARAMETER
);
2502 RtlReleasePebLock();
2507 /**********************************************************************
2508 * TlsGetValue [KERNEL32.@]
2510 * Gets value in a thread's TLS slot.
2513 * index [in] TLS index to retrieve value for.
2516 * Success: Value stored in calling thread's TLS slot for index.
2517 * Failure: 0 and GetLastError() returns NO_ERROR.
2519 LPVOID WINAPI
TlsGetValue( DWORD index
)
2523 if (index
< TLS_MINIMUM_AVAILABLE
)
2525 ret
= NtCurrentTeb()->TlsSlots
[index
];
2529 index
-= TLS_MINIMUM_AVAILABLE
;
2530 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2532 SetLastError( ERROR_INVALID_PARAMETER
);
2535 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2536 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2538 SetLastError( ERROR_SUCCESS
);
2543 /**********************************************************************
2544 * TlsSetValue [KERNEL32.@]
2546 * Stores a value in the thread's TLS slot.
2549 * index [in] TLS index to set value for.
2550 * value [in] Value to be stored.
2556 BOOL WINAPI
TlsSetValue( DWORD index
, LPVOID value
)
2558 if (index
< TLS_MINIMUM_AVAILABLE
)
2560 NtCurrentTeb()->TlsSlots
[index
] = value
;
2564 index
-= TLS_MINIMUM_AVAILABLE
;
2565 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2567 SetLastError( ERROR_INVALID_PARAMETER
);
2570 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2571 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2572 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2574 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2577 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2583 /***********************************************************************
2584 * GetProcessFlags (KERNEL32.@)
2586 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2588 IMAGE_NT_HEADERS
*nt
;
2591 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2593 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2595 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2596 flags
|= PDB32_CONSOLE_PROC
;
2598 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2599 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2604 /***********************************************************************
2605 * GetProcessDword (KERNEL32.18)
2607 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
2609 FIXME( "(%d, %d): not supported\n", dwProcessID
, offset
);
2614 /*********************************************************************
2615 * OpenProcess (KERNEL32.@)
2617 * Opens a handle to a process.
2620 * access [I] Desired access rights assigned to the returned handle.
2621 * inherit [I] Determines whether or not child processes will inherit the handle.
2622 * id [I] Process identifier of the process to get a handle to.
2625 * Success: Valid handle to the specified process.
2626 * Failure: NULL, check GetLastError().
2628 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2632 OBJECT_ATTRIBUTES attr
;
2635 cid
.UniqueProcess
= ULongToHandle(id
);
2636 cid
.UniqueThread
= 0; /* FIXME ? */
2638 attr
.Length
= sizeof(OBJECT_ATTRIBUTES
);
2639 attr
.RootDirectory
= NULL
;
2640 attr
.Attributes
= inherit
? OBJ_INHERIT
: 0;
2641 attr
.SecurityDescriptor
= NULL
;
2642 attr
.SecurityQualityOfService
= NULL
;
2643 attr
.ObjectName
= NULL
;
2645 if (GetVersion() & 0x80000000) access
= PROCESS_ALL_ACCESS
;
2647 status
= NtOpenProcess(&handle
, access
, &attr
, &cid
);
2648 if (status
!= STATUS_SUCCESS
)
2650 SetLastError( RtlNtStatusToDosError(status
) );
2657 /*********************************************************************
2658 * GetProcessId (KERNEL32.@)
2660 * Gets the a unique identifier of a process.
2663 * hProcess [I] Handle to the process.
2667 * Failure: FALSE, check GetLastError().
2671 * The identifier is unique only on the machine and only until the process
2672 * exits (including system shutdown).
2674 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2677 PROCESS_BASIC_INFORMATION pbi
;
2679 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2681 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2682 SetLastError( RtlNtStatusToDosError(status
) );
2687 /*********************************************************************
2688 * CloseHandle (KERNEL32.@)
2693 * handle [I] Handle to close.
2697 * Failure: FALSE, check GetLastError().
2699 BOOL WINAPI
CloseHandle( HANDLE handle
)
2703 /* stdio handles need special treatment */
2704 if ((handle
== (HANDLE
)STD_INPUT_HANDLE
) ||
2705 (handle
== (HANDLE
)STD_OUTPUT_HANDLE
) ||
2706 (handle
== (HANDLE
)STD_ERROR_HANDLE
))
2707 handle
= GetStdHandle( HandleToULong(handle
) );
2709 if (is_console_handle(handle
))
2710 return CloseConsoleHandle(handle
);
2712 status
= NtClose( handle
);
2713 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2718 /*********************************************************************
2719 * GetHandleInformation (KERNEL32.@)
2721 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2723 OBJECT_DATA_INFORMATION info
;
2724 NTSTATUS status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
);
2726 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2730 if (info
.InheritHandle
) *flags
|= HANDLE_FLAG_INHERIT
;
2731 if (info
.ProtectFromClose
) *flags
|= HANDLE_FLAG_PROTECT_FROM_CLOSE
;
2737 /*********************************************************************
2738 * SetHandleInformation (KERNEL32.@)
2740 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2742 OBJECT_DATA_INFORMATION info
;
2745 /* if not setting both fields, retrieve current value first */
2746 if ((mask
& (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
)) !=
2747 (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
))
2749 if ((status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
)))
2751 SetLastError( RtlNtStatusToDosError(status
) );
2755 if (mask
& HANDLE_FLAG_INHERIT
)
2756 info
.InheritHandle
= (flags
& HANDLE_FLAG_INHERIT
) != 0;
2757 if (mask
& HANDLE_FLAG_PROTECT_FROM_CLOSE
)
2758 info
.ProtectFromClose
= (flags
& HANDLE_FLAG_PROTECT_FROM_CLOSE
) != 0;
2760 status
= NtSetInformationObject( handle
, ObjectDataInformation
, &info
, sizeof(info
) );
2761 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2766 /*********************************************************************
2767 * DuplicateHandle (KERNEL32.@)
2769 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2770 HANDLE dest_process
, HANDLE
*dest
,
2771 DWORD access
, BOOL inherit
, DWORD options
)
2775 if (is_console_handle(source
))
2777 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2778 if (source_process
!= dest_process
||
2779 source_process
!= GetCurrentProcess())
2781 SetLastError(ERROR_INVALID_PARAMETER
);
2784 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2785 return (*dest
!= INVALID_HANDLE_VALUE
);
2787 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2788 access
, inherit
? OBJ_INHERIT
: 0, options
);
2789 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2794 /***********************************************************************
2795 * ConvertToGlobalHandle (KERNEL32.@)
2797 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
2799 HANDLE ret
= INVALID_HANDLE_VALUE
;
2800 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
2801 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
2806 /***********************************************************************
2807 * SetHandleContext (KERNEL32.@)
2809 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
2811 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2812 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
2813 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2818 /***********************************************************************
2819 * GetHandleContext (KERNEL32.@)
2821 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
2823 FIXME("(%p), 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
);
2825 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2830 /***********************************************************************
2831 * CreateSocketHandle (KERNEL32.@)
2833 HANDLE WINAPI
CreateSocketHandle(void)
2835 FIXME("(), 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");
2837 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2838 return INVALID_HANDLE_VALUE
;
2842 /***********************************************************************
2843 * SetPriorityClass (KERNEL32.@)
2845 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
2848 PROCESS_PRIORITY_CLASS ppc
;
2850 ppc
.Foreground
= FALSE
;
2851 switch (priorityclass
)
2853 case IDLE_PRIORITY_CLASS
:
2854 ppc
.PriorityClass
= PROCESS_PRIOCLASS_IDLE
; break;
2855 case BELOW_NORMAL_PRIORITY_CLASS
:
2856 ppc
.PriorityClass
= PROCESS_PRIOCLASS_BELOW_NORMAL
; break;
2857 case NORMAL_PRIORITY_CLASS
:
2858 ppc
.PriorityClass
= PROCESS_PRIOCLASS_NORMAL
; break;
2859 case ABOVE_NORMAL_PRIORITY_CLASS
:
2860 ppc
.PriorityClass
= PROCESS_PRIOCLASS_ABOVE_NORMAL
; break;
2861 case HIGH_PRIORITY_CLASS
:
2862 ppc
.PriorityClass
= PROCESS_PRIOCLASS_HIGH
; break;
2863 case REALTIME_PRIORITY_CLASS
:
2864 ppc
.PriorityClass
= PROCESS_PRIOCLASS_REALTIME
; break;
2866 SetLastError(ERROR_INVALID_PARAMETER
);
2870 status
= NtSetInformationProcess(hprocess
, ProcessPriorityClass
,
2873 if (status
!= STATUS_SUCCESS
)
2875 SetLastError( RtlNtStatusToDosError(status
) );
2882 /***********************************************************************
2883 * GetPriorityClass (KERNEL32.@)
2885 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
2888 PROCESS_BASIC_INFORMATION pbi
;
2890 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2892 if (status
!= STATUS_SUCCESS
)
2894 SetLastError( RtlNtStatusToDosError(status
) );
2897 switch (pbi
.BasePriority
)
2899 case PROCESS_PRIOCLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
2900 case PROCESS_PRIOCLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
2901 case PROCESS_PRIOCLASS_NORMAL
: return NORMAL_PRIORITY_CLASS
;
2902 case PROCESS_PRIOCLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
2903 case PROCESS_PRIOCLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
2904 case PROCESS_PRIOCLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
2906 SetLastError( ERROR_INVALID_PARAMETER
);
2911 /***********************************************************************
2912 * SetProcessAffinityMask (KERNEL32.@)
2914 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
2918 status
= NtSetInformationProcess(hProcess
, ProcessAffinityMask
,
2919 &affmask
, sizeof(DWORD_PTR
));
2922 SetLastError( RtlNtStatusToDosError(status
) );
2929 /**********************************************************************
2930 * GetProcessAffinityMask (KERNEL32.@)
2932 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
2933 PDWORD_PTR lpProcessAffinityMask
,
2934 PDWORD_PTR lpSystemAffinityMask
)
2936 PROCESS_BASIC_INFORMATION pbi
;
2939 status
= NtQueryInformationProcess(hProcess
,
2940 ProcessBasicInformation
,
2941 &pbi
, sizeof(pbi
), NULL
);
2944 SetLastError( RtlNtStatusToDosError(status
) );
2947 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= pbi
.AffinityMask
;
2948 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= (1 << NtCurrentTeb()->Peb
->NumberOfProcessors
) - 1;
2953 /***********************************************************************
2954 * GetProcessVersion (KERNEL32.@)
2956 DWORD WINAPI
GetProcessVersion( DWORD pid
)
2960 PROCESS_BASIC_INFORMATION pbi
;
2963 IMAGE_DOS_HEADER dos
;
2964 IMAGE_NT_HEADERS nt
;
2967 if (!pid
|| pid
== GetCurrentProcessId())
2969 IMAGE_NT_HEADERS
*nt
;
2971 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2972 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
2973 nt
->OptionalHeader
.MinorSubsystemVersion
);
2977 process
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
2978 if (!process
) return 0;
2980 status
= NtQueryInformationProcess(process
, ProcessBasicInformation
, &pbi
, sizeof(pbi
), NULL
);
2981 if (status
) goto err
;
2983 status
= NtReadVirtualMemory(process
, pbi
.PebBaseAddress
, &peb
, sizeof(peb
), &count
);
2984 if (status
|| count
!= sizeof(peb
)) goto err
;
2986 memset(&dos
, 0, sizeof(dos
));
2987 status
= NtReadVirtualMemory(process
, peb
.ImageBaseAddress
, &dos
, sizeof(dos
), &count
);
2988 if (status
|| count
!= sizeof(dos
)) goto err
;
2989 if (dos
.e_magic
!= IMAGE_DOS_SIGNATURE
) goto err
;
2991 memset(&nt
, 0, sizeof(nt
));
2992 status
= NtReadVirtualMemory(process
, (char *)peb
.ImageBaseAddress
+ dos
.e_lfanew
, &nt
, sizeof(nt
), &count
);
2993 if (status
|| count
!= sizeof(nt
)) goto err
;
2994 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) goto err
;
2996 ver
= MAKELONG(nt
.OptionalHeader
.MinorSubsystemVersion
, nt
.OptionalHeader
.MajorSubsystemVersion
);
2999 CloseHandle(process
);
3001 if (status
!= STATUS_SUCCESS
)
3002 SetLastError(RtlNtStatusToDosError(status
));
3008 /***********************************************************************
3009 * SetProcessWorkingSetSize [KERNEL32.@]
3010 * Sets the min/max working set sizes for a specified process.
3013 * hProcess [I] Handle to the process of interest
3014 * minset [I] Specifies minimum working set size
3015 * maxset [I] Specifies maximum working set size
3021 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
3024 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
3025 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
3026 /* Trim the working set to zero */
3027 /* Swap the process out of physical RAM */
3032 /***********************************************************************
3033 * GetProcessWorkingSetSize (KERNEL32.@)
3035 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
3038 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
3039 /* 32 MB working set size */
3040 if (minset
) *minset
= 32*1024*1024;
3041 if (maxset
) *maxset
= 32*1024*1024;
3046 /***********************************************************************
3047 * SetProcessShutdownParameters (KERNEL32.@)
3049 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
3051 FIXME("(%08x, %08x): partial stub.\n", level
, flags
);
3052 shutdown_flags
= flags
;
3053 shutdown_priority
= level
;
3058 /***********************************************************************
3059 * GetProcessShutdownParameters (KERNEL32.@)
3062 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
3064 *lpdwLevel
= shutdown_priority
;
3065 *lpdwFlags
= shutdown_flags
;
3070 /***********************************************************************
3071 * GetProcessPriorityBoost (KERNEL32.@)
3073 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
3075 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
3077 /* Report that no boost is present.. */
3078 *pDisablePriorityBoost
= FALSE
;
3083 /***********************************************************************
3084 * SetProcessPriorityBoost (KERNEL32.@)
3086 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
3088 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
3089 /* Say we can do it. I doubt the program will notice that we don't. */
3094 /***********************************************************************
3095 * ReadProcessMemory (KERNEL32.@)
3097 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
3098 SIZE_T
*bytes_read
)
3100 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
3101 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3106 /***********************************************************************
3107 * WriteProcessMemory (KERNEL32.@)
3109 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
3110 SIZE_T
*bytes_written
)
3112 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
3113 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3118 /****************************************************************************
3119 * FlushInstructionCache (KERNEL32.@)
3121 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
3124 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
3125 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3130 /******************************************************************
3131 * GetProcessIoCounters (KERNEL32.@)
3133 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
3137 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
3138 ioc
, sizeof(*ioc
), NULL
);
3139 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3143 /******************************************************************
3144 * GetProcessHandleCount (KERNEL32.@)
3146 BOOL WINAPI
GetProcessHandleCount(HANDLE hProcess
, DWORD
*cnt
)
3150 status
= NtQueryInformationProcess(hProcess
, ProcessHandleCount
,
3151 cnt
, sizeof(*cnt
), NULL
);
3152 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3156 /******************************************************************
3157 * QueryFullProcessImageNameA (KERNEL32.@)
3159 BOOL WINAPI
QueryFullProcessImageNameA(HANDLE hProcess
, DWORD dwFlags
, LPSTR lpExeName
, PDWORD pdwSize
)
3162 DWORD pdwSizeW
= *pdwSize
;
3163 LPWSTR lpExeNameW
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, *pdwSize
* sizeof(WCHAR
));
3165 retval
= QueryFullProcessImageNameW(hProcess
, dwFlags
, lpExeNameW
, &pdwSizeW
);
3168 retval
= (0 != WideCharToMultiByte(CP_ACP
, 0, lpExeNameW
, -1,
3169 lpExeName
, *pdwSize
, NULL
, NULL
));
3171 *pdwSize
= strlen(lpExeName
);
3173 HeapFree(GetProcessHeap(), 0, lpExeNameW
);
3177 /******************************************************************
3178 * QueryFullProcessImageNameW (KERNEL32.@)
3180 BOOL WINAPI
QueryFullProcessImageNameW(HANDLE hProcess
, DWORD dwFlags
, LPWSTR lpExeName
, PDWORD pdwSize
)
3182 BYTE buffer
[sizeof(UNICODE_STRING
) + MAX_PATH
*sizeof(WCHAR
)]; /* this buffer should be enough */
3183 UNICODE_STRING
*dynamic_buffer
= NULL
;
3184 UNICODE_STRING nt_path
;
3185 UNICODE_STRING
*result
= NULL
;
3189 RtlInitUnicodeStringEx(&nt_path
, NULL
);
3190 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3191 * as this is on Wine. */
3192 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, buffer
,
3193 sizeof(buffer
) - sizeof(WCHAR
), &needed
);
3194 if (status
== STATUS_INFO_LENGTH_MISMATCH
)
3196 dynamic_buffer
= HeapAlloc(GetProcessHeap(), 0, needed
+ sizeof(WCHAR
));
3197 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, (LPBYTE
)dynamic_buffer
, needed
, &needed
);
3198 result
= dynamic_buffer
;
3201 result
= (PUNICODE_STRING
)buffer
;
3203 if (status
) goto cleanup
;
3205 if (dwFlags
& PROCESS_NAME_NATIVE
)
3207 result
->Buffer
[result
->Length
/ sizeof(WCHAR
)] = 0;
3208 if (!RtlDosPathNameToNtPathName_U(result
->Buffer
, &nt_path
, NULL
, NULL
))
3210 status
= STATUS_OBJECT_PATH_NOT_FOUND
;
3216 if (result
->Length
/sizeof(WCHAR
) + 1 > *pdwSize
)
3218 status
= STATUS_BUFFER_TOO_SMALL
;
3222 *pdwSize
= result
->Length
/sizeof(WCHAR
);
3223 memcpy( lpExeName
, result
->Buffer
, result
->Length
);
3224 lpExeName
[*pdwSize
] = 0;
3227 HeapFree(GetProcessHeap(), 0, dynamic_buffer
);
3228 RtlFreeUnicodeString(&nt_path
);
3229 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3233 /***********************************************************************
3234 * ProcessIdToSessionId (KERNEL32.@)
3235 * This function is available on Terminal Server 4SP4 and Windows 2000
3237 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
3239 /* According to MSDN, if the calling process is not in a terminal
3240 * services environment, then the sessionid returned is zero.
3247 /***********************************************************************
3248 * RegisterServiceProcess (KERNEL32.@)
3250 * A service process calls this function to ensure that it continues to run
3251 * even after a user logged off.
3253 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
3255 /* I don't think that Wine needs to do anything in this function */
3256 return 1; /* success */
3260 /**********************************************************************
3261 * IsWow64Process (KERNEL32.@)
3263 BOOL WINAPI
IsWow64Process(HANDLE hProcess
, PBOOL Wow64Process
)
3268 status
= NtQueryInformationProcess( hProcess
, ProcessWow64Information
, &pbi
, sizeof(pbi
), NULL
);
3270 if (status
!= STATUS_SUCCESS
)
3272 SetLastError( RtlNtStatusToDosError( status
) );
3275 *Wow64Process
= (pbi
!= 0);
3280 /***********************************************************************
3281 * GetCurrentProcess (KERNEL32.@)
3283 * Get a handle to the current process.
3289 * A handle representing the current process.
3291 #undef GetCurrentProcess
3292 HANDLE WINAPI
GetCurrentProcess(void)
3294 return (HANDLE
)~(ULONG_PTR
)0;
3297 /***********************************************************************
3298 * CmdBatNotification (KERNEL32.@)
3300 * Notifies the system that a batch file has started or finished.
3303 * bBatchRunning [I] TRUE if a batch file has started or
3304 * FALSE if a batch file has finished executing.
3309 BOOL WINAPI
CmdBatNotification( BOOL bBatchRunning
)
3311 FIXME("%d\n", bBatchRunning
);
3316 /***********************************************************************
3317 * RegisterApplicationRestart (KERNEL32.@)
3319 HRESULT WINAPI
RegisterApplicationRestart(PCWSTR pwzCommandLine
, DWORD dwFlags
)
3321 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine
), dwFlags
);
3326 /**********************************************************************
3327 * WTSGetActiveConsoleSessionId (KERNEL32.@)
3329 DWORD WINAPI
WTSGetActiveConsoleSessionId(void)