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
);
67 static UINT process_error_mode
;
69 static DWORD shutdown_flags
= 0;
70 static DWORD shutdown_priority
= 0x280;
71 static DWORD process_dword
;
73 HMODULE kernel32_handle
= 0;
75 const WCHAR
*DIR_Windows
= NULL
;
76 const WCHAR
*DIR_System
= NULL
;
79 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
80 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
81 #define PDB32_DOS_PROC 0x0010 /* Dos process */
82 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
83 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
84 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
86 static const WCHAR comW
[] = {'.','c','o','m',0};
87 static const WCHAR batW
[] = {'.','b','a','t',0};
88 static const WCHAR cmdW
[] = {'.','c','m','d',0};
89 static const WCHAR pifW
[] = {'.','p','i','f',0};
90 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
92 static void exec_process( LPCWSTR name
);
94 extern void SHELL_LoadRegistry(void);
97 /***********************************************************************
100 static inline int contains_path( LPCWSTR name
)
102 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
106 /***********************************************************************
109 * Check if an environment variable needs to be handled specially when
110 * passed through the Unix environment (i.e. prefixed with "WINE").
112 static inline int is_special_env_var( const char *var
)
114 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
115 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
116 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
117 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
121 /***************************************************************************
124 * Get the path of a builtin module when the native file does not exist.
126 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
, UINT size
)
129 UINT len
= strlenW( DIR_System
);
131 if (contains_path( libname
))
133 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
134 filename
, &file_part
) > size
* sizeof(WCHAR
))
135 return FALSE
; /* too long */
137 if (strncmpiW( filename
, DIR_System
, len
) || filename
[len
] != '\\')
139 while (filename
[len
] == '\\') len
++;
140 if (filename
+ len
!= file_part
) return FALSE
;
144 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
145 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
146 file_part
= filename
+ len
;
147 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
148 strcpyW( file_part
, libname
);
150 if (ext
&& !strchrW( file_part
, '.' ))
152 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
153 return FALSE
; /* too long */
154 strcatW( file_part
, ext
);
160 /***********************************************************************
161 * open_builtin_exe_file
163 * Open an exe file for a builtin exe.
165 static void *open_builtin_exe_file( const WCHAR
*name
, char *error
, int error_size
,
166 int test_only
, int *file_exists
)
168 char exename
[MAX_PATH
];
173 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
174 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
176 /* we don't want to depend on the current codepage here */
177 len
= strlenW( name
) + 1;
178 if (len
>= sizeof(exename
)) return NULL
;
179 for (i
= 0; i
< len
; i
++)
181 if (name
[i
] > 127) return NULL
;
182 exename
[i
] = (char)name
[i
];
183 if (exename
[i
] >= 'A' && exename
[i
] <= 'Z') exename
[i
] += 'a' - 'A';
185 return wine_dll_load_main_exe( exename
, error
, error_size
, test_only
, file_exists
);
189 /***********************************************************************
192 * Open a specific exe file, taking load order into account.
193 * Returns the file handle or 0 for a builtin exe.
195 static HANDLE
open_exe_file( const WCHAR
*name
)
199 TRACE("looking for %s\n", debugstr_w(name
) );
201 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
202 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
204 WCHAR buffer
[MAX_PATH
];
205 /* file doesn't exist, check for builtin */
206 if (!contains_path( name
)) goto error
;
207 if (!get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
) )) goto error
;
213 SetLastError( ERROR_FILE_NOT_FOUND
);
214 return INVALID_HANDLE_VALUE
;
218 /***********************************************************************
221 * Open an exe file, and return the full name and file handle.
222 * Returns FALSE if file could not be found.
223 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
224 * If file is a builtin exe, returns TRUE and sets handle to 0.
226 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
, HANDLE
*handle
)
228 static const WCHAR exeW
[] = {'.','e','x','e',0};
231 TRACE("looking for %s\n", debugstr_w(name
) );
233 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
) &&
234 !get_builtin_path( name
, exeW
, buffer
, buflen
))
236 /* no builtin found, try native without extension in case it is a Unix app */
238 if (SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
))
240 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer
) );
241 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
242 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
248 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
249 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
250 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
253 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer
) );
254 open_builtin_exe_file( buffer
, NULL
, 0, 1, &file_exists
);
265 /***********************************************************************
266 * build_initial_environment
268 * Build the Win32 environment from the Unix environment
270 static BOOL
build_initial_environment( char **environ
)
277 /* Compute the total size of the Unix environment */
278 for (e
= environ
; *e
; e
++)
280 if (is_special_env_var( *e
)) continue;
281 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
283 size
*= sizeof(WCHAR
);
285 /* Now allocate the environment */
287 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
288 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
291 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
292 endptr
= p
+ size
/ sizeof(WCHAR
);
294 /* And fill it with the Unix environment */
295 for (e
= environ
; *e
; e
++)
299 /* skip Unix special variables and use the Wine variants instead */
300 if (!strncmp( str
, "WINE", 4 ))
302 if (is_special_env_var( str
+ 4 )) str
+= 4;
303 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
305 else if (is_special_env_var( str
)) continue; /* skip it */
307 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
315 /***********************************************************************
316 * set_registry_variables
318 * Set environment variables by enumerating the values of a key;
319 * helper for set_registry_environment().
320 * Note that Windows happily truncates the value if it's too big.
322 static void set_registry_variables( HANDLE hkey
, ULONG type
)
324 UNICODE_STRING env_name
, env_value
;
328 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
329 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
331 for (index
= 0; ; index
++)
333 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
334 buffer
, sizeof(buffer
), &size
);
335 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
337 if (info
->Type
!= type
)
339 env_name
.Buffer
= info
->Name
;
340 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
341 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
342 env_value
.Length
= env_value
.MaximumLength
= info
->DataLength
;
343 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
344 env_value
.Length
-= sizeof(WCHAR
); /* don't count terminating null if any */
345 if (info
->Type
== REG_EXPAND_SZ
)
347 WCHAR buf_expanded
[1024];
348 UNICODE_STRING env_expanded
;
349 env_expanded
.Length
= env_expanded
.MaximumLength
= sizeof(buf_expanded
);
350 env_expanded
.Buffer
=buf_expanded
;
351 status
= RtlExpandEnvironmentStrings_U(NULL
, &env_value
, &env_expanded
, NULL
);
352 if (status
== STATUS_SUCCESS
|| status
== STATUS_BUFFER_OVERFLOW
)
353 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_expanded
);
357 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
363 /***********************************************************************
364 * set_registry_environment
366 * Set the environment variables specified in the registry.
368 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
369 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
370 * on the order in which the variables are processed. But on Windows it
371 * does not really matter since they only use %SystemDrive% and
372 * %SystemRoot% which are predefined. But Wine defines these in the
373 * registry, so we need two passes.
375 static BOOL
set_registry_environment(void)
377 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
378 'S','y','s','t','e','m','\\',
379 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
380 'C','o','n','t','r','o','l','\\',
381 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
382 'E','n','v','i','r','o','n','m','e','n','t',0};
383 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
385 OBJECT_ATTRIBUTES attr
;
386 UNICODE_STRING nameW
;
390 attr
.Length
= sizeof(attr
);
391 attr
.RootDirectory
= 0;
392 attr
.ObjectName
= &nameW
;
394 attr
.SecurityDescriptor
= NULL
;
395 attr
.SecurityQualityOfService
= NULL
;
397 /* first the system environment variables */
398 RtlInitUnicodeString( &nameW
, env_keyW
);
399 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
401 set_registry_variables( hkey
, REG_SZ
);
402 set_registry_variables( hkey
, REG_EXPAND_SZ
);
407 /* then the ones for the current user */
408 if (RtlOpenCurrentUser( KEY_ALL_ACCESS
, &attr
.RootDirectory
) != STATUS_SUCCESS
) return ret
;
409 RtlInitUnicodeString( &nameW
, envW
);
410 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
412 set_registry_variables( hkey
, REG_SZ
);
413 set_registry_variables( hkey
, REG_EXPAND_SZ
);
416 NtClose( attr
.RootDirectory
);
421 /***********************************************************************
424 static WCHAR
*get_reg_value( HKEY hkey
, const WCHAR
*name
)
426 char buffer
[1024 * sizeof(WCHAR
) + sizeof(KEY_VALUE_PARTIAL_INFORMATION
)];
427 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
428 DWORD len
, size
= sizeof(buffer
);
430 UNICODE_STRING nameW
;
432 RtlInitUnicodeString( &nameW
, name
);
433 if (NtQueryValueKey( hkey
, &nameW
, KeyValuePartialInformation
, buffer
, size
, &size
))
436 if (size
<= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) return NULL
;
437 len
= (size
- FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
)) / sizeof(WCHAR
);
439 if (info
->Type
== REG_EXPAND_SZ
)
441 UNICODE_STRING value
, expanded
;
443 value
.MaximumLength
= len
* sizeof(WCHAR
);
444 value
.Buffer
= (WCHAR
*)info
->Data
;
445 if (!value
.Buffer
[len
- 1]) len
--; /* don't count terminating null if any */
446 value
.Length
= len
* sizeof(WCHAR
);
447 expanded
.Length
= expanded
.MaximumLength
= 1024 * sizeof(WCHAR
);
448 if (!(expanded
.Buffer
= HeapAlloc( GetProcessHeap(), 0, expanded
.MaximumLength
))) return NULL
;
449 if (!RtlExpandEnvironmentStrings_U( NULL
, &value
, &expanded
, NULL
)) ret
= expanded
.Buffer
;
450 else RtlFreeUnicodeString( &expanded
);
452 else if (info
->Type
== REG_SZ
)
454 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
456 memcpy( ret
, info
->Data
, len
* sizeof(WCHAR
) );
464 /***********************************************************************
465 * set_additional_environment
467 * Set some additional environment variables not specified in the registry.
469 static void set_additional_environment(void)
471 static const WCHAR profile_keyW
[] = {'M','a','c','h','i','n','e','\\',
472 'S','o','f','t','w','a','r','e','\\',
473 'M','i','c','r','o','s','o','f','t','\\',
474 'W','i','n','d','o','w','s',' ','N','T','\\',
475 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
476 'P','r','o','f','i','l','e','L','i','s','t',0};
477 static const WCHAR profiles_valueW
[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
478 static const WCHAR all_users_valueW
[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
479 static const WCHAR usernameW
[] = {'U','S','E','R','N','A','M','E',0};
480 static const WCHAR userprofileW
[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
481 static const WCHAR allusersW
[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
482 OBJECT_ATTRIBUTES attr
;
483 UNICODE_STRING nameW
;
484 WCHAR
*user_name
= NULL
, *profile_dir
= NULL
, *all_users_dir
= NULL
;
486 const char *name
= wine_get_user_name();
489 /* set the USERNAME variable */
491 len
= MultiByteToWideChar( CP_UNIXCP
, 0, name
, -1, NULL
, 0 );
494 user_name
= HeapAlloc( GetProcessHeap(), 0, len
*sizeof(WCHAR
) );
495 MultiByteToWideChar( CP_UNIXCP
, 0, name
, -1, user_name
, len
);
496 SetEnvironmentVariableW( usernameW
, user_name
);
499 /* set the USERPROFILE and ALLUSERSPROFILE variables */
501 attr
.Length
= sizeof(attr
);
502 attr
.RootDirectory
= 0;
503 attr
.ObjectName
= &nameW
;
505 attr
.SecurityDescriptor
= NULL
;
506 attr
.SecurityQualityOfService
= NULL
;
507 RtlInitUnicodeString( &nameW
, profile_keyW
);
508 if (!NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
))
510 profile_dir
= get_reg_value( hkey
, profiles_valueW
);
511 all_users_dir
= get_reg_value( hkey
, all_users_valueW
);
519 if (all_users_dir
) len
= max( len
, strlenW(all_users_dir
) + 1 );
520 len
+= strlenW(profile_dir
) + 1;
521 value
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
522 strcpyW( value
, profile_dir
);
523 p
= value
+ strlenW(value
);
524 if (p
> value
&& p
[-1] != '\\') *p
++ = '\\';
525 strcpyW( p
, user_name
);
526 SetEnvironmentVariableW( userprofileW
, value
);
529 strcpyW( p
, all_users_dir
);
530 SetEnvironmentVariableW( allusersW
, value
);
532 HeapFree( GetProcessHeap(), 0, value
);
535 HeapFree( GetProcessHeap(), 0, all_users_dir
);
536 HeapFree( GetProcessHeap(), 0, profile_dir
);
537 HeapFree( GetProcessHeap(), 0, user_name
);
540 /***********************************************************************
543 * Set the Wine library Unicode argv global variables.
545 static void set_library_wargv( char **argv
)
553 for (argc
= 0; argv
[argc
]; argc
++)
554 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
556 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
557 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
558 p
= (WCHAR
*)(wargv
+ argc
+ 1);
559 for (argc
= 0; argv
[argc
]; argc
++)
561 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
568 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
570 for (argc
= 0; wargv
[argc
]; argc
++)
571 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
573 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
574 q
= (char *)(argv
+ argc
+ 1);
575 for (argc
= 0; wargv
[argc
]; argc
++)
577 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
584 __wine_main_argc
= argc
;
585 __wine_main_argv
= argv
;
586 __wine_main_wargv
= wargv
;
590 /***********************************************************************
593 * Build the command line of a process from the argv array.
595 * Note that it does NOT necessarily include the file name.
596 * Sometimes we don't even have any command line options at all.
598 * We must quote and escape characters so that the argv array can be rebuilt
599 * from the command line:
600 * - spaces and tabs must be quoted
602 * - quotes must be escaped
604 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
605 * resulting in an odd number of '\' followed by a '"'
608 * - '\'s that are not followed by a '"' can be left as is
612 static BOOL
build_command_line( WCHAR
**argv
)
617 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
619 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
622 for (arg
= argv
; *arg
; arg
++)
624 int has_space
,bcount
;
630 if( !*a
) has_space
=1;
635 if (*a
==' ' || *a
=='\t') {
637 } else if (*a
=='"') {
638 /* doubling of '\' preceding a '"',
639 * plus escaping of said '"'
647 len
+=(a
-*arg
)+1 /* for the separating space */;
649 len
+=2; /* for the quotes */
652 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
655 p
= rupp
->CommandLine
.Buffer
;
656 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
657 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
658 for (arg
= argv
; *arg
; arg
++)
660 int has_space
,has_quote
;
663 /* Check for quotes and spaces in this argument */
664 has_space
=has_quote
=0;
666 if( !*a
) has_space
=1;
668 if (*a
==' ' || *a
=='\t') {
672 } else if (*a
=='"') {
680 /* Now transfer it to the command line */
697 /* Double all the '\\' preceding this '"', plus one */
698 for (i
=0;i
<=bcount
;i
++)
710 while ((*p
=*x
++)) p
++;
716 if (p
> rupp
->CommandLine
.Buffer
)
717 p
--; /* remove last space */
724 /***********************************************************************
725 * init_current_directory
727 * Initialize the current directory from the Unix cwd or the parent info.
729 static void init_current_directory( CURDIR
*cur_dir
)
731 UNICODE_STRING dir_str
;
735 /* if we received a cur dir from the parent, try this first */
737 if (cur_dir
->DosPath
.Length
)
739 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
742 /* now try to get it from the Unix cwd */
744 for (size
= 256; ; size
*= 2)
746 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
747 if (getcwd( cwd
, size
)) break;
748 HeapFree( GetProcessHeap(), 0, cwd
);
749 if (errno
== ERANGE
) continue;
757 int lenW
= MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, NULL
, 0 );
758 if ((dirW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) )))
760 MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, dirW
, lenW
);
761 RtlInitUnicodeString( &dir_str
, dirW
);
762 RtlSetCurrentDirectory_U( &dir_str
);
763 RtlFreeUnicodeString( &dir_str
);
767 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
769 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
770 "starting in the Windows directory.\n", cwd
? cwd
: "" );
771 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
772 RtlSetCurrentDirectory_U( &dir_str
);
774 HeapFree( GetProcessHeap(), 0, cwd
);
777 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
778 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
782 /***********************************************************************
785 * Initialize the windows and system directories from the environment.
787 static void init_windows_dirs(void)
789 extern void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
791 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
792 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
793 static const WCHAR default_windirW
[] = {'C',':','\\','w','i','n','d','o','w','s',0};
794 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m','3','2',0};
799 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
801 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
802 GetEnvironmentVariableW( windirW
, buffer
, len
);
803 DIR_Windows
= buffer
;
805 else DIR_Windows
= default_windirW
;
807 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
809 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
810 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
815 len
= strlenW( DIR_Windows
);
816 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
817 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
818 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
822 if (!CreateDirectoryW( DIR_Windows
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
823 ERR( "directory %s could not be created, error %u\n",
824 debugstr_w(DIR_Windows
), GetLastError() );
825 if (!CreateDirectoryW( DIR_System
, NULL
) && GetLastError() != ERROR_ALREADY_EXISTS
)
826 ERR( "directory %s could not be created, error %u\n",
827 debugstr_w(DIR_System
), GetLastError() );
829 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
830 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
832 /* set the directories in ntdll too */
833 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
837 /***********************************************************************
840 * Start the wineboot process if necessary. Return the event to wait on.
842 static HANDLE
start_wineboot(void)
844 static const WCHAR wineboot_eventW
[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
847 if (!(event
= CreateEventW( NULL
, TRUE
, FALSE
, wineboot_eventW
)))
849 ERR( "failed to create wineboot event, expect trouble\n" );
852 if (GetLastError() != ERROR_ALREADY_EXISTS
) /* we created it */
854 static const WCHAR command_line
[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
856 PROCESS_INFORMATION pi
;
857 WCHAR cmdline
[MAX_PATH
+ sizeof(command_line
)/sizeof(WCHAR
)];
859 memset( &si
, 0, sizeof(si
) );
861 si
.dwFlags
= STARTF_USESTDHANDLES
;
864 si
.hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
866 GetSystemDirectoryW( cmdline
, MAX_PATH
);
867 lstrcatW( cmdline
, command_line
);
868 if (CreateProcessW( NULL
, cmdline
, NULL
, NULL
, FALSE
, DETACHED_PROCESS
, NULL
, NULL
, &si
, &pi
))
870 TRACE( "started wineboot pid %04x tid %04x\n", pi
.dwProcessId
, pi
.dwThreadId
);
871 CloseHandle( pi
.hThread
);
872 CloseHandle( pi
.hProcess
);
877 ERR( "failed to start wineboot, err %u\n", GetLastError() );
886 /***********************************************************************
889 * Startup routine of a new process. Runs on the new process stack.
891 static void start_process( void *arg
)
895 PEB
*peb
= NtCurrentTeb()->Peb
;
896 IMAGE_NT_HEADERS
*nt
;
897 LPTHREAD_START_ROUTINE entry
;
899 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
900 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
901 nt
->OptionalHeader
.AddressOfEntryPoint
);
904 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
905 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
907 SetLastError( 0 ); /* clear error code */
908 if (peb
->BeingDebugged
) DbgBreakPoint();
909 ExitThread( entry( peb
) );
911 __EXCEPT(UnhandledExceptionFilter
)
913 TerminateThread( GetCurrentThread(), GetExceptionCode() );
919 /***********************************************************************
922 * Change the process name in the ps output.
924 static void set_process_name( int argc
, char *argv
[] )
926 #ifdef HAVE_SETPROCTITLE
927 setproctitle("-%s", argv
[1]);
932 char *p
, *prctl_name
= argv
[1];
933 char *end
= argv
[argc
-1] + strlen(argv
[argc
-1]) + 1;
936 # define PR_SET_NAME 15
939 if ((p
= strrchr( prctl_name
, '\\' ))) prctl_name
= p
+ 1;
940 if ((p
= strrchr( prctl_name
, '/' ))) prctl_name
= p
+ 1;
942 if (prctl( PR_SET_NAME
, prctl_name
) != -1)
944 offset
= argv
[1] - argv
[0];
945 memmove( argv
[1] - offset
, argv
[1], end
- argv
[1] );
946 memset( end
- offset
, 0, offset
);
947 for (i
= 1; i
< argc
; i
++) argv
[i
-1] = argv
[i
] - offset
;
951 #endif /* HAVE_PRCTL */
954 memmove( argv
, argv
+ 1, argc
* sizeof(argv
[0]) );
959 /***********************************************************************
962 * Wine initialisation: load and start the main exe file.
964 void CDECL
__wine_kernel_init(void)
966 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
967 static const WCHAR dotW
[] = {'.',0};
968 static const WCHAR exeW
[] = {'.','e','x','e',0};
970 WCHAR
*p
, main_exe_name
[MAX_PATH
+1];
971 PEB
*peb
= NtCurrentTeb()->Peb
;
972 RTL_USER_PROCESS_PARAMETERS
*params
= peb
->ProcessParameters
;
973 HANDLE boot_event
= 0;
974 BOOL got_environment
= TRUE
;
976 /* Initialize everything */
980 kernel32_handle
= GetModuleHandleW(kernel32W
);
984 if (!params
->Environment
)
986 /* Copy the parent environment */
987 if (!build_initial_environment( __wine_main_environ
)) exit(1);
989 /* convert old configuration to new format */
990 convert_old_config();
992 got_environment
= set_registry_environment();
993 set_additional_environment();
997 init_current_directory( ¶ms
->CurrentDirectory
);
999 set_process_name( __wine_main_argc
, __wine_main_argv
);
1000 set_library_wargv( __wine_main_argv
);
1002 if (peb
->ProcessParameters
->ImagePathName
.Buffer
)
1004 strcpyW( main_exe_name
, peb
->ProcessParameters
->ImagePathName
.Buffer
);
1008 if (!SearchPathW( NULL
, __wine_main_wargv
[0], exeW
, MAX_PATH
, main_exe_name
, NULL
) &&
1009 !get_builtin_path( __wine_main_wargv
[0], exeW
, main_exe_name
, MAX_PATH
))
1011 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1012 ExitProcess( GetLastError() );
1014 if (!build_command_line( __wine_main_wargv
)) goto error
;
1015 boot_event
= start_wineboot();
1018 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1019 p
= strrchrW( main_exe_name
, '.' );
1020 if (!p
|| strchrW( p
, '/' ) || strchrW( p
, '\\' )) strcatW( main_exe_name
, dotW
);
1022 TRACE( "starting process name=%s argv[0]=%s\n",
1023 debugstr_w(main_exe_name
), debugstr_w(__wine_main_wargv
[0]) );
1025 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1026 MODULE_get_dll_load_path(main_exe_name
) );
1030 if (WaitForSingleObject( boot_event
, 30000 )) ERR( "boot event wait timed out\n" );
1031 CloseHandle( boot_event
);
1032 /* if we didn't find environment section, try again now that wineboot has run */
1033 if (!got_environment
)
1035 set_registry_environment();
1036 set_additional_environment();
1040 if (!(peb
->ImageBaseAddress
= LoadLibraryExW( main_exe_name
, 0, DONT_RESOLVE_DLL_REFERENCES
)))
1043 DWORD error
= GetLastError();
1045 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1046 if (error
== ERROR_BAD_EXE_FORMAT
||
1047 error
== ERROR_INVALID_ADDRESS
||
1048 error
== ERROR_NOT_ENOUGH_MEMORY
)
1050 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name
);
1051 /* if we get back here, it failed */
1054 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, error
, 0, msg
, sizeof(msg
), NULL
);
1055 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name
), msg
);
1056 ExitProcess( error
);
1059 LdrInitializeThunk( 0, 0, 0, 0 );
1060 /* switch to the new stack */
1061 wine_switch_to_stack( start_process
, NULL
, NtCurrentTeb()->Tib
.StackBase
);
1064 ExitProcess( GetLastError() );
1068 /***********************************************************************
1071 * Build an argv array from a command-line.
1072 * 'reserved' is the number of args to reserve before the first one.
1074 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1078 char *arg
,*s
,*d
,*cmdline
;
1079 int in_quotes
,bcount
,len
;
1081 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1082 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, len
))) return NULL
;
1083 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1090 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1093 /* skip the remaining spaces */
1094 while (*s
==' ' || *s
=='\t') {
1101 } else if (*s
=='\\') {
1102 /* '\', count them */
1104 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1106 in_quotes
=!in_quotes
;
1109 /* a regular character */
1114 if (!(argv
= HeapAlloc( GetProcessHeap(), 0, argc
*sizeof(*argv
) + len
)))
1116 HeapFree( GetProcessHeap(), 0, cmdline
);
1120 arg
= d
= s
= (char *)(argv
+ argc
);
1121 memcpy( d
, cmdline
, len
);
1126 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1127 /* Close the argument and copy it */
1131 /* skip the remaining spaces */
1134 } while (*s
==' ' || *s
=='\t');
1136 /* Start with a new argument */
1139 } else if (*s
=='\\') {
1143 } else if (*s
=='"') {
1145 if ((bcount
& 1)==0) {
1146 /* Preceded by an even number of '\', this is half that
1147 * number of '\', plus a '"' which we discard.
1151 in_quotes
=!in_quotes
;
1153 /* Preceded by an odd number of '\', this is half that
1154 * number of '\' followed by a '"'
1162 /* a regular character */
1173 HeapFree( GetProcessHeap(), 0, cmdline
);
1178 /***********************************************************************
1181 * Build the environment of a new child process.
1183 static char **build_envp( const WCHAR
*envW
)
1185 static const char * const unix_vars
[] = { "PATH", "TEMP", "TMP", "HOME" };
1190 int count
= 0, length
;
1193 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1195 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1196 if (!(env
= HeapAlloc( GetProcessHeap(), 0, length
))) return NULL
;
1197 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1199 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1200 if (is_special_env_var( p
)) length
+= 4; /* prefix it with "WINE" */
1202 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1204 if (!(p
= getenv(unix_vars
[i
]))) continue;
1205 length
+= strlen(unix_vars
[i
]) + strlen(p
) + 2;
1209 if ((envp
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(*envp
) + length
)))
1211 char **envptr
= envp
;
1212 char *dst
= (char *)(envp
+ count
);
1214 /* some variables must not be modified, so we get them directly from the unix env */
1215 for (i
= 0; i
< sizeof(unix_vars
)/sizeof(unix_vars
[0]); i
++)
1217 if (!(p
= getenv(unix_vars
[i
]))) continue;
1218 *envptr
++ = strcpy( dst
, unix_vars
[i
] );
1221 dst
+= strlen(dst
) + 1;
1224 /* now put the Windows environment strings */
1225 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1227 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1228 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1229 if (!strncmp( p
, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1230 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1232 *envptr
++ = strcpy( dst
, "WINE" );
1237 *envptr
++ = strcpy( dst
, p
);
1239 dst
+= strlen(dst
) + 1;
1243 HeapFree( GetProcessHeap(), 0, env
);
1248 /***********************************************************************
1251 * Fork and exec a new Unix binary, checking for errors.
1253 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
, const WCHAR
*env
,
1254 const char *newdir
, DWORD flags
, STARTUPINFOW
*startup
)
1256 int fd
[2], stdin_fd
= -1, stdout_fd
= -1;
1258 char **argv
, **envp
;
1260 if (!env
) env
= GetEnvironmentStringsW();
1264 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1267 fcntl( fd
[1], F_SETFD
, 1 ); /* set close on exec */
1269 if (!(flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)))
1271 HANDLE hstdin
, hstdout
;
1273 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1275 hstdin
= startup
->hStdInput
;
1276 hstdout
= startup
->hStdOutput
;
1280 hstdin
= GetStdHandle(STD_INPUT_HANDLE
);
1281 hstdout
= GetStdHandle(STD_OUTPUT_HANDLE
);
1284 if (is_console_handle( hstdin
))
1285 hstdin
= wine_server_ptr_handle( console_handle_unmap( hstdin
));
1286 if (is_console_handle( hstdout
))
1287 hstdout
= wine_server_ptr_handle( console_handle_unmap( hstdout
));
1288 wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1289 wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1292 argv
= build_argv( cmdline
, 0 );
1293 envp
= build_envp( env
);
1295 if (!(pid
= fork())) /* child */
1299 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1302 if (!(pid
= fork()))
1304 int fd
= open( "/dev/null", O_RDWR
);
1306 /* close stdin and stdout */
1314 else if (pid
!= -1) _exit(0); /* parent */
1320 dup2( stdin_fd
, 0 );
1323 if (stdout_fd
!= -1)
1325 dup2( stdout_fd
, 1 );
1330 /* Reset signals that we previously set to SIG_IGN */
1331 signal( SIGPIPE
, SIG_DFL
);
1332 signal( SIGCHLD
, SIG_DFL
);
1334 if (newdir
) chdir(newdir
);
1336 if (argv
&& envp
) execve( filename
, argv
, envp
);
1338 write( fd
[1], &err
, sizeof(err
) );
1341 HeapFree( GetProcessHeap(), 0, argv
);
1342 HeapFree( GetProcessHeap(), 0, envp
);
1343 if (stdin_fd
!= -1) close( stdin_fd
);
1344 if (stdout_fd
!= -1) close( stdout_fd
);
1346 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1351 if (pid
== -1) FILE_SetDosError();
1357 /***********************************************************************
1358 * create_user_params
1360 static RTL_USER_PROCESS_PARAMETERS
*create_user_params( LPCWSTR filename
, LPCWSTR cmdline
,
1361 LPCWSTR cur_dir
, LPWSTR env
, DWORD flags
,
1362 const STARTUPINFOW
*startup
)
1364 RTL_USER_PROCESS_PARAMETERS
*params
;
1365 UNICODE_STRING image_str
, cmdline_str
, curdir_str
, desktop
, title
, runtime
, newdir
;
1367 WCHAR buffer
[MAX_PATH
];
1369 if(!GetLongPathNameW( filename
, buffer
, MAX_PATH
))
1370 lstrcpynW( buffer
, filename
, MAX_PATH
);
1371 if(!GetFullPathNameW( buffer
, MAX_PATH
, buffer
, NULL
))
1372 lstrcpynW( buffer
, filename
, MAX_PATH
);
1373 RtlInitUnicodeString( &image_str
, buffer
);
1375 RtlInitUnicodeString( &cmdline_str
, cmdline
);
1376 newdir
.Buffer
= NULL
;
1379 if (RtlDosPathNameToNtPathName_U( cur_dir
, &newdir
, NULL
, NULL
))
1381 /* skip \??\ prefix */
1382 curdir_str
.Buffer
= newdir
.Buffer
+ 4;
1383 curdir_str
.Length
= newdir
.Length
- 4 * sizeof(WCHAR
);
1384 curdir_str
.MaximumLength
= newdir
.MaximumLength
- 4 * sizeof(WCHAR
);
1386 else cur_dir
= NULL
;
1388 if (startup
->lpDesktop
) RtlInitUnicodeString( &desktop
, startup
->lpDesktop
);
1389 if (startup
->lpTitle
) RtlInitUnicodeString( &title
, startup
->lpTitle
);
1390 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1393 runtime
.MaximumLength
= startup
->cbReserved2
;
1394 runtime
.Buffer
= (WCHAR
*)startup
->lpReserved2
;
1397 status
= RtlCreateProcessParameters( ¶ms
, &image_str
, NULL
,
1398 cur_dir
? &curdir_str
: NULL
,
1400 startup
->lpTitle
? &title
: NULL
,
1401 startup
->lpDesktop
? &desktop
: NULL
,
1403 (startup
->lpReserved2
&& startup
->cbReserved2
) ? &runtime
: NULL
);
1404 RtlFreeUnicodeString( &newdir
);
1405 if (status
!= STATUS_SUCCESS
)
1407 SetLastError( RtlNtStatusToDosError(status
) );
1411 if (flags
& CREATE_NEW_PROCESS_GROUP
) params
->ConsoleFlags
= 1;
1412 if (flags
& CREATE_NEW_CONSOLE
) params
->ConsoleHandle
= (HANDLE
)1; /* FIXME: cf. kernel_main.c */
1414 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1416 params
->hStdInput
= startup
->hStdInput
;
1417 params
->hStdOutput
= startup
->hStdOutput
;
1418 params
->hStdError
= startup
->hStdError
;
1422 params
->hStdInput
= GetStdHandle( STD_INPUT_HANDLE
);
1423 params
->hStdOutput
= GetStdHandle( STD_OUTPUT_HANDLE
);
1424 params
->hStdError
= GetStdHandle( STD_ERROR_HANDLE
);
1426 params
->dwX
= startup
->dwX
;
1427 params
->dwY
= startup
->dwY
;
1428 params
->dwXSize
= startup
->dwXSize
;
1429 params
->dwYSize
= startup
->dwYSize
;
1430 params
->dwXCountChars
= startup
->dwXCountChars
;
1431 params
->dwYCountChars
= startup
->dwYCountChars
;
1432 params
->dwFillAttribute
= startup
->dwFillAttribute
;
1433 params
->dwFlags
= startup
->dwFlags
;
1434 params
->wShowWindow
= startup
->wShowWindow
;
1439 /***********************************************************************
1442 * Create a new process. If hFile is a valid handle we have an exe
1443 * file, otherwise it is a Winelib app.
1445 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1446 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1447 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1448 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1449 void *res_start
, void *res_end
, int exec_only
)
1451 BOOL ret
, success
= FALSE
;
1452 HANDLE process_info
, hstdin
, hstdout
;
1454 char *winedebug
= NULL
;
1456 RTL_USER_PROCESS_PARAMETERS
*params
;
1457 int socketfd
[2], stdin_fd
= -1, stdout_fd
= -1;
1461 if (!env
) RtlAcquirePebLock();
1463 if (!(params
= create_user_params( filename
, cmd_line
, cur_dir
, env
, flags
, startup
)))
1465 if (!env
) RtlReleasePebLock();
1468 env_end
= params
->Environment
;
1471 static const WCHAR WINEDEBUG
[] = {'W','I','N','E','D','E','B','U','G','=',0};
1472 if (!winedebug
&& !strncmpW( env_end
, WINEDEBUG
, sizeof(WINEDEBUG
)/sizeof(WCHAR
) - 1 ))
1474 DWORD len
= WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, NULL
, 0, NULL
, NULL
);
1475 if ((winedebug
= HeapAlloc( GetProcessHeap(), 0, len
)))
1476 WideCharToMultiByte( CP_UNIXCP
, 0, env_end
, -1, winedebug
, len
, NULL
, NULL
);
1478 env_end
+= strlenW(env_end
) + 1;
1482 /* create the socket for the new process */
1484 if (socketpair( PF_UNIX
, SOCK_STREAM
, 0, socketfd
) == -1)
1486 if (!env
) RtlReleasePebLock();
1487 HeapFree( GetProcessHeap(), 0, winedebug
);
1488 RtlDestroyProcessParameters( params
);
1489 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1492 wine_server_send_fd( socketfd
[1] );
1493 close( socketfd
[1] );
1495 /* create the process on the server side */
1497 SERVER_START_REQ( new_process
)
1499 req
->inherit_all
= inherit
;
1500 req
->create_flags
= flags
;
1501 req
->socket_fd
= socketfd
[1];
1502 req
->exe_file
= wine_server_obj_handle( hFile
);
1503 req
->process_access
= PROCESS_ALL_ACCESS
;
1504 req
->process_attr
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1505 req
->thread_access
= THREAD_ALL_ACCESS
;
1506 req
->thread_attr
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
) ? OBJ_INHERIT
: 0;
1507 req
->hstdin
= wine_server_obj_handle( params
->hStdInput
);
1508 req
->hstdout
= wine_server_obj_handle( params
->hStdOutput
);
1509 req
->hstderr
= wine_server_obj_handle( params
->hStdError
);
1511 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1513 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1514 if (is_console_handle(params
->hStdInput
)) req
->hstdin
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1515 if (is_console_handle(params
->hStdOutput
)) req
->hstdout
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1516 if (is_console_handle(params
->hStdError
)) req
->hstderr
= wine_server_obj_handle( INVALID_HANDLE_VALUE
);
1517 hstdin
= hstdout
= 0;
1521 if (is_console_handle(params
->hStdInput
)) req
->hstdin
= console_handle_unmap(params
->hStdInput
);
1522 if (is_console_handle(params
->hStdOutput
)) req
->hstdout
= console_handle_unmap(params
->hStdOutput
);
1523 if (is_console_handle(params
->hStdError
)) req
->hstderr
= console_handle_unmap(params
->hStdError
);
1524 hstdin
= wine_server_ptr_handle( req
->hstdin
);
1525 hstdout
= wine_server_ptr_handle( req
->hstdout
);
1528 wine_server_add_data( req
, params
, params
->Size
);
1529 wine_server_add_data( req
, params
->Environment
, (env_end
-params
->Environment
)*sizeof(WCHAR
) );
1530 if ((ret
= !wine_server_call_err( req
)))
1532 info
->dwProcessId
= (DWORD
)reply
->pid
;
1533 info
->dwThreadId
= (DWORD
)reply
->tid
;
1534 info
->hProcess
= wine_server_ptr_handle( reply
->phandle
);
1535 info
->hThread
= wine_server_ptr_handle( reply
->thandle
);
1537 process_info
= wine_server_ptr_handle( reply
->info
);
1541 if (!env
) RtlReleasePebLock();
1542 RtlDestroyProcessParameters( params
);
1545 close( socketfd
[0] );
1546 HeapFree( GetProcessHeap(), 0, winedebug
);
1550 if (hstdin
) wine_server_handle_to_fd( hstdin
, FILE_READ_DATA
, &stdin_fd
, NULL
);
1551 if (hstdout
) wine_server_handle_to_fd( hstdout
, FILE_WRITE_DATA
, &stdout_fd
, NULL
);
1553 /* create the child process */
1554 argv
= build_argv( cmd_line
, 1 );
1556 if (exec_only
|| !(pid
= fork())) /* child */
1558 char preloader_reserve
[64], socket_env
[64];
1560 if (flags
& (CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
| DETACHED_PROCESS
))
1562 if (!(pid
= fork()))
1564 int fd
= open( "/dev/null", O_RDWR
);
1566 /* close stdin and stdout */
1574 else if (pid
!= -1) _exit(0); /* parent */
1578 if (stdin_fd
!= -1) dup2( stdin_fd
, 0 );
1579 if (stdout_fd
!= -1) dup2( stdout_fd
, 1 );
1582 if (stdin_fd
!= -1) close( stdin_fd
);
1583 if (stdout_fd
!= -1) close( stdout_fd
);
1585 /* Reset signals that we previously set to SIG_IGN */
1586 signal( SIGPIPE
, SIG_DFL
);
1587 signal( SIGCHLD
, SIG_DFL
);
1589 sprintf( socket_env
, "WINESERVERSOCKET=%u", socketfd
[0] );
1590 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx",
1591 (unsigned long)res_start
, (unsigned long)res_end
);
1593 putenv( preloader_reserve
);
1594 putenv( socket_env
);
1595 if (winedebug
) putenv( winedebug
);
1596 if (unixdir
) chdir(unixdir
);
1598 if (argv
) wine_exec_wine_binary( NULL
, argv
, getenv("WINELOADER") );
1602 /* this is the parent */
1604 if (stdin_fd
!= -1) close( stdin_fd
);
1605 if (stdout_fd
!= -1) close( stdout_fd
);
1606 close( socketfd
[0] );
1607 HeapFree( GetProcessHeap(), 0, argv
);
1608 HeapFree( GetProcessHeap(), 0, winedebug
);
1615 /* wait for the new process info to be ready */
1617 WaitForSingleObject( process_info
, INFINITE
);
1618 SERVER_START_REQ( get_new_process_info
)
1620 req
->info
= wine_server_obj_handle( process_info
);
1621 wine_server_call( req
);
1622 success
= reply
->success
;
1623 err
= reply
->exit_code
;
1629 SetLastError( err
? err
: ERROR_INTERNAL_ERROR
);
1632 CloseHandle( process_info
);
1636 CloseHandle( process_info
);
1637 CloseHandle( info
->hProcess
);
1638 CloseHandle( info
->hThread
);
1639 info
->hProcess
= info
->hThread
= 0;
1640 info
->dwProcessId
= info
->dwThreadId
= 0;
1645 /***********************************************************************
1646 * create_vdm_process
1648 * Create a new VDM process for a 16-bit or DOS application.
1650 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
1651 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1652 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1653 LPPROCESS_INFORMATION info
, LPCSTR unixdir
, int exec_only
)
1655 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1658 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
1659 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
1663 SetLastError( ERROR_OUTOFMEMORY
);
1666 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
1667 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
1668 flags
, startup
, info
, unixdir
, NULL
, NULL
, exec_only
);
1669 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
1674 /***********************************************************************
1675 * create_cmd_process
1677 * Create a new cmd shell process for a .BAT file.
1679 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
1680 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1681 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1682 LPPROCESS_INFORMATION info
)
1685 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
1686 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
1687 WCHAR comspec
[MAX_PATH
];
1691 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
1693 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
1694 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
1697 strcpyW( newcmdline
, comspec
);
1698 strcatW( newcmdline
, slashcW
);
1699 strcatW( newcmdline
, cmd_line
);
1700 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
1701 flags
, env
, cur_dir
, startup
, info
);
1702 HeapFree( GetProcessHeap(), 0, newcmdline
);
1707 /*************************************************************************
1710 * Helper for CreateProcess: retrieve the file name to load from the
1711 * app name and command line. Store the file name in buffer, and
1712 * return a possibly modified command line.
1713 * Also returns a handle to the opened file if it's a Windows binary.
1715 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
1716 int buflen
, HANDLE
*handle
)
1718 static const WCHAR quotesW
[] = {'"','%','s','"',0};
1720 WCHAR
*name
, *pos
, *ret
= NULL
;
1724 /* if we have an app name, everything is easy */
1728 /* use the unmodified app name as file name */
1729 lstrcpynW( buffer
, appname
, buflen
);
1730 *handle
= open_exe_file( buffer
);
1731 if (!(ret
= cmdline
) || !cmdline
[0])
1733 /* no command-line, create one */
1734 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
1735 sprintfW( ret
, quotesW
, appname
);
1742 SetLastError( ERROR_INVALID_PARAMETER
);
1746 /* first check for a quoted file name */
1748 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
1750 int len
= p
- cmdline
- 1;
1751 /* extract the quoted portion as file name */
1752 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1753 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
1756 if (find_exe_file( name
, buffer
, buflen
, handle
))
1757 ret
= cmdline
; /* no change necessary */
1761 /* now try the command-line word by word */
1763 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
1771 do *pos
++ = *p
++; while (*p
&& *p
!= ' ' && *p
!= '\t');
1773 if (find_exe_file( name
, buffer
, buflen
, handle
))
1778 if (*p
) got_space
= TRUE
;
1781 if (ret
&& got_space
) /* now build a new command-line with quotes */
1783 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
1785 sprintfW( ret
, quotesW
, name
);
1790 HeapFree( GetProcessHeap(), 0, name
);
1795 /**********************************************************************
1796 * CreateProcessA (KERNEL32.@)
1798 BOOL WINAPI
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1799 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
1800 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
1801 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
1804 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
1805 UNICODE_STRING desktopW
, titleW
;
1808 desktopW
.Buffer
= NULL
;
1809 titleW
.Buffer
= NULL
;
1810 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
1811 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
1812 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
1814 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
1815 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
1817 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
1818 infoW
.lpDesktop
= desktopW
.Buffer
;
1819 infoW
.lpTitle
= titleW
.Buffer
;
1821 if (startup_info
->lpReserved
)
1822 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1823 debugstr_a(startup_info
->lpReserved
));
1825 ret
= CreateProcessW( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
1826 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
1828 HeapFree( GetProcessHeap(), 0, app_nameW
);
1829 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
1830 HeapFree( GetProcessHeap(), 0, cur_dirW
);
1831 RtlFreeUnicodeString( &desktopW
);
1832 RtlFreeUnicodeString( &titleW
);
1837 /**********************************************************************
1838 * CreateProcessW (KERNEL32.@)
1840 BOOL WINAPI
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1841 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
1842 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
1843 LPPROCESS_INFORMATION info
)
1847 char *unixdir
= NULL
;
1848 WCHAR name
[MAX_PATH
];
1849 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
1850 void *res_start
, *res_end
;
1852 /* Process the AppName and/or CmdLine to get module name and path */
1854 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
1856 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
)/sizeof(WCHAR
), &hFile
)))
1858 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
1860 /* Warn if unsupported features are used */
1862 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
1863 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
1864 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
1865 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
1866 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name
), flags
);
1870 if (!(unixdir
= wine_get_unix_file_name( cur_dir
)))
1872 SetLastError(ERROR_DIRECTORY
);
1878 WCHAR buf
[MAX_PATH
];
1879 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
1882 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
1887 while (*p
) p
+= strlen(p
) + 1;
1888 p
++; /* final null */
1889 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
1890 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
1891 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
1892 flags
|= CREATE_UNICODE_ENVIRONMENT
;
1895 info
->hThread
= info
->hProcess
= 0;
1896 info
->dwProcessId
= info
->dwThreadId
= 0;
1898 /* Determine executable type */
1900 if (!hFile
) /* builtin exe */
1902 TRACE( "starting %s as Winelib app\n", debugstr_w(name
) );
1903 retv
= create_process( 0, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1904 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
, FALSE
);
1908 switch( MODULE_GetBinaryType( hFile
, &res_start
, &res_end
))
1911 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name
), res_start
, res_end
);
1912 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1913 inherit
, flags
, startup_info
, info
, unixdir
, res_start
, res_end
, FALSE
);
1918 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
1919 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1920 inherit
, flags
, startup_info
, info
, unixdir
, FALSE
);
1923 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
1924 SetLastError( ERROR_BAD_EXE_FORMAT
);
1926 case BINARY_UNIX_LIB
:
1927 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
1928 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1929 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
, FALSE
);
1931 case BINARY_UNKNOWN
:
1932 /* check for .com or .bat extension */
1933 if ((p
= strrchrW( name
, '.' )))
1935 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
1937 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
1938 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1939 inherit
, flags
, startup_info
, info
, unixdir
, FALSE
);
1942 if (!strcmpiW( p
, batW
) || !strcmpiW( p
, cmdW
) )
1944 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
1945 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1946 inherit
, flags
, startup_info
, info
);
1951 case BINARY_UNIX_EXE
:
1953 /* unknown file, try as unix executable */
1956 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
1958 if ((unix_name
= wine_get_unix_file_name( name
)))
1960 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
, flags
, startup_info
) != -1);
1961 HeapFree( GetProcessHeap(), 0, unix_name
);
1966 CloseHandle( hFile
);
1969 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
1970 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
1971 HeapFree( GetProcessHeap(), 0, unixdir
);
1973 TRACE( "started process pid %04x tid %04x\n", info
->dwProcessId
, info
->dwThreadId
);
1978 /**********************************************************************
1981 static void exec_process( LPCWSTR name
)
1985 void *res_start
, *res_end
;
1986 STARTUPINFOW startup_info
;
1987 PROCESS_INFORMATION info
;
1989 hFile
= open_exe_file( name
);
1990 if (!hFile
|| hFile
== INVALID_HANDLE_VALUE
) return;
1992 memset( &startup_info
, 0, sizeof(startup_info
) );
1993 startup_info
.cb
= sizeof(startup_info
);
1995 /* Determine executable type */
1997 switch( MODULE_GetBinaryType( hFile
, &res_start
, &res_end
))
2000 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name
), res_start
, res_end
);
2001 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2002 FALSE
, 0, &startup_info
, &info
, NULL
, res_start
, res_end
, TRUE
);
2004 case BINARY_UNIX_LIB
:
2005 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
2006 create_process( hFile
, name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2007 FALSE
, 0, &startup_info
, &info
, NULL
, NULL
, NULL
, TRUE
);
2009 case BINARY_UNKNOWN
:
2010 /* check for .com or .pif extension */
2011 if (!(p
= strrchrW( name
, '.' ))) break;
2012 if (strcmpiW( p
, comW
) && strcmpiW( p
, pifW
)) break;
2017 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
2018 create_vdm_process( name
, GetCommandLineW(), NULL
, NULL
, NULL
, NULL
,
2019 FALSE
, 0, &startup_info
, &info
, NULL
, TRUE
);
2024 CloseHandle( hFile
);
2028 /***********************************************************************
2031 * Wrapper to call WaitForInputIdle USER function
2033 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2035 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2037 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2040 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2041 if (ptr
) return ptr( process
, timeout
);
2047 /***********************************************************************
2048 * WinExec (KERNEL32.@)
2050 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2052 PROCESS_INFORMATION info
;
2053 STARTUPINFOA startup
;
2057 memset( &startup
, 0, sizeof(startup
) );
2058 startup
.cb
= sizeof(startup
);
2059 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2060 startup
.wShowWindow
= nCmdShow
;
2062 /* cmdline needs to be writable for CreateProcess */
2063 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2064 strcpy( cmdline
, lpCmdLine
);
2066 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2067 0, NULL
, NULL
, &startup
, &info
))
2069 /* Give 30 seconds to the app to come up */
2070 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2071 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2073 /* Close off the handles */
2074 CloseHandle( info
.hThread
);
2075 CloseHandle( info
.hProcess
);
2077 else if ((ret
= GetLastError()) >= 32)
2079 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2082 HeapFree( GetProcessHeap(), 0, cmdline
);
2087 /**********************************************************************
2088 * LoadModule (KERNEL32.@)
2090 HINSTANCE WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2092 LOADPARMS32
*params
= paramBlock
;
2093 PROCESS_INFORMATION info
;
2094 STARTUPINFOA startup
;
2095 HINSTANCE hInstance
;
2097 char filename
[MAX_PATH
];
2100 if (!name
) return (HINSTANCE
)ERROR_FILE_NOT_FOUND
;
2102 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2103 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2104 return ULongToHandle(GetLastError());
2106 len
= (BYTE
)params
->lpCmdLine
[0];
2107 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2108 return (HINSTANCE
)ERROR_NOT_ENOUGH_MEMORY
;
2110 strcpy( cmdline
, filename
);
2111 p
= cmdline
+ strlen(cmdline
);
2113 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2116 memset( &startup
, 0, sizeof(startup
) );
2117 startup
.cb
= sizeof(startup
);
2118 if (params
->lpCmdShow
)
2120 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2121 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2124 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2125 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2127 /* Give 30 seconds to the app to come up */
2128 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2129 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2130 hInstance
= (HINSTANCE
)33;
2131 /* Close off the handles */
2132 CloseHandle( info
.hThread
);
2133 CloseHandle( info
.hProcess
);
2135 else if ((hInstance
= ULongToHandle(GetLastError())) >= (HINSTANCE
)32)
2137 FIXME("Strange error set by CreateProcess: %p\n", hInstance
);
2138 hInstance
= (HINSTANCE
)11;
2141 HeapFree( GetProcessHeap(), 0, cmdline
);
2146 /******************************************************************************
2147 * TerminateProcess (KERNEL32.@)
2149 * Terminates a process.
2152 * handle [I] Process to terminate.
2153 * exit_code [I] Exit code.
2157 * Failure: FALSE, check GetLastError().
2159 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2161 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2162 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2166 /***********************************************************************
2167 * ExitProcess (KERNEL32.@)
2169 * Exits the current process.
2172 * status [I] Status code to exit with.
2178 __ASM_GLOBAL_FUNC( ExitProcess
, /* Shrinker depend on this particular ExitProcess implementation */
2180 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2181 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2182 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2184 "call " __ASM_NAME("process_ExitProcess") "\n\t"
2188 void WINAPI
process_ExitProcess( DWORD status
)
2190 LdrShutdownProcess();
2191 NtTerminateProcess(GetCurrentProcess(), status
);
2197 void WINAPI
ExitProcess( DWORD status
)
2199 LdrShutdownProcess();
2200 NtTerminateProcess(GetCurrentProcess(), status
);
2206 /***********************************************************************
2207 * GetExitCodeProcess [KERNEL32.@]
2209 * Gets termination status of specified process.
2212 * hProcess [in] Handle to the process.
2213 * lpExitCode [out] Address to receive termination status.
2219 BOOL WINAPI
GetExitCodeProcess( HANDLE hProcess
, LPDWORD lpExitCode
)
2222 PROCESS_BASIC_INFORMATION pbi
;
2224 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2226 if (status
== STATUS_SUCCESS
)
2228 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2231 SetLastError( RtlNtStatusToDosError(status
) );
2236 /***********************************************************************
2237 * SetErrorMode (KERNEL32.@)
2239 UINT WINAPI
SetErrorMode( UINT mode
)
2241 UINT old
= process_error_mode
;
2242 process_error_mode
= mode
;
2247 /**********************************************************************
2248 * TlsAlloc [KERNEL32.@]
2250 * Allocates a thread local storage index.
2253 * Success: TLS index.
2254 * Failure: 0xFFFFFFFF
2256 DWORD WINAPI
TlsAlloc( void )
2259 PEB
* const peb
= NtCurrentTeb()->Peb
;
2261 RtlAcquirePebLock();
2262 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 0 );
2263 if (index
!= ~0U) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2266 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2269 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2270 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2271 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2273 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2275 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2279 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2280 index
+= TLS_MINIMUM_AVAILABLE
;
2283 else SetLastError( ERROR_NO_MORE_ITEMS
);
2285 RtlReleasePebLock();
2290 /**********************************************************************
2291 * TlsFree [KERNEL32.@]
2293 * Releases a thread local storage index, making it available for reuse.
2296 * index [in] TLS index to free.
2302 BOOL WINAPI
TlsFree( DWORD index
)
2306 RtlAcquirePebLock();
2307 if (index
>= TLS_MINIMUM_AVAILABLE
)
2309 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2310 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2314 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2315 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2317 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2318 else SetLastError( ERROR_INVALID_PARAMETER
);
2319 RtlReleasePebLock();
2324 /**********************************************************************
2325 * TlsGetValue [KERNEL32.@]
2327 * Gets value in a thread's TLS slot.
2330 * index [in] TLS index to retrieve value for.
2333 * Success: Value stored in calling thread's TLS slot for index.
2334 * Failure: 0 and GetLastError() returns NO_ERROR.
2336 LPVOID WINAPI
TlsGetValue( DWORD index
)
2340 if (index
< TLS_MINIMUM_AVAILABLE
)
2342 ret
= NtCurrentTeb()->TlsSlots
[index
];
2346 index
-= TLS_MINIMUM_AVAILABLE
;
2347 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2349 SetLastError( ERROR_INVALID_PARAMETER
);
2352 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2353 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2355 SetLastError( ERROR_SUCCESS
);
2360 /**********************************************************************
2361 * TlsSetValue [KERNEL32.@]
2363 * Stores a value in the thread's TLS slot.
2366 * index [in] TLS index to set value for.
2367 * value [in] Value to be stored.
2373 BOOL WINAPI
TlsSetValue( DWORD index
, LPVOID value
)
2375 if (index
< TLS_MINIMUM_AVAILABLE
)
2377 NtCurrentTeb()->TlsSlots
[index
] = value
;
2381 index
-= TLS_MINIMUM_AVAILABLE
;
2382 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2384 SetLastError( ERROR_INVALID_PARAMETER
);
2387 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2388 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2389 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2391 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2394 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2400 /***********************************************************************
2401 * GetProcessFlags (KERNEL32.@)
2403 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2405 IMAGE_NT_HEADERS
*nt
;
2408 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2410 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2412 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2413 flags
|= PDB32_CONSOLE_PROC
;
2415 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2416 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2421 /***********************************************************************
2422 * GetProcessDword (KERNEL.485)
2423 * GetProcessDword (KERNEL32.18)
2424 * 'Of course you cannot directly access Windows internal structures'
2426 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
2431 TRACE("(%d, %d)\n", dwProcessID
, offset
);
2433 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2435 ERR("%d: process %x not accessible\n", offset
, dwProcessID
);
2441 case GPD_APP_COMPAT_FLAGS
:
2442 return GetAppCompatFlags16(0);
2443 case GPD_LOAD_DONE_EVENT
:
2445 case GPD_HINSTANCE16
:
2446 return GetTaskDS16();
2447 case GPD_WINDOWS_VERSION
:
2448 return GetExeVersion16();
2450 return (DWORD_PTR
)NtCurrentTeb() - 0x10 /* FIXME */;
2452 return (DWORD_PTR
)NtCurrentTeb()->Peb
; /* FIXME: truncating a pointer */
2453 case GPD_STARTF_SHELLDATA
: /* return stdoutput handle from startupinfo ??? */
2454 GetStartupInfoW(&siw
);
2455 return HandleToULong(siw
.hStdOutput
);
2456 case GPD_STARTF_HOTKEY
: /* return stdinput handle from startupinfo ??? */
2457 GetStartupInfoW(&siw
);
2458 return HandleToULong(siw
.hStdInput
);
2459 case GPD_STARTF_SHOWWINDOW
:
2460 GetStartupInfoW(&siw
);
2461 return siw
.wShowWindow
;
2462 case GPD_STARTF_SIZE
:
2463 GetStartupInfoW(&siw
);
2465 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2467 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2468 return MAKELONG( x
, y
);
2469 case GPD_STARTF_POSITION
:
2470 GetStartupInfoW(&siw
);
2472 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2474 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2475 return MAKELONG( x
, y
);
2476 case GPD_STARTF_FLAGS
:
2477 GetStartupInfoW(&siw
);
2482 return GetProcessFlags(0);
2484 return process_dword
;
2486 ERR("Unknown offset %d\n", offset
);
2491 /***********************************************************************
2492 * SetProcessDword (KERNEL.484)
2493 * 'Of course you cannot directly access Windows internal structures'
2495 void WINAPI
SetProcessDword( DWORD dwProcessID
, INT offset
, DWORD value
)
2497 TRACE("(%d, %d)\n", dwProcessID
, offset
);
2499 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2501 ERR("%d: process %x not accessible\n", offset
, dwProcessID
);
2507 case GPD_APP_COMPAT_FLAGS
:
2508 case GPD_LOAD_DONE_EVENT
:
2509 case GPD_HINSTANCE16
:
2510 case GPD_WINDOWS_VERSION
:
2513 case GPD_STARTF_SHELLDATA
:
2514 case GPD_STARTF_HOTKEY
:
2515 case GPD_STARTF_SHOWWINDOW
:
2516 case GPD_STARTF_SIZE
:
2517 case GPD_STARTF_POSITION
:
2518 case GPD_STARTF_FLAGS
:
2521 ERR("Not allowed to modify offset %d\n", offset
);
2524 process_dword
= value
;
2527 ERR("Unknown offset %d\n", offset
);
2533 /***********************************************************************
2534 * ExitProcess (KERNEL.466)
2536 void WINAPI
ExitProcess16( WORD status
)
2539 ReleaseThunkLock( &count
);
2540 ExitProcess( status
);
2544 /*********************************************************************
2545 * OpenProcess (KERNEL32.@)
2547 * Opens a handle to a process.
2550 * access [I] Desired access rights assigned to the returned handle.
2551 * inherit [I] Determines whether or not child processes will inherit the handle.
2552 * id [I] Process identifier of the process to get a handle to.
2555 * Success: Valid handle to the specified process.
2556 * Failure: NULL, check GetLastError().
2558 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2562 OBJECT_ATTRIBUTES attr
;
2565 cid
.UniqueProcess
= ULongToHandle(id
);
2566 cid
.UniqueThread
= 0; /* FIXME ? */
2568 attr
.Length
= sizeof(OBJECT_ATTRIBUTES
);
2569 attr
.RootDirectory
= NULL
;
2570 attr
.Attributes
= inherit
? OBJ_INHERIT
: 0;
2571 attr
.SecurityDescriptor
= NULL
;
2572 attr
.SecurityQualityOfService
= NULL
;
2573 attr
.ObjectName
= NULL
;
2575 if (GetVersion() & 0x80000000) access
= PROCESS_ALL_ACCESS
;
2577 status
= NtOpenProcess(&handle
, access
, &attr
, &cid
);
2578 if (status
!= STATUS_SUCCESS
)
2580 SetLastError( RtlNtStatusToDosError(status
) );
2587 /*********************************************************************
2588 * MapProcessHandle (KERNEL.483)
2589 * GetProcessId (KERNEL32.@)
2591 * Gets the a unique identifier of a process.
2594 * hProcess [I] Handle to the process.
2598 * Failure: FALSE, check GetLastError().
2602 * The identifier is unique only on the machine and only until the process
2603 * exits (including system shutdown).
2605 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2608 PROCESS_BASIC_INFORMATION pbi
;
2610 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2612 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2613 SetLastError( RtlNtStatusToDosError(status
) );
2618 /*********************************************************************
2619 * CloseW32Handle (KERNEL.474)
2620 * CloseHandle (KERNEL32.@)
2625 * handle [I] Handle to close.
2629 * Failure: FALSE, check GetLastError().
2631 BOOL WINAPI
CloseHandle( HANDLE handle
)
2635 /* stdio handles need special treatment */
2636 if ((handle
== (HANDLE
)STD_INPUT_HANDLE
) ||
2637 (handle
== (HANDLE
)STD_OUTPUT_HANDLE
) ||
2638 (handle
== (HANDLE
)STD_ERROR_HANDLE
))
2639 handle
= GetStdHandle( HandleToULong(handle
) );
2641 if (is_console_handle(handle
))
2642 return CloseConsoleHandle(handle
);
2644 status
= NtClose( handle
);
2645 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2650 /*********************************************************************
2651 * GetHandleInformation (KERNEL32.@)
2653 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2655 OBJECT_DATA_INFORMATION info
;
2656 NTSTATUS status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
);
2658 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2662 if (info
.InheritHandle
) *flags
|= HANDLE_FLAG_INHERIT
;
2663 if (info
.ProtectFromClose
) *flags
|= HANDLE_FLAG_PROTECT_FROM_CLOSE
;
2669 /*********************************************************************
2670 * SetHandleInformation (KERNEL32.@)
2672 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2674 OBJECT_DATA_INFORMATION info
;
2677 /* if not setting both fields, retrieve current value first */
2678 if ((mask
& (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
)) !=
2679 (HANDLE_FLAG_INHERIT
| HANDLE_FLAG_PROTECT_FROM_CLOSE
))
2681 if ((status
= NtQueryObject( handle
, ObjectDataInformation
, &info
, sizeof(info
), NULL
)))
2683 SetLastError( RtlNtStatusToDosError(status
) );
2687 if (mask
& HANDLE_FLAG_INHERIT
)
2688 info
.InheritHandle
= (flags
& HANDLE_FLAG_INHERIT
) != 0;
2689 if (mask
& HANDLE_FLAG_PROTECT_FROM_CLOSE
)
2690 info
.ProtectFromClose
= (flags
& HANDLE_FLAG_PROTECT_FROM_CLOSE
) != 0;
2692 status
= NtSetInformationObject( handle
, ObjectDataInformation
, &info
, sizeof(info
) );
2693 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2698 /*********************************************************************
2699 * DuplicateHandle (KERNEL32.@)
2701 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2702 HANDLE dest_process
, HANDLE
*dest
,
2703 DWORD access
, BOOL inherit
, DWORD options
)
2707 if (is_console_handle(source
))
2709 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2710 if (source_process
!= dest_process
||
2711 source_process
!= GetCurrentProcess())
2713 SetLastError(ERROR_INVALID_PARAMETER
);
2716 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2717 return (*dest
!= INVALID_HANDLE_VALUE
);
2719 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2720 access
, inherit
? OBJ_INHERIT
: 0, options
);
2721 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2726 /***********************************************************************
2727 * ConvertToGlobalHandle (KERNEL.476)
2728 * ConvertToGlobalHandle (KERNEL32.@)
2730 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
2732 HANDLE ret
= INVALID_HANDLE_VALUE
;
2733 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
2734 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
2739 /***********************************************************************
2740 * SetHandleContext (KERNEL32.@)
2742 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
2744 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2745 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
2746 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2751 /***********************************************************************
2752 * GetHandleContext (KERNEL32.@)
2754 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
2756 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2757 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
2758 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2763 /***********************************************************************
2764 * CreateSocketHandle (KERNEL32.@)
2766 HANDLE WINAPI
CreateSocketHandle(void)
2768 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2769 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2770 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2771 return INVALID_HANDLE_VALUE
;
2775 /***********************************************************************
2776 * SetPriorityClass (KERNEL32.@)
2778 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
2781 PROCESS_PRIORITY_CLASS ppc
;
2783 ppc
.Foreground
= FALSE
;
2784 switch (priorityclass
)
2786 case IDLE_PRIORITY_CLASS
:
2787 ppc
.PriorityClass
= PROCESS_PRIOCLASS_IDLE
; break;
2788 case BELOW_NORMAL_PRIORITY_CLASS
:
2789 ppc
.PriorityClass
= PROCESS_PRIOCLASS_BELOW_NORMAL
; break;
2790 case NORMAL_PRIORITY_CLASS
:
2791 ppc
.PriorityClass
= PROCESS_PRIOCLASS_NORMAL
; break;
2792 case ABOVE_NORMAL_PRIORITY_CLASS
:
2793 ppc
.PriorityClass
= PROCESS_PRIOCLASS_ABOVE_NORMAL
; break;
2794 case HIGH_PRIORITY_CLASS
:
2795 ppc
.PriorityClass
= PROCESS_PRIOCLASS_HIGH
; break;
2796 case REALTIME_PRIORITY_CLASS
:
2797 ppc
.PriorityClass
= PROCESS_PRIOCLASS_REALTIME
; break;
2799 SetLastError(ERROR_INVALID_PARAMETER
);
2803 status
= NtSetInformationProcess(hprocess
, ProcessPriorityClass
,
2806 if (status
!= STATUS_SUCCESS
)
2808 SetLastError( RtlNtStatusToDosError(status
) );
2815 /***********************************************************************
2816 * GetPriorityClass (KERNEL32.@)
2818 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
2821 PROCESS_BASIC_INFORMATION pbi
;
2823 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2825 if (status
!= STATUS_SUCCESS
)
2827 SetLastError( RtlNtStatusToDosError(status
) );
2830 switch (pbi
.BasePriority
)
2832 case PROCESS_PRIOCLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
2833 case PROCESS_PRIOCLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
2834 case PROCESS_PRIOCLASS_NORMAL
: return NORMAL_PRIORITY_CLASS
;
2835 case PROCESS_PRIOCLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
2836 case PROCESS_PRIOCLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
2837 case PROCESS_PRIOCLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
2839 SetLastError( ERROR_INVALID_PARAMETER
);
2844 /***********************************************************************
2845 * SetProcessAffinityMask (KERNEL32.@)
2847 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
2851 status
= NtSetInformationProcess(hProcess
, ProcessAffinityMask
,
2852 &affmask
, sizeof(DWORD_PTR
));
2855 SetLastError( RtlNtStatusToDosError(status
) );
2862 /**********************************************************************
2863 * GetProcessAffinityMask (KERNEL32.@)
2865 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
2866 PDWORD_PTR lpProcessAffinityMask
,
2867 PDWORD_PTR lpSystemAffinityMask
)
2869 PROCESS_BASIC_INFORMATION pbi
;
2872 status
= NtQueryInformationProcess(hProcess
,
2873 ProcessBasicInformation
,
2874 &pbi
, sizeof(pbi
), NULL
);
2877 SetLastError( RtlNtStatusToDosError(status
) );
2880 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= pbi
.AffinityMask
;
2881 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= (1 << NtCurrentTeb()->Peb
->NumberOfProcessors
) - 1;
2886 /***********************************************************************
2887 * GetProcessVersion (KERNEL32.@)
2889 DWORD WINAPI
GetProcessVersion( DWORD pid
)
2893 PROCESS_BASIC_INFORMATION pbi
;
2896 IMAGE_DOS_HEADER dos
;
2897 IMAGE_NT_HEADERS nt
;
2900 if (!pid
|| pid
== GetCurrentProcessId())
2902 IMAGE_NT_HEADERS
*nt
;
2904 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2905 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
2906 nt
->OptionalHeader
.MinorSubsystemVersion
);
2910 process
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
, FALSE
, pid
);
2911 if (!process
) return 0;
2913 status
= NtQueryInformationProcess(process
, ProcessBasicInformation
, &pbi
, sizeof(pbi
), NULL
);
2914 if (status
) goto err
;
2916 status
= NtReadVirtualMemory(process
, pbi
.PebBaseAddress
, &peb
, sizeof(peb
), &count
);
2917 if (status
|| count
!= sizeof(peb
)) goto err
;
2919 memset(&dos
, 0, sizeof(dos
));
2920 status
= NtReadVirtualMemory(process
, peb
.ImageBaseAddress
, &dos
, sizeof(dos
), &count
);
2921 if (status
|| count
!= sizeof(dos
)) goto err
;
2922 if (dos
.e_magic
!= IMAGE_DOS_SIGNATURE
) goto err
;
2924 memset(&nt
, 0, sizeof(nt
));
2925 status
= NtReadVirtualMemory(process
, (char *)peb
.ImageBaseAddress
+ dos
.e_lfanew
, &nt
, sizeof(nt
), &count
);
2926 if (status
|| count
!= sizeof(nt
)) goto err
;
2927 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) goto err
;
2929 ver
= MAKELONG(nt
.OptionalHeader
.MinorSubsystemVersion
, nt
.OptionalHeader
.MajorSubsystemVersion
);
2932 CloseHandle(process
);
2934 if (status
!= STATUS_SUCCESS
)
2935 SetLastError(RtlNtStatusToDosError(status
));
2941 /***********************************************************************
2942 * SetProcessWorkingSetSize [KERNEL32.@]
2943 * Sets the min/max working set sizes for a specified process.
2946 * hProcess [I] Handle to the process of interest
2947 * minset [I] Specifies minimum working set size
2948 * maxset [I] Specifies maximum working set size
2954 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
2957 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
2958 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
2959 /* Trim the working set to zero */
2960 /* Swap the process out of physical RAM */
2965 /***********************************************************************
2966 * GetProcessWorkingSetSize (KERNEL32.@)
2968 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
2971 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
2972 /* 32 MB working set size */
2973 if (minset
) *minset
= 32*1024*1024;
2974 if (maxset
) *maxset
= 32*1024*1024;
2979 /***********************************************************************
2980 * SetProcessShutdownParameters (KERNEL32.@)
2982 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
2984 FIXME("(%08x, %08x): partial stub.\n", level
, flags
);
2985 shutdown_flags
= flags
;
2986 shutdown_priority
= level
;
2991 /***********************************************************************
2992 * GetProcessShutdownParameters (KERNEL32.@)
2995 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
2997 *lpdwLevel
= shutdown_priority
;
2998 *lpdwFlags
= shutdown_flags
;
3003 /***********************************************************************
3004 * GetProcessPriorityBoost (KERNEL32.@)
3006 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
3008 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
3010 /* Report that no boost is present.. */
3011 *pDisablePriorityBoost
= FALSE
;
3016 /***********************************************************************
3017 * SetProcessPriorityBoost (KERNEL32.@)
3019 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
3021 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
3022 /* Say we can do it. I doubt the program will notice that we don't. */
3027 /***********************************************************************
3028 * ReadProcessMemory (KERNEL32.@)
3030 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
3031 SIZE_T
*bytes_read
)
3033 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
3034 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3039 /***********************************************************************
3040 * WriteProcessMemory (KERNEL32.@)
3042 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
3043 SIZE_T
*bytes_written
)
3045 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
3046 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3051 /****************************************************************************
3052 * FlushInstructionCache (KERNEL32.@)
3054 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
3057 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
3058 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3063 /******************************************************************
3064 * GetProcessIoCounters (KERNEL32.@)
3066 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
3070 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
3071 ioc
, sizeof(*ioc
), NULL
);
3072 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3076 /******************************************************************
3077 * GetProcessHandleCount (KERNEL32.@)
3079 BOOL WINAPI
GetProcessHandleCount(HANDLE hProcess
, DWORD
*cnt
)
3083 status
= NtQueryInformationProcess(hProcess
, ProcessHandleCount
,
3084 cnt
, sizeof(*cnt
), NULL
);
3085 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
3089 /***********************************************************************
3090 * ProcessIdToSessionId (KERNEL32.@)
3091 * This function is available on Terminal Server 4SP4 and Windows 2000
3093 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
3095 /* According to MSDN, if the calling process is not in a terminal
3096 * services environment, then the sessionid returned is zero.
3103 /***********************************************************************
3104 * RegisterServiceProcess (KERNEL.491)
3105 * RegisterServiceProcess (KERNEL32.@)
3107 * A service process calls this function to ensure that it continues to run
3108 * even after a user logged off.
3110 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
3112 /* I don't think that Wine needs to do anything in this function */
3113 return 1; /* success */
3117 /**********************************************************************
3118 * IsWow64Process (KERNEL32.@)
3120 BOOL WINAPI
IsWow64Process(HANDLE hProcess
, PBOOL Wow64Process
)
3125 status
= NtQueryInformationProcess( hProcess
, ProcessWow64Information
, &pbi
, sizeof(pbi
), NULL
);
3127 if (status
!= STATUS_SUCCESS
)
3129 SetLastError( RtlNtStatusToDosError( status
) );
3132 *Wow64Process
= (pbi
!= 0);
3137 /***********************************************************************
3138 * GetCurrentProcess (KERNEL32.@)
3140 * Get a handle to the current process.
3146 * A handle representing the current process.
3148 #undef GetCurrentProcess
3149 HANDLE WINAPI
GetCurrentProcess(void)
3151 return (HANDLE
)~(ULONG_PTR
)0;
3154 /***********************************************************************
3155 * CmdBatNotification (KERNEL32.@)
3157 * Notifies the system that a batch file has started or finished.
3160 * bBatchRunning [I] TRUE if a batch file has started or
3161 * FALSE if a batch file has finished executing.
3166 BOOL WINAPI
CmdBatNotification( BOOL bBatchRunning
)
3168 FIXME("%d\n", bBatchRunning
);
3173 /***********************************************************************
3174 * RegisterApplicationRestart (KERNEL32.@)
3176 HRESULT WINAPI
RegisterApplicationRestart(PCWSTR pwzCommandLine
, DWORD dwFlags
)
3178 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine
), dwFlags
);