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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
34 #include <sys/types.h>
36 #include "wine/winbase16.h"
37 #include "wine/winuser16.h"
42 #include "kernel_private.h"
43 #include "wine/exception.h"
44 #include "wine/server.h"
45 #include "wine/unicode.h"
46 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(process
);
49 WINE_DECLARE_DEBUG_CHANNEL(file
);
50 WINE_DECLARE_DEBUG_CHANNEL(server
);
51 WINE_DECLARE_DEBUG_CHANNEL(relay
);
61 static UINT process_error_mode
;
63 static HANDLE main_exe_file
;
64 static DWORD shutdown_flags
= 0;
65 static DWORD shutdown_priority
= 0x280;
66 static DWORD process_dword
;
68 static unsigned int server_startticks
;
69 int main_create_flags
= 0;
70 HMODULE kernel32_handle
= 0;
72 const WCHAR
*DIR_Windows
= NULL
;
73 const WCHAR
*DIR_System
= NULL
;
76 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
77 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
78 #define PDB32_DOS_PROC 0x0010 /* Dos process */
79 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
80 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
81 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
83 static const WCHAR comW
[] = {'.','c','o','m',0};
84 static const WCHAR batW
[] = {'.','b','a','t',0};
85 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
87 extern void SHELL_LoadRegistry(void);
88 extern void VOLUME_CreateDevices(void);
89 extern void VERSION_Init( const WCHAR
*appname
);
90 extern void LOCALE_Init(void);
92 /***********************************************************************
95 inline static int contains_path( LPCWSTR name
)
97 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
101 /***********************************************************************
104 * Check if an environment variable needs to be handled specially when
105 * passed through the Unix environment (i.e. prefixed with "WINE").
107 inline static int is_special_env_var( const char *var
)
109 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
110 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
111 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
112 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
116 /***************************************************************************
119 * Get the path of a builtin module when the native file does not exist.
121 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
, UINT size
)
124 UINT len
= strlenW( DIR_System
);
126 if (contains_path( libname
))
128 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
129 filename
, &file_part
) > size
* sizeof(WCHAR
))
130 return FALSE
; /* too long */
132 if (strncmpiW( filename
, DIR_System
, len
) || filename
[len
] != '\\')
134 while (filename
[len
] == '\\') len
++;
135 if (filename
+ len
!= file_part
) return FALSE
;
139 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
140 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
141 file_part
= filename
+ len
;
142 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
143 strcpyW( file_part
, libname
);
145 if (ext
&& !strchrW( file_part
, '.' ))
147 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
148 return FALSE
; /* too long */
149 strcatW( file_part
, ext
);
155 /***********************************************************************
156 * open_builtin_exe_file
158 * Open an exe file for a builtin exe.
160 static void *open_builtin_exe_file( const WCHAR
*name
, char *error
, int error_size
,
161 int test_only
, int *file_exists
)
163 char exename
[MAX_PATH
];
167 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
168 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
170 /* we don't want to depend on the current codepage here */
171 len
= strlenW( name
) + 1;
172 if (len
>= sizeof(exename
)) return NULL
;
173 for (i
= 0; i
< len
; i
++)
175 if (name
[i
] > 127) return NULL
;
176 exename
[i
] = (char)name
[i
];
177 if (exename
[i
] >= 'A' && exename
[i
] <= 'Z') exename
[i
] += 'a' - 'A';
179 return wine_dll_load_main_exe( exename
, error
, error_size
, test_only
, file_exists
);
183 /***********************************************************************
186 * Open a specific exe file, taking load order into account.
187 * Returns the file handle or 0 for a builtin exe.
189 static HANDLE
open_exe_file( const WCHAR
*name
)
191 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
192 WCHAR buffer
[MAX_PATH
];
196 TRACE("looking for %s\n", debugstr_w(name
) );
198 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
199 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
201 /* file doesn't exist, check for builtin */
202 if (!contains_path( name
)) goto error
;
203 if (!get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
) )) goto error
;
207 MODULE_GetLoadOrderW( loadorder
, NULL
, name
);
209 for(i
= 0; i
< LOADORDER_NTYPES
; i
++)
211 if (loadorder
[i
] == LOADORDER_INVALID
) break;
215 TRACE( "Trying native exe %s\n", debugstr_w(name
) );
216 if (handle
!= INVALID_HANDLE_VALUE
) return handle
;
219 TRACE( "Trying built-in exe %s\n", debugstr_w(name
) );
220 open_builtin_exe_file( name
, NULL
, 0, 1, &file_exists
);
223 if (handle
!= INVALID_HANDLE_VALUE
) CloseHandle(handle
);
230 if (handle
!= INVALID_HANDLE_VALUE
) CloseHandle(handle
);
233 SetLastError( ERROR_FILE_NOT_FOUND
);
234 return INVALID_HANDLE_VALUE
;
238 /***********************************************************************
241 * Open an exe file, and return the full name and file handle.
242 * Returns FALSE if file could not be found.
243 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
244 * If file is a builtin exe, returns TRUE and sets handle to 0.
246 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
, HANDLE
*handle
)
248 static const WCHAR exeW
[] = {'.','e','x','e',0};
250 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
253 TRACE("looking for %s\n", debugstr_w(name
) );
255 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
) &&
256 !get_builtin_path( name
, exeW
, buffer
, buflen
))
258 /* no builtin found, try native without extension in case it is a Unix app */
260 if (SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
))
262 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer
) );
263 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
264 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
270 MODULE_GetLoadOrderW( loadorder
, NULL
, buffer
);
272 for(i
= 0; i
< LOADORDER_NTYPES
; i
++)
274 if (loadorder
[i
] == LOADORDER_INVALID
) break;
278 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
279 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
280 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
282 if (GetLastError() != ERROR_FILE_NOT_FOUND
) return TRUE
;
285 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer
) );
286 open_builtin_exe_file( buffer
, NULL
, 0, 1, &file_exists
);
297 SetLastError( ERROR_FILE_NOT_FOUND
);
302 /**********************************************************************
305 * Load a PE format EXE file.
307 static HMODULE
load_pe_exe( const WCHAR
*name
, HANDLE file
)
310 FILE_FS_DEVICE_INFORMATION device_info
;
311 IMAGE_NT_HEADERS
*nt
;
314 OBJECT_ATTRIBUTES attr
;
318 attr
.Length
= sizeof(attr
);
319 attr
.RootDirectory
= 0;
320 attr
.ObjectName
= NULL
;
322 attr
.SecurityDescriptor
= NULL
;
323 attr
.SecurityQualityOfService
= NULL
;
326 if (NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
327 &attr
, &size
, 0, SEC_IMAGE
, file
) != STATUS_SUCCESS
)
331 if (NtMapViewOfSection( mapping
, GetCurrentProcess(), &module
, 0, 0, &size
, &len
,
332 ViewShare
, 0, PAGE_READONLY
) != STATUS_SUCCESS
)
338 nt
= RtlImageNtHeader( module
);
339 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
341 if (!RtlImageRvaToSection( nt
, module
, nt
->OptionalHeader
.AddressOfEntryPoint
))
342 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
343 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
344 debugstr_w(name
), nt
->OptionalHeader
.AddressOfEntryPoint
);
347 if (NtQueryVolumeInformationFile( file
, &io
, &device_info
, sizeof(device_info
),
348 FileFsDeviceInformation
) == STATUS_SUCCESS
)
350 /* don't keep the file handle open on removable media */
351 if (device_info
.Characteristics
& FILE_REMOVABLE_MEDIA
)
353 CloseHandle( main_exe_file
);
361 /***********************************************************************
362 * build_initial_environment
364 * Build the Win32 environment from the Unix environment
366 static BOOL
build_initial_environment( char **environ
)
373 /* Compute the total size of the Unix environment */
374 for (e
= environ
; *e
; e
++)
376 if (is_special_env_var( *e
)) continue;
377 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
379 size
*= sizeof(WCHAR
);
381 /* Now allocate the environment */
383 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
384 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
387 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
388 endptr
= p
+ size
/ sizeof(WCHAR
);
390 /* And fill it with the Unix environment */
391 for (e
= environ
; *e
; e
++)
395 /* skip Unix special variables and use the Wine variants instead */
396 if (!strncmp( str
, "WINE", 4 ))
398 if (is_special_env_var( str
+ 4 )) str
+= 4;
399 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
401 else if (is_special_env_var( str
)) continue; /* skip it */
403 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
411 /***********************************************************************
412 * set_registry_variables
414 * Set environment variables by enumerating the values of a key;
415 * helper for set_registry_environment().
416 * Note that Windows happily truncates the value if it's too big.
418 static void set_registry_variables( HKEY hkey
, ULONG type
)
420 UNICODE_STRING env_name
, env_value
;
424 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
425 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
427 for (index
= 0; ; index
++)
429 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
430 buffer
, sizeof(buffer
), &size
);
431 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
433 if (info
->Type
!= type
)
435 env_name
.Buffer
= info
->Name
;
436 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
437 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
438 env_value
.Length
= env_value
.MaximumLength
= info
->DataLength
;
439 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
440 env_value
.Length
--; /* don't count terminating null if any */
441 if (info
->Type
== REG_EXPAND_SZ
)
443 WCHAR buf_expanded
[1024];
444 UNICODE_STRING env_expanded
;
445 env_expanded
.Length
= env_expanded
.MaximumLength
= sizeof(buf_expanded
);
446 env_expanded
.Buffer
=buf_expanded
;
447 status
= RtlExpandEnvironmentStrings_U(NULL
, &env_value
, &env_expanded
, NULL
);
448 if (status
== STATUS_SUCCESS
|| status
== STATUS_BUFFER_OVERFLOW
)
449 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_expanded
);
453 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
459 /***********************************************************************
460 * set_registry_environment
462 * Set the environment variables specified in the registry.
464 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
465 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
466 * on the order in which the variables are processed. But on Windows it
467 * does not really matter since they only use %SystemDrive% and
468 * %SystemRoot% which are predefined. But Wine defines these in the
469 * registry, so we need two passes.
471 static void set_registry_environment(void)
473 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
474 'S','y','s','t','e','m','\\',
475 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
476 'C','o','n','t','r','o','l','\\',
477 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
478 'E','n','v','i','r','o','n','m','e','n','t',0};
479 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
481 OBJECT_ATTRIBUTES attr
;
482 UNICODE_STRING nameW
;
485 attr
.Length
= sizeof(attr
);
486 attr
.RootDirectory
= 0;
487 attr
.ObjectName
= &nameW
;
489 attr
.SecurityDescriptor
= NULL
;
490 attr
.SecurityQualityOfService
= NULL
;
492 /* first the system environment variables */
493 RtlInitUnicodeString( &nameW
, env_keyW
);
494 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
496 set_registry_variables( hkey
, REG_SZ
);
497 set_registry_variables( hkey
, REG_EXPAND_SZ
);
501 /* then the ones for the current user */
502 if (RtlOpenCurrentUser( KEY_ALL_ACCESS
, (HKEY
*)&attr
.RootDirectory
) != STATUS_SUCCESS
) return;
503 RtlInitUnicodeString( &nameW
, envW
);
504 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
506 set_registry_variables( hkey
, REG_SZ
);
507 set_registry_variables( hkey
, REG_EXPAND_SZ
);
510 NtClose( attr
.RootDirectory
);
514 /***********************************************************************
517 * Set the Wine library Unicode argv global variables.
519 static void set_library_wargv( char **argv
)
527 for (argc
= 0; argv
[argc
]; argc
++)
528 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
530 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
531 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
532 p
= (WCHAR
*)(wargv
+ argc
+ 1);
533 for (argc
= 0; argv
[argc
]; argc
++)
535 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
542 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
544 for (argc
= 0; wargv
[argc
]; argc
++)
545 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
547 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
548 q
= (char *)(argv
+ argc
+ 1);
549 for (argc
= 0; wargv
[argc
]; argc
++)
551 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
558 __wine_main_argv
= argv
;
559 __wine_main_wargv
= wargv
;
563 /***********************************************************************
566 * Build the command line of a process from the argv array.
568 * Note that it does NOT necessarily include the file name.
569 * Sometimes we don't even have any command line options at all.
571 * We must quote and escape characters so that the argv array can be rebuilt
572 * from the command line:
573 * - spaces and tabs must be quoted
575 * - quotes must be escaped
577 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
578 * resulting in an odd number of '\' followed by a '"'
581 * - '\'s that are not followed by a '"' can be left as is
585 static BOOL
build_command_line( WCHAR
**argv
)
590 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
592 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
595 for (arg
= argv
; *arg
; arg
++)
597 int has_space
,bcount
;
603 if( !*a
) has_space
=1;
608 if (*a
==' ' || *a
=='\t') {
610 } else if (*a
=='"') {
611 /* doubling of '\' preceeding a '"',
612 * plus escaping of said '"'
620 len
+=(a
-*arg
)+1 /* for the separating space */;
622 len
+=2; /* for the quotes */
625 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
628 p
= rupp
->CommandLine
.Buffer
;
629 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
630 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
631 for (arg
= argv
; *arg
; arg
++)
633 int has_space
,has_quote
;
636 /* Check for quotes and spaces in this argument */
637 has_space
=has_quote
=0;
639 if( !*a
) has_space
=1;
641 if (*a
==' ' || *a
=='\t') {
645 } else if (*a
=='"') {
653 /* Now transfer it to the command line */
670 /* Double all the '\\' preceeding this '"', plus one */
671 for (i
=0;i
<=bcount
;i
++)
683 while ((*p
=*x
++)) p
++;
689 if (p
> rupp
->CommandLine
.Buffer
)
690 p
--; /* remove last space */
697 /* make sure the unicode string doesn't point beyond the end pointer */
698 static inline void fix_unicode_string( UNICODE_STRING
*str
, char *end_ptr
)
700 if ((char *)str
->Buffer
>= end_ptr
)
702 str
->Length
= str
->MaximumLength
= 0;
706 if ((char *)str
->Buffer
+ str
->MaximumLength
> end_ptr
)
708 str
->MaximumLength
= (end_ptr
- (char *)str
->Buffer
) & ~(sizeof(WCHAR
) - 1);
710 if (str
->Length
>= str
->MaximumLength
)
712 if (str
->MaximumLength
>= sizeof(WCHAR
))
713 str
->Length
= str
->MaximumLength
- sizeof(WCHAR
);
715 str
->Length
= str
->MaximumLength
= 0;
719 static void version(void)
721 MESSAGE( "%s\n", PACKAGE_STRING
);
725 static void usage(void)
727 MESSAGE( "%s\n", PACKAGE_STRING
);
728 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
729 MESSAGE( " wine --help Display this help and exit\n");
730 MESSAGE( " wine --version Output version information and exit\n");
735 /***********************************************************************
736 * init_user_process_params
738 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
740 static RTL_USER_PROCESS_PARAMETERS
*init_user_process_params( size_t info_size
)
743 DWORD size
, env_size
;
744 RTL_USER_PROCESS_PARAMETERS
*params
;
748 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0, &size
,
749 MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
752 SERVER_START_REQ( get_startup_info
)
754 wine_server_set_reply( req
, ptr
, info_size
);
755 wine_server_call( req
);
756 info_size
= wine_server_reply_size( reply
);
761 params
->AllocationSize
= size
;
762 if (params
->Size
> info_size
) params
->Size
= info_size
;
764 /* make sure the strings are valid */
765 fix_unicode_string( ¶ms
->CurrentDirectory
.DosPath
, (char *)info_size
);
766 fix_unicode_string( ¶ms
->DllPath
, (char *)info_size
);
767 fix_unicode_string( ¶ms
->ImagePathName
, (char *)info_size
);
768 fix_unicode_string( ¶ms
->CommandLine
, (char *)info_size
);
769 fix_unicode_string( ¶ms
->WindowTitle
, (char *)info_size
);
770 fix_unicode_string( ¶ms
->Desktop
, (char *)info_size
);
771 fix_unicode_string( ¶ms
->ShellInfo
, (char *)info_size
);
772 fix_unicode_string( ¶ms
->RuntimeInfo
, (char *)info_size
);
774 /* environment needs to be a separate memory block */
775 env_size
= info_size
- params
->Size
;
776 if (!env_size
) env_size
= 1;
778 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0, &env_size
,
779 MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
781 memcpy( ptr
, (char *)params
+ params
->Size
, info_size
- params
->Size
);
782 params
->Environment
= ptr
;
784 return RtlNormalizeProcessParams( params
);
788 /***********************************************************************
789 * init_current_directory
791 * Initialize the current directory from the Unix cwd or the parent info.
793 static void init_current_directory( CURDIR
*cur_dir
)
795 UNICODE_STRING dir_str
;
799 /* if we received a cur dir from the parent, try this first */
801 if (cur_dir
->DosPath
.Length
)
803 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
806 /* now try to get it from the Unix cwd */
808 for (size
= 256; ; size
*= 2)
810 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
811 if (getcwd( cwd
, size
)) break;
812 HeapFree( GetProcessHeap(), 0, cwd
);
813 if (errno
== ERANGE
) continue;
821 int lenW
= MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, NULL
, 0 );
822 if ((dirW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) )))
824 MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, dirW
, lenW
);
825 RtlInitUnicodeString( &dir_str
, dirW
);
826 RtlSetCurrentDirectory_U( &dir_str
);
827 RtlFreeUnicodeString( &dir_str
);
831 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
833 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
834 "starting in the Windows directory.\n", cwd
? cwd
: "" );
835 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
836 RtlSetCurrentDirectory_U( &dir_str
);
838 if (cwd
) HeapFree( GetProcessHeap(), 0, cwd
);
841 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
842 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
846 /***********************************************************************
849 * Initialize the windows and system directories from the environment.
851 static void init_windows_dirs(void)
853 extern void __wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
855 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
856 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
857 static const WCHAR default_windirW
[] = {'c',':','\\','w','i','n','d','o','w','s',0};
858 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m',0};
863 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
865 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
866 GetEnvironmentVariableW( windirW
, buffer
, len
);
867 DIR_Windows
= buffer
;
869 else DIR_Windows
= default_windirW
;
871 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
873 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
874 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
879 len
= strlenW( DIR_Windows
);
880 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
881 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
882 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
886 if (GetFileAttributesW( DIR_Windows
) == INVALID_FILE_ATTRIBUTES
)
887 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
888 debugstr_w(DIR_Windows
) );
889 if (GetFileAttributesW( DIR_System
) == INVALID_FILE_ATTRIBUTES
)
890 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
891 debugstr_w(DIR_System
) );
893 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
894 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
896 /* set the directories in ntdll too */
897 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
901 /***********************************************************************
904 * Main process initialisation code
906 static BOOL
process_init(void)
908 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
910 size_t info_size
= 0;
911 RTL_USER_PROCESS_PARAMETERS
*params
;
912 PEB
*peb
= NtCurrentTeb()->Peb
;
913 HANDLE hstdin
, hstdout
, hstderr
;
914 extern void __wine_dbg_kernel32_init(void);
918 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
922 setlocale(LC_CTYPE
,"");
924 /* Retrieve startup info from the server */
925 SERVER_START_REQ( init_process
)
928 req
->ldt_copy
= &wine_ldt_copy
;
929 if ((ret
= !wine_server_call_err( req
)))
931 main_exe_file
= reply
->exe_file
;
932 main_create_flags
= reply
->create_flags
;
933 info_size
= reply
->info_size
;
934 server_startticks
= reply
->server_start
;
935 hstdin
= reply
->hstdin
;
936 hstdout
= reply
->hstdout
;
937 hstderr
= reply
->hstderr
;
941 if (!ret
) return FALSE
;
945 params
= peb
->ProcessParameters
;
947 /* This is wine specific: we have no parent (we're started from unix)
948 * so, create a simple console with bare handles to unix stdio
949 * input & output streams (aka simple console)
951 wine_server_fd_to_handle( 0, GENERIC_READ
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdInput
);
952 wine_server_fd_to_handle( 1, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdOutput
);
953 wine_server_fd_to_handle( 2, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdError
);
955 params
->CurrentDirectory
.DosPath
.Length
= 0;
956 params
->CurrentDirectory
.DosPath
.MaximumLength
= RtlGetLongestNtPathLength() * sizeof(WCHAR
);
957 params
->CurrentDirectory
.DosPath
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, params
->CurrentDirectory
.DosPath
.MaximumLength
);
961 if (!(params
= init_user_process_params( info_size
))) return FALSE
;
962 peb
->ProcessParameters
= params
;
964 /* convert value from server:
965 * + 0 => INVALID_HANDLE_VALUE
966 * + console handle need to be mapped
969 hstdin
= INVALID_HANDLE_VALUE
;
970 else if (VerifyConsoleIoHandle(console_handle_map(hstdin
)))
971 hstdin
= console_handle_map(hstdin
);
974 hstdout
= INVALID_HANDLE_VALUE
;
975 else if (VerifyConsoleIoHandle(console_handle_map(hstdout
)))
976 hstdout
= console_handle_map(hstdout
);
979 hstderr
= INVALID_HANDLE_VALUE
;
980 else if (VerifyConsoleIoHandle(console_handle_map(hstderr
)))
981 hstderr
= console_handle_map(hstderr
);
983 params
->hStdInput
= hstdin
;
984 params
->hStdOutput
= hstdout
;
985 params
->hStdError
= hstderr
;
988 kernel32_handle
= GetModuleHandleW(kernel32W
);
994 /* Copy the parent environment */
995 if (!build_initial_environment( __wine_main_environ
)) return FALSE
;
997 /* Create device symlinks */
998 VOLUME_CreateDevices();
1000 /* registry initialisation */
1001 SHELL_LoadRegistry();
1003 /* global boot finished, the rest is process-local */
1004 SERVER_START_REQ( boot_done
)
1006 req
->debug_level
= TRACE_ON(server
);
1007 wine_server_call( req
);
1011 set_registry_environment();
1014 init_windows_dirs();
1015 init_current_directory( ¶ms
->CurrentDirectory
);
1021 /***********************************************************************
1024 * Startup routine of a new process. Runs on the new process stack.
1026 static void start_process( void *arg
)
1030 PEB
*peb
= NtCurrentTeb()->Peb
;
1031 IMAGE_NT_HEADERS
*nt
;
1032 LPTHREAD_START_ROUTINE entry
;
1034 LdrInitializeThunk( main_exe_file
, 0, 0, 0 );
1036 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1037 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
1038 nt
->OptionalHeader
.AddressOfEntryPoint
);
1040 if (TRACE_ON(relay
))
1041 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1042 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
1044 SetLastError( 0 ); /* clear error code */
1045 if (peb
->BeingDebugged
) DbgBreakPoint();
1046 ExitProcess( entry( peb
) );
1048 __EXCEPT(UnhandledExceptionFilter
)
1050 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1056 /***********************************************************************
1057 * __wine_kernel_init
1059 * Wine initialisation: load and start the main exe file.
1061 void __wine_kernel_init(void)
1063 WCHAR
*main_exe_name
, *p
;
1065 DWORD stack_size
= 0;
1067 PEB
*peb
= NtCurrentTeb()->Peb
;
1069 /* Initialize everything */
1070 if (!process_init()) exit(1);
1072 __wine_main_argv
++; /* remove argv[0] (wine itself) */
1075 if (!(main_exe_name
= peb
->ProcessParameters
->ImagePathName
.Buffer
))
1077 WCHAR buffer
[MAX_PATH
];
1078 WCHAR exe_nameW
[MAX_PATH
];
1080 if (!__wine_main_argv
[0]) usage();
1081 if (__wine_main_argc
== 1)
1083 if (strcmp(__wine_main_argv
[0], "--help") == 0) usage();
1084 if (strcmp(__wine_main_argv
[0], "--version") == 0) version();
1087 MultiByteToWideChar( CP_UNIXCP
, 0, __wine_main_argv
[0], -1, exe_nameW
, MAX_PATH
);
1088 if (!find_exe_file( exe_nameW
, buffer
, MAX_PATH
, &main_exe_file
))
1090 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1093 if (main_exe_file
== INVALID_HANDLE_VALUE
)
1095 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name
) );
1098 RtlCreateUnicodeString( &peb
->ProcessParameters
->ImagePathName
, buffer
);
1099 main_exe_name
= peb
->ProcessParameters
->ImagePathName
.Buffer
;
1102 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1103 debugstr_w(main_exe_name
), main_exe_file
, debugstr_a(__wine_main_argv
[0]) );
1105 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1106 MODULE_get_dll_load_path(NULL
) );
1107 VERSION_Init( main_exe_name
);
1109 if (!main_exe_file
) /* no file handle -> Winelib app */
1111 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name
) );
1112 if (open_builtin_exe_file( main_exe_name
, error
, sizeof(error
), 0, &file_exists
))
1114 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1115 debugstr_w(main_exe_name
), error
);
1119 switch( MODULE_GetBinaryType( main_exe_file
, NULL
, NULL
))
1122 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name
) );
1123 if ((peb
->ImageBaseAddress
= load_pe_exe( main_exe_name
, main_exe_file
)))
1125 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name
) );
1128 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name
) );
1130 case BINARY_UNKNOWN
:
1131 /* check for .com extension */
1132 if (!(p
= strrchrW( main_exe_name
, '.' )) || strcmpiW( p
, comW
))
1134 MESSAGE( "wine: cannot determine executable type for %s\n",
1135 debugstr_w(main_exe_name
) );
1142 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name
) );
1143 CloseHandle( main_exe_file
);
1147 __wine_main_argv
[0] = "winevdm.exe";
1148 if (open_builtin_exe_file( winevdmW
, error
, sizeof(error
), 0, &file_exists
))
1150 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1151 debugstr_w(main_exe_name
), error
);
1153 case BINARY_UNIX_EXE
:
1154 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name
) );
1156 case BINARY_UNIX_LIB
:
1160 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name
) );
1161 CloseHandle( main_exe_file
);
1163 if ((unix_name
= wine_get_unix_file_name( main_exe_name
)) &&
1164 wine_dlopen( unix_name
, RTLD_NOW
, error
, sizeof(error
) ))
1166 static const WCHAR soW
[] = {'.','s','o',0};
1167 if ((p
= strrchrW( main_exe_name
, '.' )) && !strcmpW( p
, soW
))
1170 /* update the unicode string */
1171 RtlInitUnicodeString( &peb
->ProcessParameters
->ImagePathName
, main_exe_name
);
1173 HeapFree( GetProcessHeap(), 0, unix_name
);
1176 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name
), error
);
1182 /* build command line */
1183 set_library_wargv( __wine_main_argv
);
1184 if (!build_command_line( __wine_main_wargv
)) goto error
;
1186 stack_size
= RtlImageNtHeader(peb
->ImageBaseAddress
)->OptionalHeader
.SizeOfStackReserve
;
1188 /* allocate main thread stack */
1189 if (!THREAD_InitStack( NtCurrentTeb(), stack_size
)) goto error
;
1191 /* switch to the new stack */
1192 wine_switch_to_stack( start_process
, NULL
, NtCurrentTeb()->Tib
.StackBase
);
1195 ExitProcess( GetLastError() );
1199 /***********************************************************************
1202 * Build an argv array from a command-line.
1203 * 'reserved' is the number of args to reserve before the first one.
1205 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1209 char *arg
,*s
,*d
,*cmdline
;
1210 int in_quotes
,bcount
,len
;
1212 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1213 if (!(cmdline
= malloc(len
))) return NULL
;
1214 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1221 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1224 /* skip the remaining spaces */
1225 while (*s
==' ' || *s
=='\t') {
1232 } else if (*s
=='\\') {
1233 /* '\', count them */
1235 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1237 in_quotes
=!in_quotes
;
1240 /* a regular character */
1245 argv
=malloc(argc
*sizeof(*argv
));
1254 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1255 /* Close the argument and copy it */
1259 /* skip the remaining spaces */
1262 } while (*s
==' ' || *s
=='\t');
1264 /* Start with a new argument */
1267 } else if (*s
=='\\') {
1271 } else if (*s
=='"') {
1273 if ((bcount
& 1)==0) {
1274 /* Preceeded by an even number of '\', this is half that
1275 * number of '\', plus a '"' which we discard.
1279 in_quotes
=!in_quotes
;
1281 /* Preceeded by an odd number of '\', this is half that
1282 * number of '\' followed by a '"'
1290 /* a regular character */
1305 /***********************************************************************
1308 * Allocate an environment string; helper for build_envp
1310 static char *alloc_env_string( const char *name
, const char *value
)
1312 char *ret
= malloc( strlen(name
) + strlen(value
) + 1 );
1313 strcpy( ret
, name
);
1314 strcat( ret
, value
);
1318 /***********************************************************************
1321 * Build the environment of a new child process.
1323 static char **build_envp( const WCHAR
*envW
)
1328 int count
= 0, length
;
1330 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1332 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1333 if (!(env
= malloc( length
))) return NULL
;
1334 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1338 if ((envp
= malloc( count
* sizeof(*envp
) )))
1340 char **envptr
= envp
;
1342 /* some variables must not be modified, so we get them directly from the unix env */
1343 if ((p
= getenv("PATH"))) *envptr
++ = alloc_env_string( "PATH=", p
);
1344 if ((p
= getenv("TEMP"))) *envptr
++ = alloc_env_string( "TEMP=", p
);
1345 if ((p
= getenv("TMP"))) *envptr
++ = alloc_env_string( "TMP=", p
);
1346 if ((p
= getenv("HOME"))) *envptr
++ = alloc_env_string( "HOME=", p
);
1347 /* now put the Windows environment strings */
1348 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1350 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1351 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1352 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1353 *envptr
++ = alloc_env_string( "WINE", p
);
1363 /***********************************************************************
1366 * Fork and exec a new Unix binary, checking for errors.
1368 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
,
1369 const WCHAR
*env
, const char *newdir
)
1374 if (!env
) env
= GetEnvironmentStringsW();
1378 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1381 fcntl( fd
[1], F_SETFD
, 1 ); /* set close on exec */
1382 if (!(pid
= fork())) /* child */
1384 char **argv
= build_argv( cmdline
, 0 );
1385 char **envp
= build_envp( env
);
1388 /* Reset signals that we previously set to SIG_IGN */
1389 signal( SIGPIPE
, SIG_DFL
);
1390 signal( SIGCHLD
, SIG_DFL
);
1392 if (newdir
) chdir(newdir
);
1394 if (argv
&& envp
) execve( filename
, argv
, envp
);
1396 write( fd
[1], &err
, sizeof(err
) );
1400 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1405 if (pid
== -1) FILE_SetDosError();
1411 /***********************************************************************
1412 * create_user_params
1414 static RTL_USER_PROCESS_PARAMETERS
*create_user_params( LPCWSTR filename
, LPCWSTR cmdline
,
1415 LPCWSTR cur_dir
, LPWSTR env
,
1416 const STARTUPINFOW
*startup
)
1418 RTL_USER_PROCESS_PARAMETERS
*params
;
1419 UNICODE_STRING image_str
, cmdline_str
, curdir_str
, desktop
, title
, runtime
;
1421 WCHAR buffer
[MAX_PATH
];
1423 if(!GetLongPathNameW( filename
, buffer
, MAX_PATH
))
1424 lstrcpynW( buffer
, filename
, MAX_PATH
);
1425 if(!GetFullPathNameW( buffer
, MAX_PATH
, buffer
, NULL
))
1426 lstrcpynW( buffer
, filename
, MAX_PATH
);
1427 RtlInitUnicodeString( &image_str
, buffer
);
1429 RtlInitUnicodeString( &cmdline_str
, cmdline
);
1430 if (cur_dir
) RtlInitUnicodeString( &curdir_str
, cur_dir
);
1431 if (startup
->lpDesktop
) RtlInitUnicodeString( &desktop
, startup
->lpDesktop
);
1432 if (startup
->lpTitle
) RtlInitUnicodeString( &title
, startup
->lpTitle
);
1433 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1436 runtime
.MaximumLength
= startup
->cbReserved2
;
1437 runtime
.Buffer
= (WCHAR
*)startup
->lpReserved2
;
1440 status
= RtlCreateProcessParameters( ¶ms
, &image_str
, NULL
,
1441 cur_dir
? &curdir_str
: NULL
,
1443 startup
->lpTitle
? &title
: NULL
,
1444 startup
->lpDesktop
? &desktop
: NULL
,
1446 (startup
->lpReserved2
&& startup
->cbReserved2
) ? &runtime
: NULL
);
1447 if (status
!= STATUS_SUCCESS
)
1449 SetLastError( RtlNtStatusToDosError(status
) );
1453 params
->hStdInput
= startup
->hStdInput
;
1454 params
->hStdOutput
= startup
->hStdOutput
;
1455 params
->hStdError
= startup
->hStdError
;
1456 params
->dwX
= startup
->dwX
;
1457 params
->dwY
= startup
->dwY
;
1458 params
->dwXSize
= startup
->dwXSize
;
1459 params
->dwYSize
= startup
->dwYSize
;
1460 params
->dwXCountChars
= startup
->dwXCountChars
;
1461 params
->dwYCountChars
= startup
->dwYCountChars
;
1462 params
->dwFillAttribute
= startup
->dwFillAttribute
;
1463 params
->dwFlags
= startup
->dwFlags
;
1464 params
->wShowWindow
= startup
->wShowWindow
;
1469 /***********************************************************************
1472 * Create a new process. If hFile is a valid handle we have an exe
1473 * file, otherwise it is a Winelib app.
1475 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1476 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1477 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1478 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1479 void *res_start
, void *res_end
)
1481 BOOL ret
, success
= FALSE
;
1482 HANDLE process_info
;
1484 RTL_USER_PROCESS_PARAMETERS
*params
;
1490 char preloader_reserve
[64];
1492 if (!env
) RtlAcquirePebLock();
1494 if (!(params
= create_user_params( filename
, cmd_line
, cur_dir
, env
, startup
)))
1496 if (!env
) RtlReleasePebLock();
1499 env_end
= params
->Environment
;
1500 while (*env_end
) env_end
+= strlenW(env_end
) + 1;
1503 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx%c",
1504 (unsigned long)res_start
, (unsigned long)res_end
, 0 );
1506 /* create the synchronization pipes */
1508 if (pipe( startfd
) == -1)
1510 if (!env
) RtlReleasePebLock();
1511 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1512 RtlDestroyProcessParameters( params
);
1515 if (pipe( execfd
) == -1)
1517 if (!env
) RtlReleasePebLock();
1518 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1519 close( startfd
[0] );
1520 close( startfd
[1] );
1521 RtlDestroyProcessParameters( params
);
1524 fcntl( execfd
[1], F_SETFD
, 1 ); /* set close on exec */
1526 /* create the child process */
1528 if (!(pid
= fork())) /* child */
1530 char **argv
= build_argv( cmd_line
, 1 );
1532 close( startfd
[1] );
1535 /* wait for parent to tell us to start */
1536 if (read( startfd
[0], &dummy
, 1 ) != 1) _exit(1);
1538 close( startfd
[0] );
1539 /* Reset signals that we previously set to SIG_IGN */
1540 signal( SIGPIPE
, SIG_DFL
);
1541 signal( SIGCHLD
, SIG_DFL
);
1543 putenv( preloader_reserve
);
1544 if (unixdir
) chdir(unixdir
);
1548 /* first, try for a WINELOADER environment variable */
1549 const char *loader
= getenv("WINELOADER");
1550 if (loader
) wine_exec_wine_binary( loader
, argv
, NULL
, TRUE
);
1551 /* now use the standard search strategy */
1552 wine_exec_wine_binary( NULL
, argv
, NULL
, TRUE
);
1555 write( execfd
[1], &err
, sizeof(err
) );
1559 /* this is the parent */
1561 close( startfd
[0] );
1565 if (!env
) RtlReleasePebLock();
1566 close( startfd
[1] );
1569 RtlDestroyProcessParameters( params
);
1573 /* create the process on the server side */
1575 SERVER_START_REQ( new_process
)
1577 req
->inherit_all
= inherit
;
1578 req
->create_flags
= flags
;
1579 req
->unix_pid
= pid
;
1580 req
->exe_file
= hFile
;
1581 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1583 req
->hstdin
= startup
->hStdInput
;
1584 req
->hstdout
= startup
->hStdOutput
;
1585 req
->hstderr
= startup
->hStdError
;
1589 req
->hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1590 req
->hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1591 req
->hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1594 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1596 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1597 if (is_console_handle(req
->hstdin
)) req
->hstdin
= INVALID_HANDLE_VALUE
;
1598 if (is_console_handle(req
->hstdout
)) req
->hstdout
= INVALID_HANDLE_VALUE
;
1599 if (is_console_handle(req
->hstderr
)) req
->hstderr
= INVALID_HANDLE_VALUE
;
1603 if (is_console_handle(req
->hstdin
)) req
->hstdin
= console_handle_unmap(req
->hstdin
);
1604 if (is_console_handle(req
->hstdout
)) req
->hstdout
= console_handle_unmap(req
->hstdout
);
1605 if (is_console_handle(req
->hstderr
)) req
->hstderr
= console_handle_unmap(req
->hstderr
);
1608 wine_server_add_data( req
, params
, params
->Size
);
1609 wine_server_add_data( req
, params
->Environment
, (env_end
-params
->Environment
)*sizeof(WCHAR
) );
1610 ret
= !wine_server_call_err( req
);
1611 process_info
= reply
->info
;
1615 if (!env
) RtlReleasePebLock();
1616 RtlDestroyProcessParameters( params
);
1619 close( startfd
[1] );
1624 /* tell child to start and wait for it to exec */
1626 write( startfd
[1], &dummy
, 1 );
1627 close( startfd
[1] );
1629 if (read( execfd
[0], &err
, sizeof(err
) ) > 0) /* exec failed */
1634 CloseHandle( process_info
);
1639 /* wait for the new process info to be ready */
1641 WaitForSingleObject( process_info
, INFINITE
);
1642 SERVER_START_REQ( get_new_process_info
)
1644 req
->info
= process_info
;
1645 req
->pinherit
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
);
1646 req
->tinherit
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
);
1647 if ((ret
= !wine_server_call_err( req
)))
1649 info
->dwProcessId
= (DWORD
)reply
->pid
;
1650 info
->dwThreadId
= (DWORD
)reply
->tid
;
1651 info
->hProcess
= reply
->phandle
;
1652 info
->hThread
= reply
->thandle
;
1653 success
= reply
->success
;
1658 if (ret
&& !success
) /* new process failed to start */
1661 if (GetExitCodeProcess( info
->hProcess
, &exitcode
)) SetLastError( exitcode
);
1662 CloseHandle( info
->hThread
);
1663 CloseHandle( info
->hProcess
);
1666 CloseHandle( process_info
);
1671 /***********************************************************************
1672 * create_vdm_process
1674 * Create a new VDM process for a 16-bit or DOS application.
1676 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
1677 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1678 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1679 LPPROCESS_INFORMATION info
, LPCSTR unixdir
)
1681 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1684 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
1685 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
1689 SetLastError( ERROR_OUTOFMEMORY
);
1692 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
1693 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
1694 flags
, startup
, info
, unixdir
, NULL
, NULL
);
1695 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
1700 /***********************************************************************
1701 * create_cmd_process
1703 * Create a new cmd shell process for a .BAT file.
1705 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
1706 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1707 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1708 LPPROCESS_INFORMATION info
)
1711 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
1712 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
1713 WCHAR comspec
[MAX_PATH
];
1717 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
1719 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
1720 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
1723 strcpyW( newcmdline
, comspec
);
1724 strcatW( newcmdline
, slashcW
);
1725 strcatW( newcmdline
, cmd_line
);
1726 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
1727 flags
, env
, cur_dir
, startup
, info
);
1728 HeapFree( GetProcessHeap(), 0, newcmdline
);
1733 /*************************************************************************
1736 * Helper for CreateProcess: retrieve the file name to load from the
1737 * app name and command line. Store the file name in buffer, and
1738 * return a possibly modified command line.
1739 * Also returns a handle to the opened file if it's a Windows binary.
1741 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
1742 int buflen
, HANDLE
*handle
)
1744 static const WCHAR quotesW
[] = {'"','%','s','"',0};
1746 WCHAR
*name
, *pos
, *ret
= NULL
;
1749 /* if we have an app name, everything is easy */
1753 /* use the unmodified app name as file name */
1754 lstrcpynW( buffer
, appname
, buflen
);
1755 *handle
= open_exe_file( buffer
);
1756 if (!(ret
= cmdline
) || !cmdline
[0])
1758 /* no command-line, create one */
1759 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
1760 sprintfW( ret
, quotesW
, appname
);
1767 SetLastError( ERROR_INVALID_PARAMETER
);
1771 /* first check for a quoted file name */
1773 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
1775 int len
= p
- cmdline
- 1;
1776 /* extract the quoted portion as file name */
1777 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1778 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
1781 if (find_exe_file( name
, buffer
, buflen
, handle
))
1782 ret
= cmdline
; /* no change necessary */
1786 /* now try the command-line word by word */
1788 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
1795 do *pos
++ = *p
++; while (*p
&& *p
!= ' ');
1797 if (find_exe_file( name
, buffer
, buflen
, handle
))
1804 if (!ret
|| !strchrW( name
, ' ' )) goto done
; /* no change necessary */
1806 /* now build a new command-line with quotes */
1808 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
1810 sprintfW( ret
, quotesW
, name
);
1814 HeapFree( GetProcessHeap(), 0, name
);
1819 /**********************************************************************
1820 * CreateProcessA (KERNEL32.@)
1822 BOOL WINAPI
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1823 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
1824 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
1825 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
1828 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
1829 UNICODE_STRING desktopW
, titleW
;
1832 desktopW
.Buffer
= NULL
;
1833 titleW
.Buffer
= NULL
;
1834 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
1835 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
1836 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
1838 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
1839 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
1841 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
1842 infoW
.lpDesktop
= desktopW
.Buffer
;
1843 infoW
.lpTitle
= titleW
.Buffer
;
1845 if (startup_info
->lpReserved
)
1846 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1847 debugstr_a(startup_info
->lpReserved
));
1849 ret
= CreateProcessW( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
1850 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
1852 if (app_nameW
) HeapFree( GetProcessHeap(), 0, app_nameW
);
1853 if (cmd_lineW
) HeapFree( GetProcessHeap(), 0, cmd_lineW
);
1854 if (cur_dirW
) HeapFree( GetProcessHeap(), 0, cur_dirW
);
1855 RtlFreeUnicodeString( &desktopW
);
1856 RtlFreeUnicodeString( &titleW
);
1861 /**********************************************************************
1862 * CreateProcessW (KERNEL32.@)
1864 BOOL WINAPI
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1865 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
1866 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
1867 LPPROCESS_INFORMATION info
)
1871 char *unixdir
= NULL
;
1872 WCHAR name
[MAX_PATH
];
1873 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
1874 void *res_start
, *res_end
;
1876 /* Process the AppName and/or CmdLine to get module name and path */
1878 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
1880 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
), &hFile
)))
1882 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
1884 /* Warn if unsupported features are used */
1886 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
1887 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
1888 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
1889 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
1890 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name
), flags
);
1894 unixdir
= wine_get_unix_file_name( cur_dir
);
1898 WCHAR buf
[MAX_PATH
];
1899 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
1902 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
1907 while (*p
) p
+= strlen(p
) + 1;
1908 p
++; /* final null */
1909 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
1910 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
1911 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
1912 flags
|= CREATE_UNICODE_ENVIRONMENT
;
1915 info
->hThread
= info
->hProcess
= 0;
1916 info
->dwProcessId
= info
->dwThreadId
= 0;
1918 /* Determine executable type */
1920 if (!hFile
) /* builtin exe */
1922 TRACE( "starting %s as Winelib app\n", debugstr_w(name
) );
1923 retv
= create_process( 0, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1924 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
);
1928 switch( MODULE_GetBinaryType( hFile
, &res_start
, &res_end
))
1931 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name
), res_start
, res_end
);
1932 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1933 inherit
, flags
, startup_info
, info
, unixdir
, res_start
, res_end
);
1938 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
1939 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1940 inherit
, flags
, startup_info
, info
, unixdir
);
1943 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
1944 SetLastError( ERROR_BAD_EXE_FORMAT
);
1946 case BINARY_UNIX_LIB
:
1947 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
1948 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1949 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
);
1951 case BINARY_UNKNOWN
:
1952 /* check for .com or .bat extension */
1953 if ((p
= strrchrW( name
, '.' )))
1955 if (!strcmpiW( p
, comW
))
1957 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
1958 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1959 inherit
, flags
, startup_info
, info
, unixdir
);
1962 if (!strcmpiW( p
, batW
))
1964 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
1965 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1966 inherit
, flags
, startup_info
, info
);
1971 case BINARY_UNIX_EXE
:
1973 /* unknown file, try as unix executable */
1976 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
1978 if ((unix_name
= wine_get_unix_file_name( name
)))
1980 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
) != -1);
1981 HeapFree( GetProcessHeap(), 0, unix_name
);
1986 CloseHandle( hFile
);
1989 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
1990 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
1991 if (unixdir
) HeapFree( GetProcessHeap(), 0, unixdir
);
1996 /***********************************************************************
1999 * Wrapper to call WaitForInputIdle USER function
2001 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2003 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2005 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2008 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2009 if (ptr
) return ptr( process
, timeout
);
2015 /***********************************************************************
2016 * WinExec (KERNEL32.@)
2018 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2020 PROCESS_INFORMATION info
;
2021 STARTUPINFOA startup
;
2025 memset( &startup
, 0, sizeof(startup
) );
2026 startup
.cb
= sizeof(startup
);
2027 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2028 startup
.wShowWindow
= nCmdShow
;
2030 /* cmdline needs to be writeable for CreateProcess */
2031 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2032 strcpy( cmdline
, lpCmdLine
);
2034 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2035 0, NULL
, NULL
, &startup
, &info
))
2037 /* Give 30 seconds to the app to come up */
2038 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2039 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2041 /* Close off the handles */
2042 CloseHandle( info
.hThread
);
2043 CloseHandle( info
.hProcess
);
2045 else if ((ret
= GetLastError()) >= 32)
2047 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2050 HeapFree( GetProcessHeap(), 0, cmdline
);
2055 /**********************************************************************
2056 * LoadModule (KERNEL32.@)
2058 HINSTANCE WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2060 LOADPARMS32
*params
= paramBlock
;
2061 PROCESS_INFORMATION info
;
2062 STARTUPINFOA startup
;
2063 HINSTANCE hInstance
;
2065 char filename
[MAX_PATH
];
2068 if (!name
) return (HINSTANCE
)ERROR_FILE_NOT_FOUND
;
2070 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2071 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2072 return (HINSTANCE
)GetLastError();
2074 len
= (BYTE
)params
->lpCmdLine
[0];
2075 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2076 return (HINSTANCE
)ERROR_NOT_ENOUGH_MEMORY
;
2078 strcpy( cmdline
, filename
);
2079 p
= cmdline
+ strlen(cmdline
);
2081 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2084 memset( &startup
, 0, sizeof(startup
) );
2085 startup
.cb
= sizeof(startup
);
2086 if (params
->lpCmdShow
)
2088 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2089 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2092 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2093 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2095 /* Give 30 seconds to the app to come up */
2096 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2097 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2098 hInstance
= (HINSTANCE
)33;
2099 /* Close off the handles */
2100 CloseHandle( info
.hThread
);
2101 CloseHandle( info
.hProcess
);
2103 else if ((hInstance
= (HINSTANCE
)GetLastError()) >= (HINSTANCE
)32)
2105 FIXME("Strange error set by CreateProcess: %p\n", hInstance
);
2106 hInstance
= (HINSTANCE
)11;
2109 HeapFree( GetProcessHeap(), 0, cmdline
);
2114 /******************************************************************************
2115 * TerminateProcess (KERNEL32.@)
2117 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2119 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2120 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2125 /***********************************************************************
2126 * ExitProcess (KERNEL32.@)
2128 void WINAPI
ExitProcess( DWORD status
)
2130 LdrShutdownProcess();
2131 SERVER_START_REQ( terminate_process
)
2133 /* send the exit code to the server */
2134 req
->handle
= GetCurrentProcess();
2135 req
->exit_code
= status
;
2136 wine_server_call( req
);
2143 /***********************************************************************
2144 * GetExitCodeProcess [KERNEL32.@]
2146 * Gets termination status of specified process
2152 BOOL WINAPI
GetExitCodeProcess(
2153 HANDLE hProcess
, /* [in] handle to the process */
2154 LPDWORD lpExitCode
) /* [out] address to receive termination status */
2157 PROCESS_BASIC_INFORMATION pbi
;
2159 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2161 if (status
== STATUS_SUCCESS
)
2163 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2166 SetLastError( RtlNtStatusToDosError(status
) );
2171 /***********************************************************************
2172 * SetErrorMode (KERNEL32.@)
2174 UINT WINAPI
SetErrorMode( UINT mode
)
2176 UINT old
= process_error_mode
;
2177 process_error_mode
= mode
;
2182 /**********************************************************************
2183 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2185 * Allocates a thread local storage index
2188 * Success: TLS Index
2189 * Failure: 0xFFFFFFFF
2191 DWORD WINAPI
TlsAlloc( void )
2195 RtlAcquirePebLock();
2196 index
= RtlFindClearBitsAndSet( NtCurrentTeb()->Peb
->TlsBitmap
, 1, 0 );
2197 if (index
!= ~0UL) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2198 else SetLastError( ERROR_NO_MORE_ITEMS
);
2199 RtlReleasePebLock();
2204 /**********************************************************************
2205 * TlsFree [KERNEL32.@] Releases a TLS index.
2207 * Releases a thread local storage index, making it available for reuse
2213 BOOL WINAPI
TlsFree(
2214 DWORD index
) /* [in] TLS Index to free */
2218 RtlAcquirePebLock();
2219 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2222 RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2223 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2225 else SetLastError( ERROR_INVALID_PARAMETER
);
2226 RtlReleasePebLock();
2231 /**********************************************************************
2232 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2235 * Success: Value stored in calling thread's TLS slot for index
2236 * Failure: 0 and GetLastError returns NO_ERROR
2238 LPVOID WINAPI
TlsGetValue(
2239 DWORD index
) /* [in] TLS index to retrieve value for */
2241 if (index
>= NtCurrentTeb()->Peb
->TlsBitmap
->SizeOfBitMap
)
2243 SetLastError( ERROR_INVALID_PARAMETER
);
2246 SetLastError( ERROR_SUCCESS
);
2247 return NtCurrentTeb()->TlsSlots
[index
];
2251 /**********************************************************************
2252 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2258 BOOL WINAPI
TlsSetValue(
2259 DWORD index
, /* [in] TLS index to set value for */
2260 LPVOID value
) /* [in] Value to be stored */
2262 if (index
>= NtCurrentTeb()->Peb
->TlsBitmap
->SizeOfBitMap
)
2264 SetLastError( ERROR_INVALID_PARAMETER
);
2267 NtCurrentTeb()->TlsSlots
[index
] = value
;
2272 /***********************************************************************
2273 * GetProcessFlags (KERNEL32.@)
2275 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2277 IMAGE_NT_HEADERS
*nt
;
2280 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2282 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2284 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2285 flags
|= PDB32_CONSOLE_PROC
;
2287 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2288 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2293 /***********************************************************************
2294 * GetProcessDword (KERNEL.485)
2295 * GetProcessDword (KERNEL32.18)
2296 * 'Of course you cannot directly access Windows internal structures'
2298 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
2303 TRACE("(%ld, %d)\n", dwProcessID
, offset
);
2305 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2307 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
2313 case GPD_APP_COMPAT_FLAGS
:
2314 return GetAppCompatFlags16(0);
2315 case GPD_LOAD_DONE_EVENT
:
2317 case GPD_HINSTANCE16
:
2318 return GetTaskDS16();
2319 case GPD_WINDOWS_VERSION
:
2320 return GetExeVersion16();
2322 return (DWORD
)NtCurrentTeb() - 0x10 /* FIXME */;
2324 return (DWORD
)NtCurrentTeb()->Peb
;
2325 case GPD_STARTF_SHELLDATA
: /* return stdoutput handle from startupinfo ??? */
2326 GetStartupInfoW(&siw
);
2327 return (DWORD
)siw
.hStdOutput
;
2328 case GPD_STARTF_HOTKEY
: /* return stdinput handle from startupinfo ??? */
2329 GetStartupInfoW(&siw
);
2330 return (DWORD
)siw
.hStdInput
;
2331 case GPD_STARTF_SHOWWINDOW
:
2332 GetStartupInfoW(&siw
);
2333 return siw
.wShowWindow
;
2334 case GPD_STARTF_SIZE
:
2335 GetStartupInfoW(&siw
);
2337 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2339 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2340 return MAKELONG( x
, y
);
2341 case GPD_STARTF_POSITION
:
2342 GetStartupInfoW(&siw
);
2344 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2346 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2347 return MAKELONG( x
, y
);
2348 case GPD_STARTF_FLAGS
:
2349 GetStartupInfoW(&siw
);
2354 return GetProcessFlags(0);
2356 return process_dword
;
2358 ERR("Unknown offset %d\n", offset
);
2363 /***********************************************************************
2364 * SetProcessDword (KERNEL.484)
2365 * 'Of course you cannot directly access Windows internal structures'
2367 void WINAPI
SetProcessDword( DWORD dwProcessID
, INT offset
, DWORD value
)
2369 TRACE("(%ld, %d)\n", dwProcessID
, offset
);
2371 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2373 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
2379 case GPD_APP_COMPAT_FLAGS
:
2380 case GPD_LOAD_DONE_EVENT
:
2381 case GPD_HINSTANCE16
:
2382 case GPD_WINDOWS_VERSION
:
2385 case GPD_STARTF_SHELLDATA
:
2386 case GPD_STARTF_HOTKEY
:
2387 case GPD_STARTF_SHOWWINDOW
:
2388 case GPD_STARTF_SIZE
:
2389 case GPD_STARTF_POSITION
:
2390 case GPD_STARTF_FLAGS
:
2393 ERR("Not allowed to modify offset %d\n", offset
);
2396 process_dword
= value
;
2399 ERR("Unknown offset %d\n", offset
);
2405 /***********************************************************************
2406 * ExitProcess (KERNEL.466)
2408 void WINAPI
ExitProcess16( WORD status
)
2411 ReleaseThunkLock( &count
);
2412 ExitProcess( status
);
2416 /*********************************************************************
2417 * OpenProcess (KERNEL32.@)
2419 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2422 SERVER_START_REQ( open_process
)
2425 req
->access
= access
;
2426 req
->inherit
= inherit
;
2427 if (!wine_server_call_err( req
)) ret
= reply
->handle
;
2434 /*********************************************************************
2435 * MapProcessHandle (KERNEL.483)
2436 * GetProcessId (KERNEL32.@)
2438 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2441 PROCESS_BASIC_INFORMATION pbi
;
2443 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2445 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2446 SetLastError( RtlNtStatusToDosError(status
) );
2451 /*********************************************************************
2452 * CloseW32Handle (KERNEL.474)
2453 * CloseHandle (KERNEL32.@)
2455 BOOL WINAPI
CloseHandle( HANDLE handle
)
2459 /* stdio handles need special treatment */
2460 if ((handle
== (HANDLE
)STD_INPUT_HANDLE
) ||
2461 (handle
== (HANDLE
)STD_OUTPUT_HANDLE
) ||
2462 (handle
== (HANDLE
)STD_ERROR_HANDLE
))
2463 handle
= GetStdHandle( (DWORD
)handle
);
2465 if (is_console_handle(handle
))
2466 return CloseConsoleHandle(handle
);
2468 status
= NtClose( handle
);
2469 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2474 /*********************************************************************
2475 * GetHandleInformation (KERNEL32.@)
2477 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2480 SERVER_START_REQ( set_handle_info
)
2482 req
->handle
= handle
;
2486 ret
= !wine_server_call_err( req
);
2487 if (ret
&& flags
) *flags
= reply
->old_flags
;
2494 /*********************************************************************
2495 * SetHandleInformation (KERNEL32.@)
2497 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2500 SERVER_START_REQ( set_handle_info
)
2502 req
->handle
= handle
;
2506 ret
= !wine_server_call_err( req
);
2513 /*********************************************************************
2514 * DuplicateHandle (KERNEL32.@)
2516 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2517 HANDLE dest_process
, HANDLE
*dest
,
2518 DWORD access
, BOOL inherit
, DWORD options
)
2522 if (is_console_handle(source
))
2524 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2525 if (source_process
!= dest_process
||
2526 source_process
!= GetCurrentProcess())
2528 SetLastError(ERROR_INVALID_PARAMETER
);
2531 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2532 return (*dest
!= INVALID_HANDLE_VALUE
);
2534 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2535 access
, inherit
? OBJ_INHERIT
: 0, options
);
2536 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2541 /***********************************************************************
2542 * ConvertToGlobalHandle (KERNEL.476)
2543 * ConvertToGlobalHandle (KERNEL32.@)
2545 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
2547 HANDLE ret
= INVALID_HANDLE_VALUE
;
2548 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
2549 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
2554 /***********************************************************************
2555 * SetHandleContext (KERNEL32.@)
2557 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
2559 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2560 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
2561 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2566 /***********************************************************************
2567 * GetHandleContext (KERNEL32.@)
2569 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
2571 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2572 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
2573 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2578 /***********************************************************************
2579 * CreateSocketHandle (KERNEL32.@)
2581 HANDLE WINAPI
CreateSocketHandle(void)
2583 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2584 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2585 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2586 return INVALID_HANDLE_VALUE
;
2590 /***********************************************************************
2591 * SetPriorityClass (KERNEL32.@)
2593 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
2596 SERVER_START_REQ( set_process_info
)
2598 req
->handle
= hprocess
;
2599 req
->priority
= priorityclass
;
2600 req
->mask
= SET_PROCESS_INFO_PRIORITY
;
2601 ret
= !wine_server_call_err( req
);
2608 /***********************************************************************
2609 * GetPriorityClass (KERNEL32.@)
2611 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
2614 PROCESS_BASIC_INFORMATION pbi
;
2616 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2618 if (status
== STATUS_SUCCESS
) return pbi
.BasePriority
;
2619 SetLastError( RtlNtStatusToDosError(status
) );
2624 /***********************************************************************
2625 * SetProcessAffinityMask (KERNEL32.@)
2627 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
2630 SERVER_START_REQ( set_process_info
)
2632 req
->handle
= hProcess
;
2633 req
->affinity
= affmask
;
2634 req
->mask
= SET_PROCESS_INFO_AFFINITY
;
2635 ret
= !wine_server_call_err( req
);
2642 /**********************************************************************
2643 * GetProcessAffinityMask (KERNEL32.@)
2645 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
2646 LPDWORD lpProcessAffinityMask
,
2647 LPDWORD lpSystemAffinityMask
)
2650 SERVER_START_REQ( get_process_info
)
2652 req
->handle
= hProcess
;
2653 if (!wine_server_call_err( req
))
2655 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= reply
->process_affinity
;
2656 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= reply
->system_affinity
;
2665 /***********************************************************************
2666 * GetProcessVersion (KERNEL32.@)
2668 DWORD WINAPI
GetProcessVersion( DWORD processid
)
2670 IMAGE_NT_HEADERS
*nt
;
2672 if (processid
&& processid
!= GetCurrentProcessId())
2674 FIXME("should use ReadProcessMemory\n");
2677 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2678 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
2679 nt
->OptionalHeader
.MinorSubsystemVersion
);
2684 /***********************************************************************
2685 * SetProcessWorkingSetSize [KERNEL32.@]
2686 * Sets the min/max working set sizes for a specified process.
2689 * hProcess [I] Handle to the process of interest
2690 * minset [I] Specifies minimum working set size
2691 * maxset [I] Specifies maximum working set size
2695 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
2698 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
2699 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
2700 /* Trim the working set to zero */
2701 /* Swap the process out of physical RAM */
2706 /***********************************************************************
2707 * GetProcessWorkingSetSize (KERNEL32.@)
2709 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
2712 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
2713 /* 32 MB working set size */
2714 if (minset
) *minset
= 32*1024*1024;
2715 if (maxset
) *maxset
= 32*1024*1024;
2720 /***********************************************************************
2721 * SetProcessShutdownParameters (KERNEL32.@)
2723 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
2725 FIXME("(%08lx, %08lx): partial stub.\n", level
, flags
);
2726 shutdown_flags
= flags
;
2727 shutdown_priority
= level
;
2732 /***********************************************************************
2733 * GetProcessShutdownParameters (KERNEL32.@)
2736 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
2738 *lpdwLevel
= shutdown_priority
;
2739 *lpdwFlags
= shutdown_flags
;
2744 /***********************************************************************
2745 * GetProcessPriorityBoost (KERNEL32.@)
2747 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
2749 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
2751 /* Report that no boost is present.. */
2752 *pDisablePriorityBoost
= FALSE
;
2757 /***********************************************************************
2758 * SetProcessPriorityBoost (KERNEL32.@)
2760 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
2762 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
2763 /* Say we can do it. I doubt the program will notice that we don't. */
2768 /***********************************************************************
2769 * ReadProcessMemory (KERNEL32.@)
2771 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
2772 SIZE_T
*bytes_read
)
2774 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
2775 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2780 /***********************************************************************
2781 * WriteProcessMemory (KERNEL32.@)
2783 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
2784 SIZE_T
*bytes_written
)
2786 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
2787 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2792 /****************************************************************************
2793 * FlushInstructionCache (KERNEL32.@)
2795 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
2798 if (GetVersion() & 0x80000000) return TRUE
; /* not NT, always TRUE */
2799 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
2800 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2805 /******************************************************************
2806 * GetProcessIoCounters (KERNEL32.@)
2808 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
2812 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
2813 ioc
, sizeof(*ioc
), NULL
);
2814 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2818 /***********************************************************************
2819 * ProcessIdToSessionId (KERNEL32.@)
2820 * This function is available on Terminal Server 4SP4 and Windows 2000
2822 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
2824 /* According to MSDN, if the calling process is not in a terminal
2825 * services environment, then the sessionid returned is zero.
2832 /***********************************************************************
2833 * RegisterServiceProcess (KERNEL.491)
2834 * RegisterServiceProcess (KERNEL32.@)
2836 * A service process calls this function to ensure that it continues to run
2837 * even after a user logged off.
2839 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
2841 /* I don't think that Wine needs to do anything in that function */
2842 return 1; /* success */
2846 /***********************************************************************
2847 * GetSystemMSecCount (SYSTEM.6)
2848 * GetTickCount (KERNEL32.@)
2850 * Returns the number of milliseconds, modulo 2^32, since the start
2851 * of the wineserver.
2853 DWORD WINAPI
GetTickCount(void)
2856 gettimeofday( &t
, NULL
);
2857 return ((t
.tv_sec
* 1000) + (t
.tv_usec
/ 1000)) - server_startticks
;
2861 /***********************************************************************
2862 * GetCurrentProcess (KERNEL32.@)
2864 #undef GetCurrentProcess
2865 HANDLE WINAPI
GetCurrentProcess(void)
2867 return (HANDLE
)0xffffffff;