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/exception.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(process
);
56 WINE_DECLARE_DEBUG_CHANNEL(file
);
57 WINE_DECLARE_DEBUG_CHANNEL(relay
);
60 extern char **__wine_get_main_environment(void);
62 extern char **__wine_main_environ
;
63 static char **__wine_get_main_environment(void) { return __wine_main_environ
; }
74 static UINT process_error_mode
;
76 static DWORD shutdown_flags
= 0;
77 static DWORD shutdown_priority
= 0x280;
78 static DWORD process_dword
;
80 HMODULE kernel32_handle
= 0;
82 const WCHAR
*DIR_Windows
= NULL
;
83 const WCHAR
*DIR_System
= 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 * Get the path of a builtin module when the native file does not exist.
133 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
, UINT size
)
136 UINT len
= strlenW( DIR_System
);
138 if (contains_path( libname
))
140 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
141 filename
, &file_part
) > size
* sizeof(WCHAR
))
142 return FALSE
; /* too long */
144 if (strncmpiW( filename
, DIR_System
, len
) || filename
[len
] != '\\')
146 while (filename
[len
] == '\\') len
++;
147 if (filename
+ len
!= file_part
) return FALSE
;
151 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
152 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
153 file_part
= filename
+ len
;
154 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
155 strcpyW( file_part
, libname
);
157 if (ext
&& !strchrW( file_part
, '.' ))
159 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
160 return FALSE
; /* too long */
161 strcatW( file_part
, ext
);
167 /***********************************************************************
168 * open_builtin_exe_file
170 * Open an exe file for a builtin exe.
172 static void *open_builtin_exe_file( const WCHAR
*name
, char *error
, int error_size
,
173 int test_only
, int *file_exists
)
175 char exename
[MAX_PATH
];
180 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
181 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
183 /* we don't want to depend on the current codepage here */
184 len
= strlenW( name
) + 1;
185 if (len
>= sizeof(exename
)) return NULL
;
186 for (i
= 0; i
< len
; i
++)
188 if (name
[i
] > 127) return NULL
;
189 exename
[i
] = (char)name
[i
];
190 if (exename
[i
] >= 'A' && exename
[i
] <= 'Z') exename
[i
] += 'a' - 'A';
192 return wine_dll_load_main_exe( exename
, error
, error_size
, test_only
, file_exists
);
196 /***********************************************************************
199 * Open a specific exe file, taking load order into account.
200 * Returns the file handle or 0 for a builtin exe.
202 static HANDLE
open_exe_file( const WCHAR
*name
)
206 TRACE("looking for %s\n", debugstr_w(name
) );
208 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
209 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
211 WCHAR buffer
[MAX_PATH
];
212 /* file doesn't exist, check for builtin */
213 if (contains_path( name
) && get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
) ))
220 /***********************************************************************
223 * Open an exe file, and return the full name and file handle.
224 * Returns FALSE if file could not be found.
225 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
226 * If file is a builtin exe, returns TRUE and sets handle to 0.
228 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
, HANDLE
*handle
)
230 static const WCHAR exeW
[] = {'.','e','x','e',0};
233 TRACE("looking for %s\n", debugstr_w(name
) );
235 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
) &&
236 !get_builtin_path( name
, exeW
, buffer
, buflen
))
238 /* no builtin found, try native without extension in case it is a Unix app */
240 if (SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
))
242 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer
) );
243 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
244 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
250 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
251 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
252 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
255 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer
) );
256 open_builtin_exe_file( buffer
, NULL
, 0, 1, &file_exists
);
267 /***********************************************************************
268 * build_initial_environment
270 * Build the Win32 environment from the Unix environment
272 static BOOL
build_initial_environment(void)
278 char **env
= __wine_get_main_environment();
280 /* Compute the total size of the Unix environment */
281 for (e
= env
; *e
; e
++)
283 if (is_special_env_var( *e
)) continue;
284 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
286 size
*= sizeof(WCHAR
);
288 /* Now allocate the environment */
290 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
291 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
294 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
295 endptr
= p
+ size
/ sizeof(WCHAR
);
297 /* And fill it with the Unix environment */
298 for (e
= env
; *e
; e
++)
302 /* skip Unix special variables and use the Wine variants instead */
303 if (!strncmp( str
, "WINE", 4 ))
305 if (is_special_env_var( str
+ 4 )) str
+= 4;
306 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
308 else if (is_special_env_var( str
)) continue; /* skip it */
310 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
318 /***********************************************************************
319 * set_registry_variables
321 * Set environment variables by enumerating the values of a key;
322 * helper for set_registry_environment().
323 * Note that Windows happily truncates the value if it's too big.
325 static void set_registry_variables( HANDLE hkey
, ULONG type
)
327 UNICODE_STRING env_name
, env_value
;
331 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
332 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
334 for (index
= 0; ; index
++)
336 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
337 buffer
, sizeof(buffer
), &size
);
338 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
340 if (info
->Type
!= type
)
342 env_name
.Buffer
= info
->Name
;
343 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
344 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
345 env_value
.Length
= env_value
.MaximumLength
= info
->DataLength
;
346 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
347 env_value
.Length
-= sizeof(WCHAR
); /* don't count terminating null if any */
348 if (info
->Type
== REG_EXPAND_SZ
)
350 WCHAR buf_expanded
[1024];
351 UNICODE_STRING env_expanded
;
352 env_expanded
.Length
= env_expanded
.MaximumLength
= sizeof(buf_expanded
);
353 env_expanded
.Buffer
=buf_expanded
;
354 status
= RtlExpandEnvironmentStrings_U(NULL
, &env_value
, &env_expanded
, NULL
);
355 if (status
== STATUS_SUCCESS
|| status
== STATUS_BUFFER_OVERFLOW
)
356 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_expanded
);
360 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
366 /***********************************************************************
367 * set_registry_environment
369 * Set the environment variables specified in the registry.
371 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
372 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
373 * on the order in which the variables are processed. But on Windows it
374 * does not really matter since they only use %SystemDrive% and
375 * %SystemRoot% which are predefined. But Wine defines these in the
376 * registry, so we need two passes.
378 static BOOL
set_registry_environment(void)
380 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
381 'S','y','s','t','e','m','\\',
382 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
383 'C','o','n','t','r','o','l','\\',
384 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
385 'E','n','v','i','r','o','n','m','e','n','t',0};
386 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
388 OBJECT_ATTRIBUTES attr
;
389 UNICODE_STRING nameW
;
393 attr
.Length
= sizeof(attr
);
394 attr
.RootDirectory
= 0;
395 attr
.ObjectName
= &nameW
;
397 attr
.SecurityDescriptor
= NULL
;
398 attr
.SecurityQualityOfService
= NULL
;
400 /* first the system environment variables */
401 RtlInitUnicodeString( &nameW
, env_keyW
);
402 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
404 set_registry_variables( hkey
, REG_SZ
);
405 set_registry_variables( hkey
, REG_EXPAND_SZ
);
410 /* then the ones for the current user */
411 if (RtlOpenCurrentUser( KEY_ALL_ACCESS
, &attr
.RootDirectory
) != STATUS_SUCCESS
) return ret
;
412 RtlInitUnicodeString( &nameW
, envW
);
413 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
415 set_registry_variables( hkey
, REG_SZ
);
416 set_registry_variables( hkey
, REG_EXPAND_SZ
);
419 NtClose( attr
.RootDirectory
);
424 /***********************************************************************
427 static WCHAR
*get_reg_value( HKEY hkey
, const WCHAR
*name
)
429 char buffer
[1024 * sizeof(WCHAR
) + sizeof(KEY_VALUE_PARTIAL_INFORMATION
)];
430 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
431 DWORD len
, size
= sizeof(buffer
);
433 UNICODE_STRING nameW
;
435 RtlInitUnicodeString( &nameW
, name
);
436 if (NtQueryValueKey( hkey
, &nameW
, KeyValuePartialInformation
, buffer
, size
, &size
))
439 if (size
<= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) return NULL
;
440 len
= (size
- FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) / sizeof(WCHAR
);
442 if (info
->Type
== REG_EXPAND_SZ
)
444 UNICODE_STRING value
, expanded
;
446 value
.MaximumLength
= len
* sizeof(WCHAR
);
447 value
.Buffer
= (WCHAR
*)info
->Data
;
448 if (!value
.Buffer
[len
- 1]) len
--; /* don't count terminating null if any */
449 value
.Length
= len
* sizeof(WCHAR
);
450 expanded
.Length
= expanded
.MaximumLength
= 1024 * sizeof(WCHAR
);
451 if (!(expanded
.Buffer
= HeapAlloc( GetProcessHeap(), 0, expanded
.MaximumLength
))) return NULL
;
452 if (!RtlExpandEnvironmentStrings_U( NULL
, &value
, &expanded
, NULL
)) ret
= expanded
.Buffer
;
453 else RtlFreeUnicodeString( &expanded
);
455 else if (info
->Type
== REG_SZ
)
457 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
459 memcpy( ret
, info
->Data
, len
* sizeof(WCHAR
) );
467 /***********************************************************************
468 * set_additional_environment
470 * Set some additional environment variables not specified in the registry.
472 static void set_additional_environment(void)
474 static const WCHAR profile_keyW
[] = {'M','a','c','h','i','n','e','\\',
475 'S','o','f','t','w','a','r','e','\\',
476 'M','i','c','r','o','s','o','f','t','\\',
477 'W','i','n','d','o','w','s',' ','N','T','\\',
478 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
479 'P','r','o','f','i','l','e','L','i','s','t',0};
480 static const WCHAR profiles_valueW
[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
481 static const WCHAR all_users_valueW
[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
482 static const WCHAR usernameW
[] = {'U','S','E','R','N','A','M','E',0};
483 static const WCHAR userprofileW
[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
484 static const WCHAR allusersW
[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
485 OBJECT_ATTRIBUTES attr
;
486 UNICODE_STRING nameW
;
487 WCHAR
*user_name
= NULL
, *profile_dir
= NULL
, *all_users_dir
= NULL
;
489 const char *name
= wine_get_user_name();
492 /* set the USERNAME variable */
494 len
= MultiByteToWideChar( CP_UNIXCP
, 0, name
, -1, NULL
, 0 );
497 user_name
= HeapAlloc( GetProcessHeap(), 0, len
*sizeof(WCHAR
) );
498 MultiByteToWideChar( CP_UNIXCP
, 0, name
, -1, user_name
, len
);
499 SetEnvironmentVariableW( usernameW
, user_name
);
501 else WARN( "user name %s not convertible.\n", debugstr_a(name
) );
503 /* set the USERPROFILE and ALLUSERSPROFILE variables */
505 attr
.Length
= sizeof(attr
);
506 attr
.RootDirectory
= 0;
507 attr
.ObjectName
= &nameW
;
509 attr
.SecurityDescriptor
= NULL
;
510 attr
.SecurityQualityOfService
= NULL
;
511 RtlInitUnicodeString( &nameW
, profile_keyW
);
512 if (!NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
))
514 profile_dir
= get_reg_value( hkey
, profiles_valueW
);
515 all_users_dir
= get_reg_value( hkey
, all_users_valueW
);
523 if (all_users_dir
) len
= max( len
, strlenW(all_users_dir
) + 1 );
524 len
+= strlenW(profile_dir
) + 1;
525 value
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
526 strcpyW( value
, profile_dir
);
527 p
= value
+ strlenW(value
);
528 if (p
> value
&& p
[-1] != '\\') *p
++ = '\\';
530 strcpyW( p
, user_name
);
531 SetEnvironmentVariableW( userprofileW
, value
);
535 strcpyW( p
, all_users_dir
);
536 SetEnvironmentVariableW( allusersW
, value
);
538 HeapFree( GetProcessHeap(), 0, value
);
541 HeapFree( GetProcessHeap(), 0, all_users_dir
);
542 HeapFree( GetProcessHeap(), 0, profile_dir
);
543 HeapFree( GetProcessHeap(), 0, user_name
);
546 /***********************************************************************
549 * Set the Wine library Unicode argv global variables.
551 static void set_library_wargv( char **argv
)
559 for (argc
= 0; argv
[argc
]; argc
++)
560 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
562 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
563 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
564 p
= (WCHAR
*)(wargv
+ argc
+ 1);
565 for (argc
= 0; argv
[argc
]; argc
++)
567 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
574 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
576 for (argc
= 0; wargv
[argc
]; argc
++)
577 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
579 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
580 q
= (char *)(argv
+ argc
+ 1);
581 for (argc
= 0; wargv
[argc
]; argc
++)
583 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
590 __wine_main_argc
= argc
;
591 __wine_main_argv
= argv
;
592 __wine_main_wargv
= wargv
;
596 /***********************************************************************
597 * update_library_argv0
599 * Update the argv[0] global variable with the binary we have found.
601 static void update_library_argv0( const WCHAR
*argv0
)
603 DWORD len
= strlenW( argv0
);
605 if (len
> strlenW( __wine_main_wargv
[0] ))
607 __wine_main_wargv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
609 strcpyW( __wine_main_wargv
[0], argv0
);
611 len
= WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, NULL
, 0, NULL
, NULL
);
612 if (len
> strlen( __wine_main_argv
[0] ) + 1)
614 __wine_main_argv
[0] = RtlAllocateHeap( GetProcessHeap(), 0, len
);
616 WideCharToMultiByte( CP_ACP
, 0, argv0
, -1, __wine_main_argv
[0], len
, NULL
, NULL
);
620 /***********************************************************************
623 * Build the command line of a process from the argv array.
625 * Note that it does NOT necessarily include the file name.
626 * Sometimes we don't even have any command line options at all.
628 * We must quote and escape characters so that the argv array can be rebuilt
629 * from the command line:
630 * - spaces and tabs must be quoted
632 * - quotes must be escaped
634 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
635 * resulting in an odd number of '\' followed by a '"'
638 * - '\'s that are not followed by a '"' can be left as is
642 static BOOL
build_command_line( WCHAR
**argv
)
647 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
649 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
652 for (arg
= argv
; *arg
; arg
++)
654 int has_space
,bcount
;
660 if( !*a
) has_space
=1;
665 if (*a
==' ' || *a
=='\t') {
667 } else if (*a
=='"') {
668 /* doubling of '\' preceding a '"',
669 * plus escaping of said '"'
677 len
+=(a
-*arg
)+1 /* for the separating space */;
679 len
+=2; /* for the quotes */
682 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
685 p
= rupp
->CommandLine
.Buffer
;
686 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
687 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
688 for (arg
= argv
; *arg
; arg
++)
690 int has_space
,has_quote
;
693 /* Check for quotes and spaces in this argument */
694 has_space
=has_quote
=0;
696 if( !*a
) has_space
=1;
698 if (*a
==' ' || *a
=='\t') {
702 } else if (*a
=='"') {
710 /* Now transfer it to the command line */
727 /* Double all the '\\' preceding this '"', plus one */
728 for (i
=0;i
<=bcount
;i
++)
740 while ((*p
=*x
++)) p
++;
746 if (p
> rupp
->CommandLine
.Buffer
)
747 p
--; /* remove last space */
754 /***********************************************************************
755 * init_current_directory
757 * Initialize the current directory from the Unix cwd or the parent info.
759 static void init_current_directory( CURDIR
*cur_dir
)
761 UNICODE_STRING dir_str
;
765 /* if we received a cur dir from the parent, try this first */
767 if (cur_dir
->DosPath
.Length
)
769 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
772 /* now try to get it from the Unix cwd */
774 for (size
= 256; ; size
*= 2)
776 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
777 if (getcwd( cwd
, size
)) break;
778 HeapFree( GetProcessHeap(), 0, cwd
);
779 if (errno
== ERANGE
) continue;
787 int lenW
= MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, NULL
, 0 );
788 if ((dirW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) )))
790 MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, dirW
, lenW
);
791 RtlInitUnicodeString( &dir_str
, dirW
);
792 RtlSetCurrentDirectory_U( &dir_str
);
793 RtlFreeUnicodeString( &dir_str
);
797 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
799 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
800 "starting in the Windows directory.\n", cwd
? cwd
: "" );
801 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
802 RtlSetCurrentDirectory_U( &dir_str
);
804 HeapFree( GetProcessHeap(), 0, cwd
);
807 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
808 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
812 /***********************************************************************
815 * Initialize the windows and system directories from the environment.
817 static void init_windows_dirs(void)
819 extern void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
821 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
822 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
823 static const WCHAR default_windirW
[] = {'C',':','\\','w','i','n','d','o','w','s',0};
824 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m','3','2',0};
829 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
831 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
832 GetEnvironmentVariableW( windirW
, buffer
, len
);
833 DIR_Windows
= buffer
;
835 else DIR_Windows
= default_windirW
;
837 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
839 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
840 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
845 len
= strlenW( DIR_Windows
);
846 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
847 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
848 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
852 if (!CreateDirectoryW( DIR_Windows
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
853 ERR( "directory %s could not be created, error %u\n",
854 debugstr_w(DIR_Windows
), GetLastError() );
855 if (!CreateDirectoryW( DIR_System
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
856 ERR( "directory %s could not be created, error %u\n",
857 debugstr_w(DIR_System
), GetLastError() );
859 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
860 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
862 /* set the directories in ntdll too */
863 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
867 /***********************************************************************
870 * Start the wineboot process if necessary. Return the event to wait on.
872 static HANDLE
start_wineboot(void)
874 static const WCHAR wineboot_eventW
[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
877 if (!(event
= CreateEventW( NULL
, TRUE
, FALSE
, wineboot_eventW
)))
879 ERR( "failed to create wineboot event, expect trouble\n" );
882 if (GetLastError() != ERROR_ALREADY_EXISTS
) /* we created it */
884 static const WCHAR command_line
[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
886 PROCESS_INFORMATION pi
;
887 WCHAR cmdline
[MAX_PATH
+ sizeof(command_line
)/sizeof(WCHAR
)];
889 memset( &si
, 0, sizeof(si
) );
891 si
.dwFlags
= STARTF_USESTDHANDLES
;
894 si
.hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
896 GetSystemDirectoryW( cmdline
, MAX_PATH
);
897 lstrcatW( cmdline
, command_line
);
898 if (CreateProcessW( NULL
, cmdline
, NULL
, NULL
, FALSE
, DETACHED_PROCESS
, NULL
, NULL
, &si
, &pi
))
900 TRACE( "started wineboot pid %04x tid %04x\n", pi
.dwProcessId
, pi
.dwThreadId
);
901 CloseHandle( pi
.hThread
);
902 CloseHandle( pi
.hProcess
);
905 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
911 /***********************************************************************
914 * Startup routine of a new process. Runs on the new process stack.
916 static void start_process( void *arg
)
920 PEB
*peb
= NtCurrentTeb()->Peb
;
921 IMAGE_NT_HEADERS
*nt
;
922 LPTHREAD_START_ROUTINE entry
;
924 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
925 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
926 nt
->OptionalHeader
.AddressOfEntryPoint
);
928 if (!nt
->OptionalHeader
.AddressOfEntryPoint
)
930 ERR( "%s doesn't have an entry point, it cannot be executed\n",
931 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
) );
936 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
937 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
939 SetLastError( 0 ); /* clear error code */
940 if (peb
->BeingDebugged
) DbgBreakPoint();
941 ExitThread( entry( peb
) );
943 __EXCEPT(UnhandledExceptionFilter
)
945 TerminateThread( GetCurrentThread(), GetExceptionCode() );
951 /***********************************************************************
954 * Change the process name in the ps output.
956 static void set_process_name( int argc
, char *argv
[] )
958 #ifdef HAVE_SETPROCTITLE
959 setproctitle("-%s", argv
[1]);
964 char *p
, *prctl_name
= argv
[1];
965 char *end
= argv
[argc
-1] + strlen(argv
[argc
-1]) + 1;
968 # define PR_SET_NAME 15
971 if ((p
= strrchr( prctl_name
, '\\' ))) prctl_name
= p
+ 1;
972 if ((p
= strrchr( prctl_name
, '/' ))) prctl_name
= p
+ 1;
974 if (prctl( PR_SET_NAME
, prctl_name
) != -1)
976 offset
= argv
[1] - argv
[0];
977 memmove( argv
[1] - offset
, argv
[1], end
- argv
[1] );
978 memset( end
- offset
, 0, offset
);
979 for (i
= 1; i
< argc
; i
++) argv
[i
-1] = argv
[i
] - offset
;
983 #endif /* HAVE_PRCTL */
986 memmove( argv
, argv
+ 1, argc
* sizeof(argv
[0]) );
991 /***********************************************************************
994 * Wine initialisation: load and start the main exe file.
996 void CDECL
__wine_kernel_init(void)
998 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
999 static const WCHAR dotW
[] = {'.',0};
1000 static const WCHAR exeW
[] = {'.','e','x','e',0};
1002 WCHAR
*p
, main_exe_name
[MAX_PATH
+1];
1003 PEB
*peb
= NtCurrentTeb()->Peb
;
1004 RTL_USER_PROCESS_PARAMETERS
*params
= peb
->ProcessParameters
;
1005 HANDLE boot_event
= 0;
1006 BOOL got_environment
= TRUE
;
1008 /* Initialize everything */
1010 setbuf(stdout
,NULL
);
1011 setbuf(stderr
,NULL
);
1012 kernel32_handle
= GetModuleHandleW(kernel32W
);
1016 if (!params
->Environment
)
1018 /* Copy the parent environment */
1019 if (!build_initial_environment()) exit(1);
1021 /* convert old configuration to new format */
1022 convert_old_config();
1024 got_environment
= set_registry_environment();
1025 set_additional_environment();
1028 init_windows_dirs();
1029 init_current_directory( ¶ms
->CurrentDirectory
);
1031 set_process_name( __wine_main_argc
, __wine_main_argv
);
1032 set_library_wargv( __wine_main_argv
);
1034 if (peb
->ProcessParameters
->ImagePathName
.Buffer
)
1036 strcpyW( main_exe_name
, peb
->ProcessParameters
->ImagePathName
.Buffer
);
1040 if (!SearchPathW( NULL
, __wine_main_wargv
[0], exeW
, MAX_PATH
, main_exe_name
, NULL
) &&
1041 !get_builtin_path( __wine_main_wargv
[0], exeW
, main_exe_name
, MAX_PATH
))
1043 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1044 ExitProcess( GetLastError() );
1046 update_library_argv0( main_exe_name
);
1047 if (!build_command_line( __wine_main_wargv
)) goto error
;
1048 boot_event
= start_wineboot();
1051 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1052 p
= strrchrW( main_exe_name
, '.' );
1053 if (!p
|| strchrW( p
, '/' ) || strchrW( p
, '\\' )) strcatW( main_exe_name
, dotW
);
1055 TRACE( "starting process name=%s argv[0]=%s\n",
1056 debugstr_w(main_exe_name
), debugstr_w(__wine_main_wargv
[0]) );
1058 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1059 MODULE_get_dll_load_path(main_exe_name
) );
1063 if (WaitForSingleObject( boot_event
, 30000 )) ERR( "boot event wait timed out\n" );
1064 CloseHandle( boot_event
);
1065 /* if we didn't find environment section, try again now that wineboot has run */
1066 if (!got_environment
)
1068 set_registry_environment();
1069 set_additional_environment();
1073 if (!(peb
->ImageBaseAddress
= LoadLibraryExW( main_exe_name
, 0, DONT_RESOLVE_DLL_REFERENCES
)))
1076 DWORD error
= GetLastError();
1078 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1079 if (error
== ERROR_BAD_EXE_FORMAT
||
1080 error
== ERROR_INVALID_ADDRESS
||
1081 error
== ERROR_NOT_ENOUGH_MEMORY
)
1083 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name
);
1084 /* if we get back here, it failed */
1086 else if (error
== ERROR_MOD_NOT_FOUND
)
1088 if ((p
= strrchrW( main_exe_name
, '\\' ))) p
++;
1089 else p
= main_exe_name
;
1090 if (!strcmpiW( p
, winevdmW
) && __wine_main_argc
> 3)
1092 /* args 1 and 2 are --app-name full_path */
1093 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1094 debugstr_w(__wine_main_wargv
[3]) );
1095 ExitProcess( ERROR_BAD_EXE_FORMAT
);
1098 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, error
, 0, msg
, sizeof(msg
), NULL
);
1099 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name
), msg
);
1100 ExitProcess( error
);
1103 LdrInitializeThunk( 0, 0, 0, 0 );
1104 /* switch to the new stack */
1105 wine_switch_to_stack( start_process
, NULL
, NtCurrentTeb()->Tib
.StackBase
);
1108 ExitProcess( GetLastError() );
1112 /***********************************************************************
1115 * Build an argv array from a command-line.
1116 * 'reserved' is the number of args to reserve before the first one.
1118 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1122 char *arg
,*s
,*d
,*cmdline
;
1123 int in_quotes
,bcount
,len
;
1125 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1126 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, len
))) return NULL
;
1127 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1134 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1137 /* skip the remaining spaces */
1138 while (*s
==' ' || *s
=='\t') {
1145 } else if (*s
=='\\') {
1146 /* '\', count them */
1148 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1150 in_quotes
=!in_quotes
;
1153 /* a regular character */
1158 if (!(argv
= HeapAlloc( GetProcessHeap(), 0, argc
*sizeof(*argv
) + len
)))
1160 HeapFree( GetProcessHeap(), 0, cmdline
);
1164 arg
= d
= s
= (char *)(argv
+ argc
);
1165 memcpy( d
, cmdline
, len
);
1170 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1171 /* Close the argument and copy it */
1175 /* skip the remaining spaces */
1178 } while (*s
==' ' || *s
=='\t');
1180 /* Start with a new argument */
1183 } else if (*s
=='\\') {
1187 } else if (*s
=='"') {
1189 if ((bcount
& 1)==0) {
1190 /* Preceded by an even number of '\', this is half that
1191 * number of '\', plus a '"' which we discard.
1195 in_quotes
=!in_quotes
;
1197 /* Preceded by an odd number of '\', this is half that
1198 * number of '\' followed by a '"'
1206 /* a regular character */
1217 HeapFree( GetProcessHeap(), 0, cmdline
);
1222 /***********************************************************************
1225 * Build the environment of a new child process.
1227 static char **build_envp( const WCHAR
*envW
)
1229 static const char * const unix_vars
[] = { "PATH", "TEMP", "TMP", "HOME" };
1234 int count
= 1, length
;
1237 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1239 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1240 if (!(env
= HeapAlloc( GetProcessHeap(), 0, length
))) return NULL
;
1241 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1243 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1244 if (is_special_env_var( p
)) length
+= 4; /* prefix it with "WINE" */
1246 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1248 if (!(p
= getenv(unix_vars
[i
]))) continue;
1249 length
+= strlen(unix_vars
[i
]) + strlen(p
) + 2;
1253 if ((envp
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*envp
) + length
)))
1255 char **envptr
= envp
;
1256 char *dst
= (char *)(envp
+ count
);
1258 /* some variables must not be modified, so we get them directly from the unix env */
1259 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1261 if (!(p
= getenv(unix_vars
[i
]))) continue;
1262 *envptr
++ = strcpy( dst
, unix_vars
[i
] );
1265 dst
+= strlen(dst
) + 1;
1268 /* now put the Windows environment strings */
1269 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1271 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1272 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1273 if (!strncmp( p
, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1274 if (!strncmp( p
, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1275 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1277 *envptr
++ = strcpy( dst
, "WINE" );
1282 *envptr
++ = strcpy( dst
, p
);
1284 dst
+= strlen(dst
) + 1;
1288 HeapFree( GetProcessHeap(), 0, env
);
1293 /***********************************************************************
1296 * Fork and exec a new Unix binary, checking for errors.
1298 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
, const WCHAR
*env
,
1299 const char *newdir
, DWORD flags
, STARTUPINFOW
*startup
)
1301 int fd
[2], stdin_fd
= -1, stdout_fd
= -1;
1303 char **argv
, **envp
;
1305 if (!env
) env
= GetEnvironmentStringsW();
1309 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1312 fcntl( fd
[1], F_SETFD
, 1 ); /* set close on exec */
1314 if (!(flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1316 HANDLE hstdin
, hstdout
;
1318 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1320 hstdin
= startup
->hStdInput
;
1321 hstdout
= startup
->hStdOutput
;
1325 hstdin
= GetStdHandle(STD_INPUT_HANDLE
);
1326 hstdout
= GetStdHandle(STD_OUTPUT_HANDLE
);
1329 if (is_console_handle( hstdin
))
1330 hstdin
= wine_server_ptr_handle( console_handle_unmap( hstdin
));
1331 if (is_console_handle( hstdout
))
1332 hstdout
= wine_server_ptr_handle( console_handle_unmap( hstdout
));
1333 wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1334 wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1337 argv
= build_argv( cmdline
, 0 );
1338 envp
= build_envp( env
);
1340 if (!(pid
= fork())) /* child */
1344 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1347 if (!(pid
= fork()))
1349 int fd
= open( "/dev/null", O_RDWR
);
1351 /* close stdin and stdout */
1359 else if (pid
!= -1) _exit(0); /* parent */
1365 dup2( stdin_fd
, 0 );
1368 if (stdout_fd
!= -1)
1370 dup2( stdout_fd
, 1 );
1375 /* Reset signals that we previously set to SIG_IGN */
1376 signal( SIGPIPE
, SIG_DFL
);
1377 signal( SIGCHLD
, SIG_DFL
);
1379 if (newdir
) chdir(newdir
);
1381 if (argv
&& envp
) execve( filename
, argv
, envp
);
1383 write( fd
[1], &err
, sizeof(err
) );
1386 HeapFree( GetProcessHeap(), 0, argv
);
1387 HeapFree( GetProcessHeap(), 0, envp
);
1388 if (stdin_fd
!= -1) close( stdin_fd
);
1389 if (stdout_fd
!= -1) close( stdout_fd
);
1391 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1396 if (pid
== -1) FILE_SetDosError();
1402 /***********************************************************************
1403 * create_user_params
1405 static RTL_USER_PROCESS_PARAMETERS
*create_user_params( LPCWSTR filename
, LPCWSTR cmdline
,
1406 LPCWSTR cur_dir
, LPWSTR env
, DWORD flags
,
1407 const STARTUPINFOW
*startup
)
1409 RTL_USER_PROCESS_PARAMETERS
*params
;
1410 UNICODE_STRING image_str
, cmdline_str
, curdir_str
, desktop
, title
, runtime
, newdir
;
1412 WCHAR buffer
[MAX_PATH
];
1414 if(!GetLongPathNameW( filename
, buffer
, MAX_PATH
))
1415 lstrcpynW( buffer
, filename
, MAX_PATH
);
1416 if(!GetFullPathNameW( buffer
, MAX_PATH
, buffer
, NULL
))
1417 lstrcpynW( buffer
, filename
, MAX_PATH
);
1418 RtlInitUnicodeString( &image_str
, buffer
);
1420 RtlInitUnicodeString( &cmdline_str
, cmdline
);
1421 newdir
.Buffer
= NULL
;
1424 if (RtlDosPathNameToNtPathName_U( cur_dir
, &newdir
, NULL
, NULL
))
1426 /* skip \??\ prefix */
1427 curdir_str
.Buffer
= newdir
.Buffer
+ 4;
1428 curdir_str
.Length
= newdir
.Length
- 4 * sizeof(WCHAR
);
1429 curdir_str
.MaximumLength
= newdir
.MaximumLength
- 4 * sizeof(WCHAR
);
1431 else cur_dir
= NULL
;
1433 if (startup
->lpDesktop
) RtlInitUnicodeString( &desktop
, startup
->lpDesktop
);
1434 if (startup
->lpTitle
) RtlInitUnicodeString( &title
, startup
->lpTitle
);
1435 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1438 runtime
.MaximumLength
= startup
->cbReserved2
;
1439 runtime
.Buffer
= (WCHAR
*)startup
->lpReserved2
;
1442 status
= RtlCreateProcessParameters( ¶ms
, &image_str
, NULL
,
1443 cur_dir
? &curdir_str
: NULL
,
1445 startup
->lpTitle
? &title
: NULL
,
1446 startup
->lpDesktop
? &desktop
: NULL
,
1448 (startup
->lpReserved2
&& startup
->cbReserved2
) ? &runtime
: NULL
);
1449 RtlFreeUnicodeString( &newdir
);
1450 if (status
!= STATUS_SUCCESS
)
1452 SetLastError( RtlNtStatusToDosError(status
) );
1456 if (flags
& CREATE_NEW_PROCESS_GROUP
) params
->ConsoleFlags
= 1;
1457 if (flags
& CREATE_NEW_CONSOLE
) params
->ConsoleHandle
= (HANDLE
)1; /* FIXME: cf. kernel_main.c */
1459 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1461 params
->hStdInput
= startup
->hStdInput
;
1462 params
->hStdOutput
= startup
->hStdOutput
;
1463 params
->hStdError
= startup
->hStdError
;
1467 params
->hStdInput
= GetStdHandle( STD_INPUT_HANDLE
);
1468 params
->hStdOutput
= GetStdHandle( STD_OUTPUT_HANDLE
);
1469 params
->hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
1471 params
->dwX
= startup
->dwX
;
1472 params
->dwY
= startup
->dwY
;
1473 params
->dwXSize
= startup
->dwXSize
;
1474 params
->dwYSize
= startup
->dwYSize
;
1475 params
->dwXCountChars
= startup
->dwXCountChars
;
1476 params
->dwYCountChars
= startup
->dwYCountChars
;
1477 params
->dwFillAttribute
= startup
->dwFillAttribute
;
1478 params
->dwFlags
= startup
->dwFlags
;
1479 params
->wShowWindow
= startup
->wShowWindow
;
1484 /***********************************************************************
1487 * Create a new process. If hFile is a valid handle we have an exe
1488 * file, otherwise it is a Winelib app.
1490 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1491 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1492 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1493 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1494 void *res_start
, void *res_end
, int exec_only
)
1496 BOOL ret
, success
= FALSE
;
1497 HANDLE process_info
, hstdin
, hstdout
;
1499 char *winedebug
= NULL
;
1501 RTL_USER_PROCESS_PARAMETERS
*params
;
1502 int socketfd
[2], stdin_fd
= -1, stdout_fd
= -1;
1506 if (!env
) RtlAcquirePebLock();
1508 if (!(params
= create_user_params( filename
, cmd_line
, cur_dir
, env
, flags
, startup
)))
1510 if (!env
) RtlReleasePebLock();
1513 env_end
= params
->Environment
;
1516 static const WCHAR WINEDEBUG
[] = {'W','I','N','E','D','E','B','U','G','=',0};
1517 if (!winedebug
&& !strncmpW( env_end
, WINEDEBUG
, sizeof(WINEDEBUG
)/sizeof(WCHAR
) - 1 ))
1519 DWORD len
= WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, NULL
, 0, NULL
, NULL
);
1520 if ((winedebug
= HeapAlloc( GetProcessHeap(), 0, len
)))
1521 WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, winedebug
, len
, NULL
, NULL
);
1523 env_end
+= strlenW(env_end
) + 1;
1527 /* create the socket for the new process */
1529 if (socketpair( PF_UNIX
, SOCK_STREAM
, 0, socketfd
) == -1)
1531 if (!env
) RtlReleasePebLock();
1532 HeapFree( GetProcessHeap(), 0, winedebug
);
1533 RtlDestroyProcessParameters( params
);
1534 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1537 wine_server_send_fd( socketfd
[1] );
1538 close( socketfd
[1] );
1540 /* create the process on the server side */
1542 SERVER_START_REQ( new_process
)
1544 req
->inherit_all
= inherit
;
1545 req
->create_flags
= flags
;
1546 req
->socket_fd
= socketfd
[1];
1547 req
->exe_file
= wine_server_obj_handle( hFile
);
1548 req
->process_access
= PROCESS_ALL_ACCESS
;
1549 req
->process_attr
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1550 req
->thread_access
= THREAD_ALL_ACCESS
;
1551 req
->thread_attr
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1552 req
->hstdin
= wine_server_obj_handle( params
->hStdInput
);
1553 req
->hstdout
= wine_server_obj_handle( params
->hStdOutput
);
1554 req
->hstderr
= wine_server_obj_handle( params
->hStdError
);
1556 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1558 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1559 if (is_console_handle(params
->hStdInput
)) req
->hstdin
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1560 if (is_console_handle(params
->hStdOutput
)) req
->hstdout
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1561 if (is_console_handle(params
->hStdError
)) req
->hstderr
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1562 hstdin
= hstdout
= 0;
1566 if (is_console_handle(params
->hStdInput
)) req
->hstdin
= console_handle_unmap(params
->hStdInput
);
1567 if (is_console_handle(params
->hStdOutput
)) req
->hstdout
= console_handle_unmap(params
->hStdOutput
);
1568 if (is_console_handle(params
->hStdError
)) req
->hstderr
= console_handle_unmap(params
->hStdError
);
1569 hstdin
= wine_server_ptr_handle( req
->hstdin
);
1570 hstdout
= wine_server_ptr_handle( req
->hstdout
);
1573 wine_server_add_data( req
, params
, params
->Size
);
1574 wine_server_add_data( req
, params
->Environment
, (env_end
-params
->Environment
)*sizeof(WCHAR
) );
1575 if ((ret
= !wine_server_call_err( req
)))
1577 info
->dwProcessId
= (DWORD
)reply
->pid
;
1578 info
->dwThreadId
= (DWORD
)reply
->tid
;
1579 info
->hProcess
= wine_server_ptr_handle( reply
->phandle
);
1580 info
->hThread
= wine_server_ptr_handle( reply
->thandle
);
1582 process_info
= wine_server_ptr_handle( reply
->info
);
1586 if (!env
) RtlReleasePebLock();
1587 RtlDestroyProcessParameters( params
);
1590 close( socketfd
[0] );
1591 HeapFree( GetProcessHeap(), 0, winedebug
);
1595 if (hstdin
) wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1596 if (hstdout
) wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1598 /* create the child process */
1599 argv
= build_argv( cmd_line
, 1 );
1601 if (exec_only
|| !(pid
= fork())) /* child */
1603 char preloader_reserve
[64], socket_env
[64];
1605 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1607 if (!(pid
= fork()))
1609 int fd
= open( "/dev/null", O_RDWR
);
1611 /* close stdin and stdout */
1619 else if (pid
!= -1) _exit(0); /* parent */
1623 if (stdin_fd
!= -1) dup2( stdin_fd
, 0 );
1624 if (stdout_fd
!= -1) dup2( stdout_fd
, 1 );
1627 if (stdin_fd
!= -1) close( stdin_fd
);
1628 if (stdout_fd
!= -1) close( stdout_fd
);
1630 /* Reset signals that we previously set to SIG_IGN */
1631 signal( SIGPIPE
, SIG_DFL
);
1632 signal( SIGCHLD
, SIG_DFL
);
1634 sprintf( socket_env
, "WINESERVERSOCKET=%u", socketfd
[0] );
1635 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx",
1636 (unsigned long)res_start
, (unsigned long)res_end
);
1638 putenv( preloader_reserve
);
1639 putenv( socket_env
);
1640 if (winedebug
) putenv( winedebug
);
1641 if (unixdir
) chdir(unixdir
);
1643 if (argv
) wine_exec_wine_binary( NULL
, argv
, getenv("WINELOADER") );
1647 /* this is the parent */
1649 if (stdin_fd
!= -1) close( stdin_fd
);
1650 if (stdout_fd
!= -1) close( stdout_fd
);
1651 close( socketfd
[0] );
1652 HeapFree( GetProcessHeap(), 0, argv
);
1653 HeapFree( GetProcessHeap(), 0, winedebug
);
1660 /* wait for the new process info to be ready */
1662 WaitForSingleObject( process_info
, INFINITE
);
1663 SERVER_START_REQ( get_new_process_info
)
1665 req
->info
= wine_server_obj_handle( process_info
);
1666 wine_server_call( req
);
1667 success
= reply
->success
;
1668 err
= reply
->exit_code
;
1674 SetLastError( err
? err
: ERROR_INTERNAL_ERROR
);
1677 CloseHandle( process_info
);
1681 CloseHandle( process_info
);
1682 CloseHandle( info
->hProcess
);
1683 CloseHandle( info
->hThread
);
1684 info
->hProcess
= info
->hThread
= 0;
1685 info
->dwProcessId
= info
->dwThreadId
= 0;
1690 /***********************************************************************
1691 * create_vdm_process
1693 * Create a new VDM process for a 16-bit or DOS application.
1695 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
1696 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1697 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1698 LPPROCESS_INFORMATION info
, LPCSTR unixdir
, int exec_only
)
1700 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1703 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
1704 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
1708 SetLastError( ERROR_OUTOFMEMORY
);
1711 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
1712 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
1713 flags
, startup
, info
, unixdir
, NULL
, NULL
, exec_only
);
1714 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
1719 /***********************************************************************
1720 * create_cmd_process
1722 * Create a new cmd shell process for a .BAT file.
1724 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
1725 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1726 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1727 LPPROCESS_INFORMATION info
)
1730 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
1731 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
1732 WCHAR comspec
[MAX_PATH
];
1736 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
1738 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
1739 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
1742 strcpyW( newcmdline
, comspec
);
1743 strcatW( newcmdline
, slashcW
);
1744 strcatW( newcmdline
, cmd_line
);
1745 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
1746 flags
, env
, cur_dir
, startup
, info
);
1747 HeapFree( GetProcessHeap(), 0, newcmdline
);
1752 /*************************************************************************
1755 * Helper for CreateProcess: retrieve the file name to load from the
1756 * app name and command line. Store the file name in buffer, and
1757 * return a possibly modified command line.
1758 * Also returns a handle to the opened file if it's a Windows binary.
1760 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
1761 int buflen
, HANDLE
*handle
)
1763 static const WCHAR quotesW
[] = {'"','%','s','"',0};
1765 WCHAR
*name
, *pos
, *ret
= NULL
;
1769 /* if we have an app name, everything is easy */
1773 /* use the unmodified app name as file name */
1774 lstrcpynW( buffer
, appname
, buflen
);
1775 *handle
= open_exe_file( buffer
);
1776 if (!(ret
= cmdline
) || !cmdline
[0])
1778 /* no command-line, create one */
1779 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
1780 sprintfW( ret
, quotesW
, appname
);
1785 /* first check for a quoted file name */
1787 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
1789 int len
= p
- cmdline
- 1;
1790 /* extract the quoted portion as file name */
1791 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1792 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
1795 if (find_exe_file( name
, buffer
, buflen
, handle
))
1796 ret
= cmdline
; /* no change necessary */
1800 /* now try the command-line word by word */
1802 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
1810 do *pos
++ = *p
++; while (*p
&& *p
!= ' ' && *p
!= '\t');
1812 if (find_exe_file( name
, buffer
, buflen
, handle
))
1817 if (*p
) got_space
= TRUE
;
1820 if (ret
&& got_space
) /* now build a new command-line with quotes */
1822 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
1824 sprintfW( ret
, quotesW
, name
);
1827 else if (!ret
) SetLastError( ERROR_FILE_NOT_FOUND
);
1830 HeapFree( GetProcessHeap(), 0, name
);
1835 /**********************************************************************
1836 * CreateProcessA (KERNEL32.@)
1838 BOOL WINAPI
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1839 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
1840 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
1841 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
1844 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
1845 UNICODE_STRING desktopW
, titleW
;
1848 desktopW
.Buffer
= NULL
;
1849 titleW
.Buffer
= NULL
;
1850 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
1851 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
1852 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
1854 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
1855 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
1857 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
1858 infoW
.lpDesktop
= desktopW
.Buffer
;
1859 infoW
.lpTitle
= titleW
.Buffer
;
1861 if (startup_info
->lpReserved
)
1862 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1863 debugstr_a(startup_info
->lpReserved
));
1865 ret
= CreateProcessW( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
1866 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
1868 HeapFree( GetProcessHeap(), 0, app_nameW
);
1869 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
1870 HeapFree( GetProcessHeap(), 0, cur_dirW
);
1871 RtlFreeUnicodeString( &desktopW
);
1872 RtlFreeUnicodeString( &titleW
);
1877 /**********************************************************************
1878 * CreateProcessW (KERNEL32.@)
1880 BOOL WINAPI
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1881 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
1882 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
1883 LPPROCESS_INFORMATION info
)
1887 char *unixdir
= NULL
;
1888 WCHAR name
[MAX_PATH
];
1889 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
1890 void *res_start
, *res_end
;
1892 /* Process the AppName and/or CmdLine to get module name and path */
1894 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
1896 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
)/sizeof(WCHAR
), &hFile
)))
1898 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
1900 /* Warn if unsupported features are used */
1902 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
1903 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
1904 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
1905 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
1906 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name
), flags
);
1910 if (!(unixdir
= wine_get_unix_file_name( cur_dir
)))
1912 SetLastError(ERROR_DIRECTORY
);
1918 WCHAR buf
[MAX_PATH
];
1919 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
1922 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
1927 while (*p
) p
+= strlen(p
) + 1;
1928 p
++; /* final null */
1929 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
1930 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
1931 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
1932 flags
|= CREATE_UNICODE_ENVIRONMENT
;
1935 info
->hThread
= info
->hProcess
= 0;
1936 info
->dwProcessId
= info
->dwThreadId
= 0;
1938 /* Determine executable type */
1940 if (!hFile
) /* builtin exe */
1942 TRACE( "starting %s as Winelib app\n", debugstr_w(name
) );
1943 retv
= create_process( 0, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1944 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
, FALSE
);
1948 switch( MODULE_GetBinaryType( hFile
, &res_start
, &res_end
))
1951 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name
), res_start
, res_end
);
1952 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1953 inherit
, flags
, startup_info
, info
, unixdir
, res_start
, res_end
, FALSE
);
1958 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
1959 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1960 inherit
, flags
, startup_info
, info
, unixdir
, FALSE
);
1963 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
1964 SetLastError( ERROR_BAD_EXE_FORMAT
);
1966 case BINARY_UNIX_LIB
:
1967 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
1968 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1969 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
, FALSE
);
1971 case BINARY_UNKNOWN
:
1972 /* check for .com or .bat extension */
1973 if ((p
= strrchrW( name
, '.' )))
1975 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
1977 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
1978 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1979 inherit
, flags
, startup_info
, info
, unixdir
, FALSE
);
1982 if (!strcmpiW( p
, batW
) || !strcmpiW( p
, cmdW
) )
1984 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
1985 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1986 inherit
, flags
, startup_info
, info
);
1991 case BINARY_UNIX_EXE
:
1993 /* unknown file, try as unix executable */
1996 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
1998 if ((unix_name
= wine_get_unix_file_name( name
)))
2000 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
, flags
, startup_info
) != -1);
2001 HeapFree( GetProcessHeap(), 0, unix_name
);
2006 CloseHandle( hFile
);
2009 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
2010 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
2011 HeapFree( GetProcessHeap(), 0, unixdir
);
2013 TRACE( "started process pid %04x tid %04x\n", info
->dwProcessId
, info
->dwThreadId
);
2018 /**********************************************************************
2021 static void exec_process( LPCWSTR name
)
2025 void *res_start
, *res_end
;
2026 STARTUPINFOW startup_info
;
2027 PROCESS_INFORMATION info
;
2029 hFile
= open_exe_file( name
);
2030 if (!hFile
|| hFile
== INVALID_HANDLE_VALUE
) return;
2032 memset( &startup_info
, 0, sizeof(startup_info
) );
2033 startup_info
.cb
= sizeof(startup_info
);
2035 /* Determine executable type */
2037 switch( MODULE_GetBinaryType( hFile
, &res_start
, &res_end
))
2040 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name
), res_start
, res_end
);
2041 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2042 FALSE
, 0, &startup_info
, &info
, NULL
, res_start
, res_end
, TRUE
);
2044 case BINARY_UNIX_LIB
:
2045 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
2046 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2047 FALSE
, 0, &startup_info
, &info
, NULL
, NULL
, NULL
, TRUE
);
2049 case BINARY_UNKNOWN
:
2050 /* check for .com or .pif extension */
2051 if (!(p
= strrchrW( name
, '.' ))) break;
2052 if (strcmpiW( p
, comW
) && strcmpiW( p
, pifW
)) break;
2057 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2058 create_vdm_process( name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2059 FALSE
, 0, &startup_info
, &info
, NULL
, TRUE
);
2064 CloseHandle( hFile
);
2068 /***********************************************************************
2071 * Wrapper to call WaitForInputIdle USER function
2073 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2075 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2077 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2080 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2081 if (ptr
) return ptr( process
, timeout
);
2087 /***********************************************************************
2088 * WinExec (KERNEL32.@)
2090 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2092 PROCESS_INFORMATION info
;
2093 STARTUPINFOA startup
;
2097 memset( &startup
, 0, sizeof(startup
) );
2098 startup
.cb
= sizeof(startup
);
2099 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2100 startup
.wShowWindow
= nCmdShow
;
2102 /* cmdline needs to be writable for CreateProcess */
2103 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2104 strcpy( cmdline
, lpCmdLine
);
2106 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2107 0, NULL
, NULL
, &startup
, &info
))
2109 /* Give 30 seconds to the app to come up */
2110 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2111 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2113 /* Close off the handles */
2114 CloseHandle( info
.hThread
);
2115 CloseHandle( info
.hProcess
);
2117 else if ((ret
= GetLastError()) >= 32)
2119 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2122 HeapFree( GetProcessHeap(), 0, cmdline
);
2127 /**********************************************************************
2128 * LoadModule (KERNEL32.@)
2130 HINSTANCE WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2132 LOADPARMS32
*params
= paramBlock
;
2133 PROCESS_INFORMATION info
;
2134 STARTUPINFOA startup
;
2135 HINSTANCE hInstance
;
2137 char filename
[MAX_PATH
];
2140 if (!name
) return (HINSTANCE
)ERROR_FILE_NOT_FOUND
;
2142 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2143 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2144 return ULongToHandle(GetLastError());
2146 len
= (BYTE
)params
->lpCmdLine
[0];
2147 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2148 return (HINSTANCE
)ERROR_NOT_ENOUGH_MEMORY
;
2150 strcpy( cmdline
, filename
);
2151 p
= cmdline
+ strlen(cmdline
);
2153 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2156 memset( &startup
, 0, sizeof(startup
) );
2157 startup
.cb
= sizeof(startup
);
2158 if (params
->lpCmdShow
)
2160 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2161 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2164 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2165 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2167 /* Give 30 seconds to the app to come up */
2168 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2169 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2170 hInstance
= (HINSTANCE
)33;
2171 /* Close off the handles */
2172 CloseHandle( info
.hThread
);
2173 CloseHandle( info
.hProcess
);
2175 else if ((hInstance
= ULongToHandle(GetLastError())) >= (HINSTANCE
)32)
2177 FIXME("Strange error set by CreateProcess: %p\n", hInstance
);
2178 hInstance
= (HINSTANCE
)11;
2181 HeapFree( GetProcessHeap(), 0, cmdline
);
2186 /******************************************************************************
2187 * TerminateProcess (KERNEL32.@)
2189 * Terminates a process.
2192 * handle [I] Process to terminate.
2193 * exit_code [I] Exit code.
2197 * Failure: FALSE, check GetLastError().
2199 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2201 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2202 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2206 /***********************************************************************
2207 * ExitProcess (KERNEL32.@)
2209 * Exits the current process.
2212 * status [I] Status code to exit with.
2218 __ASM_GLOBAL_FUNC( ExitProcess
, /* Shrinker depend on this particular ExitProcess implementation */
2220 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2221 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2222 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2224 "call " __ASM_NAME("process_ExitProcess") "\n\t"
2228 void WINAPI
process_ExitProcess( DWORD status
)
2230 LdrShutdownProcess();
2231 NtTerminateProcess(GetCurrentProcess(), status
);
2237 void WINAPI
ExitProcess( DWORD status
)
2239 LdrShutdownProcess();
2240 NtTerminateProcess(GetCurrentProcess(), status
);
2246 /***********************************************************************
2247 * GetExitCodeProcess [KERNEL32.@]
2249 * Gets termination status of specified process.
2252 * hProcess [in] Handle to the process.
2253 * lpExitCode [out] Address to receive termination status.
2259 BOOL WINAPI
GetExitCodeProcess( HANDLE hProcess
, LPDWORD lpExitCode
)
2262 PROCESS_BASIC_INFORMATION pbi
;
2264 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2266 if (status
== STATUS_SUCCESS
)
2268 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2271 SetLastError( RtlNtStatusToDosError(status
) );
2276 /***********************************************************************
2277 * SetErrorMode (KERNEL32.@)
2279 UINT WINAPI
SetErrorMode( UINT mode
)
2281 UINT old
= process_error_mode
;
2282 process_error_mode
= mode
;
2286 /***********************************************************************
2287 * GetErrorMode (KERNEL32.@)
2289 UINT WINAPI
GetErrorMode( void )
2291 return process_error_mode
;
2294 /**********************************************************************
2295 * TlsAlloc [KERNEL32.@]
2297 * Allocates a thread local storage index.
2300 * Success: TLS index.
2301 * Failure: 0xFFFFFFFF
2303 DWORD WINAPI
TlsAlloc( void )
2306 PEB
* const peb
= NtCurrentTeb()->Peb
;
2308 RtlAcquirePebLock();
2309 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 0 );
2310 if (index
!= ~0U) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2313 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2316 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2317 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2318 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2320 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2322 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2326 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2327 index
+= TLS_MINIMUM_AVAILABLE
;
2330 else SetLastError( ERROR_NO_MORE_ITEMS
);
2332 RtlReleasePebLock();
2337 /**********************************************************************
2338 * TlsFree [KERNEL32.@]
2340 * Releases a thread local storage index, making it available for reuse.
2343 * index [in] TLS index to free.
2349 BOOL WINAPI
TlsFree( DWORD index
)
2353 RtlAcquirePebLock();
2354 if (index
>= TLS_MINIMUM_AVAILABLE
)
2356 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2357 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2361 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2362 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2364 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2365 else SetLastError( ERROR_INVALID_PARAMETER
);
2366 RtlReleasePebLock();
2371 /**********************************************************************
2372 * TlsGetValue [KERNEL32.@]
2374 * Gets value in a thread's TLS slot.
2377 * index [in] TLS index to retrieve value for.
2380 * Success: Value stored in calling thread's TLS slot for index.
2381 * Failure: 0 and GetLastError() returns NO_ERROR.
2383 LPVOID WINAPI
TlsGetValue( DWORD index
)
2387 if (index
< TLS_MINIMUM_AVAILABLE
)
2389 ret
= NtCurrentTeb()->TlsSlots
[index
];
2393 index
-= TLS_MINIMUM_AVAILABLE
;
2394 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2396 SetLastError( ERROR_INVALID_PARAMETER
);
2399 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2400 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2402 SetLastError( ERROR_SUCCESS
);
2407 /**********************************************************************
2408 * TlsSetValue [KERNEL32.@]
2410 * Stores a value in the thread's TLS slot.
2413 * index [in] TLS index to set value for.
2414 * value [in] Value to be stored.
2420 BOOL WINAPI
TlsSetValue( DWORD index
, LPVOID value
)
2422 if (index
< TLS_MINIMUM_AVAILABLE
)
2424 NtCurrentTeb()->TlsSlots
[index
] = value
;
2428 index
-= TLS_MINIMUM_AVAILABLE
;
2429 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2431 SetLastError( ERROR_INVALID_PARAMETER
);
2434 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2435 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2436 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2438 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2441 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2447 /***********************************************************************
2448 * GetProcessFlags (KERNEL32.@)
2450 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2452 IMAGE_NT_HEADERS
*nt
;
2455 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2457 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2459 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2460 flags
|= PDB32_CONSOLE_PROC
;
2462 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2463 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2468 /***********************************************************************
2469 * GetProcessDword (KERNEL.485)
2470 * GetProcessDword (KERNEL32.18)
2471 * 'Of course you cannot directly access Windows internal structures'
2473 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
2478 TRACE("(%d, %d)\n", dwProcessID
, offset
);
2480 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2482 ERR("%d: process %x not accessible\n", offset
, dwProcessID
);
2488 case GPD_APP_COMPAT_FLAGS
:
2489 return GetAppCompatFlags16(0);
2490 case GPD_LOAD_DONE_EVENT
:
2492 case GPD_HINSTANCE16
:
2493 return GetTaskDS16();
2494 case GPD_WINDOWS_VERSION
:
2495 return GetExeVersion16();
2497 return (DWORD_PTR
)NtCurrentTeb() - 0x10 /* FIXME */;
2499 return (DWORD_PTR
)NtCurrentTeb()->Peb
; /* FIXME: truncating a pointer */
2500 case GPD_STARTF_SHELLDATA
: /* return stdoutput handle from startupinfo ??? */
2501 GetStartupInfoW(&siw
);
2502 return HandleToULong(siw
.hStdOutput
);
2503 case GPD_STARTF_HOTKEY
: /* return stdinput handle from startupinfo ??? */
2504 GetStartupInfoW(&siw
);
2505 return HandleToULong(siw
.hStdInput
);
2506 case GPD_STARTF_SHOWWINDOW
:
2507 GetStartupInfoW(&siw
);
2508 return siw
.wShowWindow
;
2509 case GPD_STARTF_SIZE
:
2510 GetStartupInfoW(&siw
);
2512 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2514 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2515 return MAKELONG( x
, y
);
2516 case GPD_STARTF_POSITION
:
2517 GetStartupInfoW(&siw
);
2519 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2521 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2522 return MAKELONG( x
, y
);
2523 case GPD_STARTF_FLAGS
:
2524 GetStartupInfoW(&siw
);
2529 return GetProcessFlags(0);
2531 return process_dword
;
2533 ERR("Unknown offset %d\n", offset
);
2538 /***********************************************************************
2539 * SetProcessDword (KERNEL.484)
2540 * 'Of course you cannot directly access Windows internal structures'
2542 void WINAPI
SetProcessDword( DWORD dwProcessID
, INT offset
, DWORD value
)
2544 TRACE("(%d, %d)\n", dwProcessID
, offset
);
2546 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2548 ERR("%d: process %x not accessible\n", offset
, dwProcessID
);
2554 case GPD_APP_COMPAT_FLAGS
:
2555 case GPD_LOAD_DONE_EVENT
:
2556 case GPD_HINSTANCE16
:
2557 case GPD_WINDOWS_VERSION
:
2560 case GPD_STARTF_SHELLDATA
:
2561 case GPD_STARTF_HOTKEY
:
2562 case GPD_STARTF_SHOWWINDOW
:
2563 case GPD_STARTF_SIZE
:
2564 case GPD_STARTF_POSITION
:
2565 case GPD_STARTF_FLAGS
:
2568 ERR("Not allowed to modify offset %d\n", offset
);
2571 process_dword
= value
;
2574 ERR("Unknown offset %d\n", offset
);
2580 /***********************************************************************
2581 * ExitProcess (KERNEL.466)
2583 void WINAPI
ExitProcess16( WORD status
)
2586 ReleaseThunkLock( &count
);
2587 ExitProcess( status
);
2591 /*********************************************************************
2592 * OpenProcess (KERNEL32.@)
2594 * Opens a handle to a process.
2597 * access [I] Desired access rights assigned to the returned handle.
2598 * inherit [I] Determines whether or not child processes will inherit the handle.
2599 * id [I] Process identifier of the process to get a handle to.
2602 * Success: Valid handle to the specified process.
2603 * Failure: NULL, check GetLastError().
2605 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2609 OBJECT_ATTRIBUTES attr
;
2612 cid
.UniqueProcess
= ULongToHandle(id
);
2613 cid
.UniqueThread
= 0; /* FIXME ? */
2615 attr
.Length
= sizeof(OBJECT_ATTRIBUTES
);
2616 attr
.RootDirectory
= NULL
;
2617 attr
.Attributes
= inherit
? OBJ_INHERIT
: 0;
2618 attr
.SecurityDescriptor
= NULL
;
2619 attr
.SecurityQualityOfService
= NULL
;
2620 attr
.ObjectName
= NULL
;
2622 if (GetVersion() & 0x80000000) access
= PROCESS_ALL_ACCESS
;
2624 status
= NtOpenProcess(&handle
, access
, &attr
, &cid
);
2625 if (status
!= STATUS_SUCCESS
)
2627 SetLastError( RtlNtStatusToDosError(status
) );
2634 /*********************************************************************
2635 * MapProcessHandle (KERNEL.483)
2636 * GetProcessId (KERNEL32.@)
2638 * Gets the a unique identifier of a process.
2641 * hProcess [I] Handle to the process.
2645 * Failure: FALSE, check GetLastError().
2649 * The identifier is unique only on the machine and only until the process
2650 * exits (including system shutdown).
2652 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2655 PROCESS_BASIC_INFORMATION pbi
;
2657 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2659 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2660 SetLastError( RtlNtStatusToDosError(status
) );
2665 /*********************************************************************
2666 * CloseW32Handle (KERNEL.474)
2667 * CloseHandle (KERNEL32.@)
2672 * handle [I] Handle to close.
2676 * Failure: FALSE, check GetLastError().
2678 BOOL WINAPI
CloseHandle( HANDLE handle
)
2682 /* stdio handles need special treatment */
2683 if ((handle
== (HANDLE
)STD_INPUT_HANDLE
) ||
2684 (handle
== (HANDLE
)STD_OUTPUT_HANDLE
) ||
2685 (handle
== (HANDLE
)STD_ERROR_HANDLE
))
2686 handle
= GetStdHandle( HandleToULong(handle
) );
2688 if (is_console_handle(handle
))
2689 return CloseConsoleHandle(handle
);
2691 status
= NtClose( handle
);
2692 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2697 /*********************************************************************
2698 * GetHandleInformation (KERNEL32.@)
2700 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2702 OBJECT_DATA_INFORMATION info
;
2703 NTSTATUS status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
);
2705 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2709 if (info
.InheritHandle
) *flags
|= HANDLE_FLAG_INHERIT
;
2710 if (info
.ProtectFromClose
) *flags
|= HANDLE_FLAG_PROTECT_FROM_CLOSE
;
2716 /*********************************************************************
2717 * SetHandleInformation (KERNEL32.@)
2719 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2721 OBJECT_DATA_INFORMATION info
;
2724 /* if not setting both fields, retrieve current value first */
2725 if ((mask
& (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
)) !=
2726 (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
))
2728 if ((status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
)))
2730 SetLastError( RtlNtStatusToDosError(status
) );
2734 if (mask
& HANDLE_FLAG_INHERIT
)
2735 info
.InheritHandle
= (flags
& HANDLE_FLAG_INHERIT
) != 0;
2736 if (mask
& HANDLE_FLAG_PROTECT_FROM_CLOSE
)
2737 info
.ProtectFromClose
= (flags
& HANDLE_FLAG_PROTECT_FROM_CLOSE
) != 0;
2739 status
= NtSetInformationObject( handle
, ObjectDataInformation
, &info
, sizeof(info
) );
2740 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2745 /*********************************************************************
2746 * DuplicateHandle (KERNEL32.@)
2748 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2749 HANDLE dest_process
, HANDLE
*dest
,
2750 DWORD access
, BOOL inherit
, DWORD options
)
2754 if (is_console_handle(source
))
2756 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2757 if (source_process
!= dest_process
||
2758 source_process
!= GetCurrentProcess())
2760 SetLastError(ERROR_INVALID_PARAMETER
);
2763 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2764 return (*dest
!= INVALID_HANDLE_VALUE
);
2766 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2767 access
, inherit
? OBJ_INHERIT
: 0, options
);
2768 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2773 /***********************************************************************
2774 * ConvertToGlobalHandle (KERNEL.476)
2775 * ConvertToGlobalHandle (KERNEL32.@)
2777 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
2779 HANDLE ret
= INVALID_HANDLE_VALUE
;
2780 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
2781 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
2786 /***********************************************************************
2787 * SetHandleContext (KERNEL32.@)
2789 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
2791 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2792 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
2793 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2798 /***********************************************************************
2799 * GetHandleContext (KERNEL32.@)
2801 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
2803 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2804 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
2805 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2810 /***********************************************************************
2811 * CreateSocketHandle (KERNEL32.@)
2813 HANDLE WINAPI
CreateSocketHandle(void)
2815 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2816 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2817 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2818 return INVALID_HANDLE_VALUE
;
2822 /***********************************************************************
2823 * SetPriorityClass (KERNEL32.@)
2825 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
2828 PROCESS_PRIORITY_CLASS ppc
;
2830 ppc
.Foreground
= FALSE
;
2831 switch (priorityclass
)
2833 case IDLE_PRIORITY_CLASS
:
2834 ppc
.PriorityClass
= PROCESS_PRIOCLASS_IDLE
; break;
2835 case BELOW_NORMAL_PRIORITY_CLASS
:
2836 ppc
.PriorityClass
= PROCESS_PRIOCLASS_BELOW_NORMAL
; break;
2837 case NORMAL_PRIORITY_CLASS
:
2838 ppc
.PriorityClass
= PROCESS_PRIOCLASS_NORMAL
; break;
2839 case ABOVE_NORMAL_PRIORITY_CLASS
:
2840 ppc
.PriorityClass
= PROCESS_PRIOCLASS_ABOVE_NORMAL
; break;
2841 case HIGH_PRIORITY_CLASS
:
2842 ppc
.PriorityClass
= PROCESS_PRIOCLASS_HIGH
; break;
2843 case REALTIME_PRIORITY_CLASS
:
2844 ppc
.PriorityClass
= PROCESS_PRIOCLASS_REALTIME
; break;
2846 SetLastError(ERROR_INVALID_PARAMETER
);
2850 status
= NtSetInformationProcess(hprocess
, ProcessPriorityClass
,
2853 if (status
!= STATUS_SUCCESS
)
2855 SetLastError( RtlNtStatusToDosError(status
) );
2862 /***********************************************************************
2863 * GetPriorityClass (KERNEL32.@)
2865 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
2868 PROCESS_BASIC_INFORMATION pbi
;
2870 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2872 if (status
!= STATUS_SUCCESS
)
2874 SetLastError( RtlNtStatusToDosError(status
) );
2877 switch (pbi
.BasePriority
)
2879 case PROCESS_PRIOCLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
2880 case PROCESS_PRIOCLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
2881 case PROCESS_PRIOCLASS_NORMAL
: return NORMAL_PRIORITY_CLASS
;
2882 case PROCESS_PRIOCLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
2883 case PROCESS_PRIOCLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
2884 case PROCESS_PRIOCLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
2886 SetLastError( ERROR_INVALID_PARAMETER
);
2891 /***********************************************************************
2892 * SetProcessAffinityMask (KERNEL32.@)
2894 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
2898 status
= NtSetInformationProcess(hProcess
, ProcessAffinityMask
,
2899 &affmask
, sizeof(DWORD_PTR
));
2902 SetLastError( RtlNtStatusToDosError(status
) );
2909 /**********************************************************************
2910 * GetProcessAffinityMask (KERNEL32.@)
2912 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
2913 PDWORD_PTR lpProcessAffinityMask
,
2914 PDWORD_PTR lpSystemAffinityMask
)
2916 PROCESS_BASIC_INFORMATION pbi
;
2919 status
= NtQueryInformationProcess(hProcess
,
2920 ProcessBasicInformation
,
2921 &pbi
, sizeof(pbi
), NULL
);
2924 SetLastError( RtlNtStatusToDosError(status
) );
2927 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= pbi
.AffinityMask
;
2928 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= (1 << NtCurrentTeb()->Peb
->NumberOfProcessors
) - 1;
2933 /***********************************************************************
2934 * GetProcessVersion (KERNEL32.@)
2936 DWORD WINAPI
GetProcessVersion( DWORD pid
)
2940 PROCESS_BASIC_INFORMATION pbi
;
2943 IMAGE_DOS_HEADER dos
;
2944 IMAGE_NT_HEADERS nt
;
2947 if (!pid
|| pid
== GetCurrentProcessId())
2949 IMAGE_NT_HEADERS
*nt
;
2951 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2952 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
2953 nt
->OptionalHeader
.MinorSubsystemVersion
);
2957 process
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
2958 if (!process
) return 0;
2960 status
= NtQueryInformationProcess(process
, ProcessBasicInformation
, &pbi
, sizeof(pbi
), NULL
);
2961 if (status
) goto err
;
2963 status
= NtReadVirtualMemory(process
, pbi
.PebBaseAddress
, &peb
, sizeof(peb
), &count
);
2964 if (status
|| count
!= sizeof(peb
)) goto err
;
2966 memset(&dos
, 0, sizeof(dos
));
2967 status
= NtReadVirtualMemory(process
, peb
.ImageBaseAddress
, &dos
, sizeof(dos
), &count
);
2968 if (status
|| count
!= sizeof(dos
)) goto err
;
2969 if (dos
.e_magic
!= IMAGE_DOS_SIGNATURE
) goto err
;
2971 memset(&nt
, 0, sizeof(nt
));
2972 status
= NtReadVirtualMemory(process
, (char *)peb
.ImageBaseAddress
+ dos
.e_lfanew
, &nt
, sizeof(nt
), &count
);
2973 if (status
|| count
!= sizeof(nt
)) goto err
;
2974 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) goto err
;
2976 ver
= MAKELONG(nt
.OptionalHeader
.MinorSubsystemVersion
, nt
.OptionalHeader
.MajorSubsystemVersion
);
2979 CloseHandle(process
);
2981 if (status
!= STATUS_SUCCESS
)
2982 SetLastError(RtlNtStatusToDosError(status
));
2988 /***********************************************************************
2989 * SetProcessWorkingSetSize [KERNEL32.@]
2990 * Sets the min/max working set sizes for a specified process.
2993 * hProcess [I] Handle to the process of interest
2994 * minset [I] Specifies minimum working set size
2995 * maxset [I] Specifies maximum working set size
3001 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
3004 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
3005 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
3006 /* Trim the working set to zero */
3007 /* Swap the process out of physical RAM */
3012 /***********************************************************************
3013 * GetProcessWorkingSetSize (KERNEL32.@)
3015 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
3018 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
3019 /* 32 MB working set size */
3020 if (minset
) *minset
= 32*1024*1024;
3021 if (maxset
) *maxset
= 32*1024*1024;
3026 /***********************************************************************
3027 * SetProcessShutdownParameters (KERNEL32.@)
3029 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
3031 FIXME("(%08x, %08x): partial stub.\n", level
, flags
);
3032 shutdown_flags
= flags
;
3033 shutdown_priority
= level
;
3038 /***********************************************************************
3039 * GetProcessShutdownParameters (KERNEL32.@)
3042 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
3044 *lpdwLevel
= shutdown_priority
;
3045 *lpdwFlags
= shutdown_flags
;
3050 /***********************************************************************
3051 * GetProcessPriorityBoost (KERNEL32.@)
3053 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
3055 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
3057 /* Report that no boost is present.. */
3058 *pDisablePriorityBoost
= FALSE
;
3063 /***********************************************************************
3064 * SetProcessPriorityBoost (KERNEL32.@)
3066 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
3068 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
3069 /* Say we can do it. I doubt the program will notice that we don't. */
3074 /***********************************************************************
3075 * ReadProcessMemory (KERNEL32.@)
3077 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
3078 SIZE_T
*bytes_read
)
3080 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
3081 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3086 /***********************************************************************
3087 * WriteProcessMemory (KERNEL32.@)
3089 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
3090 SIZE_T
*bytes_written
)
3092 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
3093 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3098 /****************************************************************************
3099 * FlushInstructionCache (KERNEL32.@)
3101 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
3104 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
3105 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3110 /******************************************************************
3111 * GetProcessIoCounters (KERNEL32.@)
3113 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
3117 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
3118 ioc
, sizeof(*ioc
), NULL
);
3119 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3123 /******************************************************************
3124 * GetProcessHandleCount (KERNEL32.@)
3126 BOOL WINAPI
GetProcessHandleCount(HANDLE hProcess
, DWORD
*cnt
)
3130 status
= NtQueryInformationProcess(hProcess
, ProcessHandleCount
,
3131 cnt
, sizeof(*cnt
), NULL
);
3132 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3136 /******************************************************************
3137 * QueryFullProcessImageNameW (KERNEL32.@)
3139 BOOL WINAPI
QueryFullProcessImageNameW(HANDLE hProcess
, DWORD dwFlags
, LPWSTR lpExeName
, PDWORD pdwSize
)
3141 BYTE buffer
[sizeof(UNICODE_STRING
) + MAX_PATH
*sizeof(WCHAR
)]; /* this buffer should be enough */
3142 UNICODE_STRING
*dynamic_buffer
= NULL
;
3143 UNICODE_STRING nt_path
;
3144 UNICODE_STRING
*result
= NULL
;
3148 RtlInitUnicodeStringEx(&nt_path
, NULL
);
3149 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3150 * as this is on Wine. */
3151 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, buffer
,
3152 sizeof(buffer
) - sizeof(WCHAR
), &needed
);
3153 if (status
== STATUS_INFO_LENGTH_MISMATCH
)
3155 dynamic_buffer
= HeapAlloc(GetProcessHeap(), 0, needed
+ sizeof(WCHAR
));
3156 status
= NtQueryInformationProcess(hProcess
, ProcessImageFileName
, (LPBYTE
)dynamic_buffer
, needed
, &needed
);
3157 result
= dynamic_buffer
;
3160 result
= (PUNICODE_STRING
)buffer
;
3162 if (status
) goto cleanup
;
3164 if (dwFlags
& PROCESS_NAME_NATIVE
)
3166 result
->Buffer
[result
->Length
/ sizeof(WCHAR
)] = 0;
3167 if (!RtlDosPathNameToNtPathName_U(result
->Buffer
, &nt_path
, NULL
, NULL
))
3169 status
= STATUS_OBJECT_PATH_NOT_FOUND
;
3175 if (result
->Length
/sizeof(WCHAR
) + 1 > *pdwSize
)
3177 status
= STATUS_BUFFER_TOO_SMALL
;
3181 *pdwSize
= result
->Length
/sizeof(WCHAR
);
3182 memcpy( lpExeName
, result
->Buffer
, result
->Length
);
3183 lpExeName
[*pdwSize
] = 0;
3186 HeapFree(GetProcessHeap(), 0, dynamic_buffer
);
3187 RtlFreeUnicodeString(&nt_path
);
3188 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3192 /***********************************************************************
3193 * ProcessIdToSessionId (KERNEL32.@)
3194 * This function is available on Terminal Server 4SP4 and Windows 2000
3196 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
3198 /* According to MSDN, if the calling process is not in a terminal
3199 * services environment, then the sessionid returned is zero.
3206 /***********************************************************************
3207 * RegisterServiceProcess (KERNEL.491)
3208 * RegisterServiceProcess (KERNEL32.@)
3210 * A service process calls this function to ensure that it continues to run
3211 * even after a user logged off.
3213 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
3215 /* I don't think that Wine needs to do anything in this function */
3216 return 1; /* success */
3220 /**********************************************************************
3221 * IsWow64Process (KERNEL32.@)
3223 BOOL WINAPI
IsWow64Process(HANDLE hProcess
, PBOOL Wow64Process
)
3228 status
= NtQueryInformationProcess( hProcess
, ProcessWow64Information
, &pbi
, sizeof(pbi
), NULL
);
3230 if (status
!= STATUS_SUCCESS
)
3232 SetLastError( RtlNtStatusToDosError( status
) );
3235 *Wow64Process
= (pbi
!= 0);
3240 /***********************************************************************
3241 * GetCurrentProcess (KERNEL32.@)
3243 * Get a handle to the current process.
3249 * A handle representing the current process.
3251 #undef GetCurrentProcess
3252 HANDLE WINAPI
GetCurrentProcess(void)
3254 return (HANDLE
)~(ULONG_PTR
)0;
3257 /***********************************************************************
3258 * CmdBatNotification (KERNEL32.@)
3260 * Notifies the system that a batch file has started or finished.
3263 * bBatchRunning [I] TRUE if a batch file has started or
3264 * FALSE if a batch file has finished executing.
3269 BOOL WINAPI
CmdBatNotification( BOOL bBatchRunning
)
3271 FIXME("%d\n", bBatchRunning
);
3276 /***********************************************************************
3277 * RegisterApplicationRestart (KERNEL32.@)
3279 HRESULT WINAPI
RegisterApplicationRestart(PCWSTR pwzCommandLine
, DWORD dwFlags
)
3281 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine
), dwFlags
);