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 pifW
[] = {'.','p','i','f',0};
86 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
88 extern void SHELL_LoadRegistry(void);
89 extern void convert_old_config(void);
90 extern void VERSION_Init( const WCHAR
*appname
);
91 extern void LOCALE_Init(void);
93 /***********************************************************************
96 inline static int contains_path( LPCWSTR name
)
98 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
102 /***********************************************************************
105 * Check if an environment variable needs to be handled specially when
106 * passed through the Unix environment (i.e. prefixed with "WINE").
108 inline static int is_special_env_var( const char *var
)
110 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
111 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
112 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
113 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
117 /***************************************************************************
120 * Get the path of a builtin module when the native file does not exist.
122 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
, UINT size
)
125 UINT len
= strlenW( DIR_System
);
127 if (contains_path( libname
))
129 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
130 filename
, &file_part
) > size
* sizeof(WCHAR
))
131 return FALSE
; /* too long */
133 if (strncmpiW( filename
, DIR_System
, len
) || filename
[len
] != '\\')
135 while (filename
[len
] == '\\') len
++;
136 if (filename
+ len
!= file_part
) return FALSE
;
140 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
141 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
142 file_part
= filename
+ len
;
143 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
144 strcpyW( file_part
, libname
);
146 if (ext
&& !strchrW( file_part
, '.' ))
148 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
149 return FALSE
; /* too long */
150 strcatW( file_part
, ext
);
156 /***********************************************************************
157 * open_builtin_exe_file
159 * Open an exe file for a builtin exe.
161 static void *open_builtin_exe_file( const WCHAR
*name
, char *error
, int error_size
,
162 int test_only
, int *file_exists
)
164 char exename
[MAX_PATH
];
168 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
169 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
171 /* we don't want to depend on the current codepage here */
172 len
= strlenW( name
) + 1;
173 if (len
>= sizeof(exename
)) return NULL
;
174 for (i
= 0; i
< len
; i
++)
176 if (name
[i
] > 127) return NULL
;
177 exename
[i
] = (char)name
[i
];
178 if (exename
[i
] >= 'A' && exename
[i
] <= 'Z') exename
[i
] += 'a' - 'A';
180 return wine_dll_load_main_exe( exename
, error
, error_size
, test_only
, file_exists
);
184 /***********************************************************************
187 * Open a specific exe file, taking load order into account.
188 * Returns the file handle or 0 for a builtin exe.
190 static HANDLE
open_exe_file( const WCHAR
*name
)
192 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
193 WCHAR buffer
[MAX_PATH
];
197 TRACE("looking for %s\n", debugstr_w(name
) );
199 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
200 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
202 /* file doesn't exist, check for builtin */
203 if (!contains_path( name
)) goto error
;
204 if (!get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
) )) goto error
;
208 MODULE_GetLoadOrderW( loadorder
, NULL
, name
);
210 for(i
= 0; i
< LOADORDER_NTYPES
; i
++)
212 if (loadorder
[i
] == LOADORDER_INVALID
) break;
216 TRACE( "Trying native exe %s\n", debugstr_w(name
) );
217 if (handle
!= INVALID_HANDLE_VALUE
) return handle
;
220 TRACE( "Trying built-in exe %s\n", debugstr_w(name
) );
221 open_builtin_exe_file( name
, NULL
, 0, 1, &file_exists
);
224 if (handle
!= INVALID_HANDLE_VALUE
) CloseHandle(handle
);
231 if (handle
!= INVALID_HANDLE_VALUE
) CloseHandle(handle
);
234 SetLastError( ERROR_FILE_NOT_FOUND
);
235 return INVALID_HANDLE_VALUE
;
239 /***********************************************************************
242 * Open an exe file, and return the full name and file handle.
243 * Returns FALSE if file could not be found.
244 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
245 * If file is a builtin exe, returns TRUE and sets handle to 0.
247 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
, HANDLE
*handle
)
249 static const WCHAR exeW
[] = {'.','e','x','e',0};
251 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
254 TRACE("looking for %s\n", debugstr_w(name
) );
256 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
) &&
257 !get_builtin_path( name
, exeW
, buffer
, buflen
))
259 /* no builtin found, try native without extension in case it is a Unix app */
261 if (SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
))
263 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer
) );
264 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
265 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
271 MODULE_GetLoadOrderW( loadorder
, NULL
, buffer
);
273 for(i
= 0; i
< LOADORDER_NTYPES
; i
++)
275 if (loadorder
[i
] == LOADORDER_INVALID
) break;
279 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
280 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
281 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
283 if (GetLastError() != ERROR_FILE_NOT_FOUND
) return TRUE
;
286 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer
) );
287 open_builtin_exe_file( buffer
, NULL
, 0, 1, &file_exists
);
298 SetLastError( ERROR_FILE_NOT_FOUND
);
303 /**********************************************************************
306 * Load a PE format EXE file.
308 static HMODULE
load_pe_exe( const WCHAR
*name
, HANDLE file
)
311 FILE_FS_DEVICE_INFORMATION device_info
;
312 IMAGE_NT_HEADERS
*nt
;
315 OBJECT_ATTRIBUTES attr
;
319 attr
.Length
= sizeof(attr
);
320 attr
.RootDirectory
= 0;
321 attr
.ObjectName
= NULL
;
323 attr
.SecurityDescriptor
= NULL
;
324 attr
.SecurityQualityOfService
= NULL
;
327 if (NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
328 &attr
, &size
, 0, SEC_IMAGE
, file
) != STATUS_SUCCESS
)
332 if (NtMapViewOfSection( mapping
, GetCurrentProcess(), &module
, 0, 0, &size
, &len
,
333 ViewShare
, 0, PAGE_READONLY
) != STATUS_SUCCESS
)
339 nt
= RtlImageNtHeader( module
);
340 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
342 if (!RtlImageRvaToSection( nt
, module
, nt
->OptionalHeader
.AddressOfEntryPoint
))
343 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
344 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
345 debugstr_w(name
), nt
->OptionalHeader
.AddressOfEntryPoint
);
348 if (NtQueryVolumeInformationFile( file
, &io
, &device_info
, sizeof(device_info
),
349 FileFsDeviceInformation
) == STATUS_SUCCESS
)
351 /* don't keep the file handle open on removable media */
352 if (device_info
.Characteristics
& FILE_REMOVABLE_MEDIA
)
354 CloseHandle( main_exe_file
);
362 /***********************************************************************
363 * build_initial_environment
365 * Build the Win32 environment from the Unix environment
367 static BOOL
build_initial_environment( char **environ
)
374 /* Compute the total size of the Unix environment */
375 for (e
= environ
; *e
; e
++)
377 if (is_special_env_var( *e
)) continue;
378 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
380 size
*= sizeof(WCHAR
);
382 /* Now allocate the environment */
384 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
385 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
388 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
389 endptr
= p
+ size
/ sizeof(WCHAR
);
391 /* And fill it with the Unix environment */
392 for (e
= environ
; *e
; e
++)
396 /* skip Unix special variables and use the Wine variants instead */
397 if (!strncmp( str
, "WINE", 4 ))
399 if (is_special_env_var( str
+ 4 )) str
+= 4;
400 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
402 else if (is_special_env_var( str
)) continue; /* skip it */
404 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
412 /***********************************************************************
413 * set_registry_variables
415 * Set environment variables by enumerating the values of a key;
416 * helper for set_registry_environment().
417 * Note that Windows happily truncates the value if it's too big.
419 static void set_registry_variables( HKEY hkey
, ULONG type
)
421 UNICODE_STRING env_name
, env_value
;
425 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
426 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
428 for (index
= 0; ; index
++)
430 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
431 buffer
, sizeof(buffer
), &size
);
432 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
434 if (info
->Type
!= type
)
436 env_name
.Buffer
= info
->Name
;
437 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
438 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
439 env_value
.Length
= env_value
.MaximumLength
= info
->DataLength
;
440 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
441 env_value
.Length
--; /* don't count terminating null if any */
442 if (info
->Type
== REG_EXPAND_SZ
)
444 WCHAR buf_expanded
[1024];
445 UNICODE_STRING env_expanded
;
446 env_expanded
.Length
= env_expanded
.MaximumLength
= sizeof(buf_expanded
);
447 env_expanded
.Buffer
=buf_expanded
;
448 status
= RtlExpandEnvironmentStrings_U(NULL
, &env_value
, &env_expanded
, NULL
);
449 if (status
== STATUS_SUCCESS
|| status
== STATUS_BUFFER_OVERFLOW
)
450 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_expanded
);
454 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
460 /***********************************************************************
461 * set_registry_environment
463 * Set the environment variables specified in the registry.
465 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
466 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
467 * on the order in which the variables are processed. But on Windows it
468 * does not really matter since they only use %SystemDrive% and
469 * %SystemRoot% which are predefined. But Wine defines these in the
470 * registry, so we need two passes.
472 static void set_registry_environment(void)
474 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
475 'S','y','s','t','e','m','\\',
476 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
477 'C','o','n','t','r','o','l','\\',
478 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
479 'E','n','v','i','r','o','n','m','e','n','t',0};
480 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
482 OBJECT_ATTRIBUTES attr
;
483 UNICODE_STRING nameW
;
486 attr
.Length
= sizeof(attr
);
487 attr
.RootDirectory
= 0;
488 attr
.ObjectName
= &nameW
;
490 attr
.SecurityDescriptor
= NULL
;
491 attr
.SecurityQualityOfService
= NULL
;
493 /* first the system environment variables */
494 RtlInitUnicodeString( &nameW
, env_keyW
);
495 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
497 set_registry_variables( hkey
, REG_SZ
);
498 set_registry_variables( hkey
, REG_EXPAND_SZ
);
502 /* then the ones for the current user */
503 if (RtlOpenCurrentUser( KEY_ALL_ACCESS
, (HKEY
*)&attr
.RootDirectory
) != STATUS_SUCCESS
) return;
504 RtlInitUnicodeString( &nameW
, envW
);
505 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
507 set_registry_variables( hkey
, REG_SZ
);
508 set_registry_variables( hkey
, REG_EXPAND_SZ
);
511 NtClose( attr
.RootDirectory
);
515 /***********************************************************************
518 * Set the Wine library Unicode argv global variables.
520 static void set_library_wargv( char **argv
)
528 for (argc
= 0; argv
[argc
]; argc
++)
529 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
531 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
532 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
533 p
= (WCHAR
*)(wargv
+ argc
+ 1);
534 for (argc
= 0; argv
[argc
]; argc
++)
536 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
543 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
545 for (argc
= 0; wargv
[argc
]; argc
++)
546 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
548 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
549 q
= (char *)(argv
+ argc
+ 1);
550 for (argc
= 0; wargv
[argc
]; argc
++)
552 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
559 __wine_main_argv
= argv
;
560 __wine_main_wargv
= wargv
;
564 /***********************************************************************
567 * Build the command line of a process from the argv array.
569 * Note that it does NOT necessarily include the file name.
570 * Sometimes we don't even have any command line options at all.
572 * We must quote and escape characters so that the argv array can be rebuilt
573 * from the command line:
574 * - spaces and tabs must be quoted
576 * - quotes must be escaped
578 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
579 * resulting in an odd number of '\' followed by a '"'
582 * - '\'s that are not followed by a '"' can be left as is
586 static BOOL
build_command_line( WCHAR
**argv
)
591 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
593 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
596 for (arg
= argv
; *arg
; arg
++)
598 int has_space
,bcount
;
604 if( !*a
) has_space
=1;
609 if (*a
==' ' || *a
=='\t') {
611 } else if (*a
=='"') {
612 /* doubling of '\' preceding a '"',
613 * plus escaping of said '"'
621 len
+=(a
-*arg
)+1 /* for the separating space */;
623 len
+=2; /* for the quotes */
626 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
629 p
= rupp
->CommandLine
.Buffer
;
630 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
631 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
632 for (arg
= argv
; *arg
; arg
++)
634 int has_space
,has_quote
;
637 /* Check for quotes and spaces in this argument */
638 has_space
=has_quote
=0;
640 if( !*a
) has_space
=1;
642 if (*a
==' ' || *a
=='\t') {
646 } else if (*a
=='"') {
654 /* Now transfer it to the command line */
671 /* Double all the '\\' preceding this '"', plus one */
672 for (i
=0;i
<=bcount
;i
++)
684 while ((*p
=*x
++)) p
++;
690 if (p
> rupp
->CommandLine
.Buffer
)
691 p
--; /* remove last space */
698 /* make sure the unicode string doesn't point beyond the end pointer */
699 static inline void fix_unicode_string( UNICODE_STRING
*str
, char *end_ptr
)
701 if ((char *)str
->Buffer
>= end_ptr
)
703 str
->Length
= str
->MaximumLength
= 0;
707 if ((char *)str
->Buffer
+ str
->MaximumLength
> end_ptr
)
709 str
->MaximumLength
= (end_ptr
- (char *)str
->Buffer
) & ~(sizeof(WCHAR
) - 1);
711 if (str
->Length
>= str
->MaximumLength
)
713 if (str
->MaximumLength
>= sizeof(WCHAR
))
714 str
->Length
= str
->MaximumLength
- sizeof(WCHAR
);
716 str
->Length
= str
->MaximumLength
= 0;
720 static void version(void)
722 MESSAGE( "%s\n", PACKAGE_STRING
);
726 static void usage(void)
728 MESSAGE( "%s\n", PACKAGE_STRING
);
729 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
730 MESSAGE( " wine --help Display this help and exit\n");
731 MESSAGE( " wine --version Output version information and exit\n");
736 /***********************************************************************
737 * init_user_process_params
739 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
741 static RTL_USER_PROCESS_PARAMETERS
*init_user_process_params( size_t info_size
)
744 DWORD size
, env_size
;
745 RTL_USER_PROCESS_PARAMETERS
*params
;
749 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0, &size
,
750 MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
753 SERVER_START_REQ( get_startup_info
)
755 wine_server_set_reply( req
, ptr
, info_size
);
756 wine_server_call( req
);
757 info_size
= wine_server_reply_size( reply
);
762 params
->AllocationSize
= size
;
763 if (params
->Size
> info_size
) params
->Size
= info_size
;
765 /* make sure the strings are valid */
766 fix_unicode_string( ¶ms
->CurrentDirectory
.DosPath
, (char *)info_size
);
767 fix_unicode_string( ¶ms
->DllPath
, (char *)info_size
);
768 fix_unicode_string( ¶ms
->ImagePathName
, (char *)info_size
);
769 fix_unicode_string( ¶ms
->CommandLine
, (char *)info_size
);
770 fix_unicode_string( ¶ms
->WindowTitle
, (char *)info_size
);
771 fix_unicode_string( ¶ms
->Desktop
, (char *)info_size
);
772 fix_unicode_string( ¶ms
->ShellInfo
, (char *)info_size
);
773 fix_unicode_string( ¶ms
->RuntimeInfo
, (char *)info_size
);
775 /* environment needs to be a separate memory block */
776 env_size
= info_size
- params
->Size
;
777 if (!env_size
) env_size
= 1;
779 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0, &env_size
,
780 MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
782 memcpy( ptr
, (char *)params
+ params
->Size
, info_size
- params
->Size
);
783 params
->Environment
= ptr
;
785 return RtlNormalizeProcessParams( params
);
789 /***********************************************************************
790 * init_current_directory
792 * Initialize the current directory from the Unix cwd or the parent info.
794 static void init_current_directory( CURDIR
*cur_dir
)
796 UNICODE_STRING dir_str
;
800 /* if we received a cur dir from the parent, try this first */
802 if (cur_dir
->DosPath
.Length
)
804 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
807 /* now try to get it from the Unix cwd */
809 for (size
= 256; ; size
*= 2)
811 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
812 if (getcwd( cwd
, size
)) break;
813 HeapFree( GetProcessHeap(), 0, cwd
);
814 if (errno
== ERANGE
) continue;
822 int lenW
= MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, NULL
, 0 );
823 if ((dirW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) )))
825 MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, dirW
, lenW
);
826 RtlInitUnicodeString( &dir_str
, dirW
);
827 RtlSetCurrentDirectory_U( &dir_str
);
828 RtlFreeUnicodeString( &dir_str
);
832 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
834 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
835 "starting in the Windows directory.\n", cwd
? cwd
: "" );
836 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
837 RtlSetCurrentDirectory_U( &dir_str
);
839 HeapFree( GetProcessHeap(), 0, cwd
);
842 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
843 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
847 /***********************************************************************
850 * Initialize the windows and system directories from the environment.
852 static void init_windows_dirs(void)
854 extern void __wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
856 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
857 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
858 static const WCHAR default_windirW
[] = {'c',':','\\','w','i','n','d','o','w','s',0};
859 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m',0};
864 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
866 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
867 GetEnvironmentVariableW( windirW
, buffer
, len
);
868 DIR_Windows
= buffer
;
870 else DIR_Windows
= default_windirW
;
872 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
874 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
875 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
880 len
= strlenW( DIR_Windows
);
881 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
882 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
883 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
887 if (GetFileAttributesW( DIR_Windows
) == INVALID_FILE_ATTRIBUTES
)
888 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
889 debugstr_w(DIR_Windows
) );
890 if (GetFileAttributesW( DIR_System
) == INVALID_FILE_ATTRIBUTES
)
891 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
892 debugstr_w(DIR_System
) );
894 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
895 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
897 /* set the directories in ntdll too */
898 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
902 /***********************************************************************
905 * Main process initialisation code
907 static BOOL
process_init(void)
909 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
911 size_t info_size
= 0;
912 RTL_USER_PROCESS_PARAMETERS
*params
;
913 PEB
*peb
= NtCurrentTeb()->Peb
;
914 HANDLE hstdin
, hstdout
, hstderr
;
915 extern void __wine_dbg_kernel32_init(void);
919 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
923 setlocale(LC_CTYPE
,"");
925 /* Retrieve startup info from the server */
926 SERVER_START_REQ( init_process
)
929 req
->ldt_copy
= &wine_ldt_copy
;
930 if ((ret
= !wine_server_call_err( req
)))
932 main_exe_file
= reply
->exe_file
;
933 main_create_flags
= reply
->create_flags
;
934 info_size
= reply
->info_size
;
935 server_startticks
= reply
->server_start
;
936 hstdin
= reply
->hstdin
;
937 hstdout
= reply
->hstdout
;
938 hstderr
= reply
->hstderr
;
942 if (!ret
) return FALSE
;
946 params
= peb
->ProcessParameters
;
948 /* This is wine specific: we have no parent (we're started from unix)
949 * so, create a simple console with bare handles to unix stdio
950 * input & output streams (aka simple console)
952 wine_server_fd_to_handle( 0, GENERIC_READ
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdInput
);
953 wine_server_fd_to_handle( 1, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdOutput
);
954 wine_server_fd_to_handle( 2, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdError
);
956 params
->CurrentDirectory
.DosPath
.Length
= 0;
957 params
->CurrentDirectory
.DosPath
.MaximumLength
= RtlGetLongestNtPathLength() * sizeof(WCHAR
);
958 params
->CurrentDirectory
.DosPath
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, params
->CurrentDirectory
.DosPath
.MaximumLength
);
962 if (!(params
= init_user_process_params( info_size
))) return FALSE
;
963 peb
->ProcessParameters
= params
;
965 /* convert value from server:
966 * + 0 => INVALID_HANDLE_VALUE
967 * + console handle need to be mapped
970 hstdin
= INVALID_HANDLE_VALUE
;
971 else if (VerifyConsoleIoHandle(console_handle_map(hstdin
)))
972 hstdin
= console_handle_map(hstdin
);
975 hstdout
= INVALID_HANDLE_VALUE
;
976 else if (VerifyConsoleIoHandle(console_handle_map(hstdout
)))
977 hstdout
= console_handle_map(hstdout
);
980 hstderr
= INVALID_HANDLE_VALUE
;
981 else if (VerifyConsoleIoHandle(console_handle_map(hstderr
)))
982 hstderr
= console_handle_map(hstderr
);
984 params
->hStdInput
= hstdin
;
985 params
->hStdOutput
= hstdout
;
986 params
->hStdError
= hstderr
;
989 kernel32_handle
= GetModuleHandleW(kernel32W
);
995 /* Copy the parent environment */
996 if (!build_initial_environment( __wine_main_environ
)) return FALSE
;
998 /* convert old configuration to new format */
999 convert_old_config();
1001 /* global boot finished, the rest is process-local */
1002 SERVER_START_REQ( boot_done
)
1004 req
->debug_level
= TRACE_ON(server
);
1005 wine_server_call( req
);
1009 set_registry_environment();
1012 init_windows_dirs();
1013 init_current_directory( ¶ms
->CurrentDirectory
);
1019 /***********************************************************************
1022 * Startup routine of a new process. Runs on the new process stack.
1024 static void start_process( void *arg
)
1028 PEB
*peb
= NtCurrentTeb()->Peb
;
1029 IMAGE_NT_HEADERS
*nt
;
1030 LPTHREAD_START_ROUTINE entry
;
1032 LdrInitializeThunk( main_exe_file
, 0, 0, 0 );
1034 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1035 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
1036 nt
->OptionalHeader
.AddressOfEntryPoint
);
1038 if (TRACE_ON(relay
))
1039 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1040 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
1042 SetLastError( 0 ); /* clear error code */
1043 if (peb
->BeingDebugged
) DbgBreakPoint();
1044 ExitProcess( entry( peb
) );
1046 __EXCEPT(UnhandledExceptionFilter
)
1048 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1054 /***********************************************************************
1055 * __wine_kernel_init
1057 * Wine initialisation: load and start the main exe file.
1059 void __wine_kernel_init(void)
1061 WCHAR
*main_exe_name
, *p
;
1063 DWORD stack_size
= 0;
1065 PEB
*peb
= NtCurrentTeb()->Peb
;
1067 /* Initialize everything */
1068 if (!process_init()) exit(1);
1070 __wine_main_argv
++; /* remove argv[0] (wine itself) */
1073 if (!(main_exe_name
= peb
->ProcessParameters
->ImagePathName
.Buffer
))
1075 WCHAR buffer
[MAX_PATH
];
1076 WCHAR exe_nameW
[MAX_PATH
];
1078 if (!__wine_main_argv
[0]) usage();
1079 if (__wine_main_argc
== 1)
1081 if (strcmp(__wine_main_argv
[0], "--help") == 0) usage();
1082 if (strcmp(__wine_main_argv
[0], "--version") == 0) version();
1085 MultiByteToWideChar( CP_UNIXCP
, 0, __wine_main_argv
[0], -1, exe_nameW
, MAX_PATH
);
1086 if (!find_exe_file( exe_nameW
, buffer
, MAX_PATH
, &main_exe_file
))
1088 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1091 if (main_exe_file
== INVALID_HANDLE_VALUE
)
1093 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name
) );
1096 RtlCreateUnicodeString( &peb
->ProcessParameters
->ImagePathName
, buffer
);
1097 main_exe_name
= peb
->ProcessParameters
->ImagePathName
.Buffer
;
1100 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1101 debugstr_w(main_exe_name
), main_exe_file
, debugstr_a(__wine_main_argv
[0]) );
1103 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1104 MODULE_get_dll_load_path(NULL
) );
1105 VERSION_Init( main_exe_name
);
1107 if (!main_exe_file
) /* no file handle -> Winelib app */
1109 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name
) );
1110 if (open_builtin_exe_file( main_exe_name
, error
, sizeof(error
), 0, &file_exists
))
1112 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1113 debugstr_w(main_exe_name
), error
);
1117 switch( MODULE_GetBinaryType( main_exe_file
, NULL
, NULL
))
1120 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name
) );
1121 if ((peb
->ImageBaseAddress
= load_pe_exe( main_exe_name
, main_exe_file
)))
1123 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name
) );
1126 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name
) );
1128 case BINARY_UNKNOWN
:
1129 /* check for .com extension */
1130 if (!(p
= strrchrW( main_exe_name
, '.' )) || strcmpiW( p
, comW
))
1132 MESSAGE( "wine: cannot determine executable type for %s\n",
1133 debugstr_w(main_exe_name
) );
1140 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name
) );
1141 CloseHandle( main_exe_file
);
1145 __wine_main_argv
[0] = "winevdm.exe";
1146 if (open_builtin_exe_file( winevdmW
, error
, sizeof(error
), 0, &file_exists
))
1148 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1149 debugstr_w(main_exe_name
), error
);
1151 case BINARY_UNIX_EXE
:
1152 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name
) );
1154 case BINARY_UNIX_LIB
:
1158 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name
) );
1159 CloseHandle( main_exe_file
);
1161 if ((unix_name
= wine_get_unix_file_name( main_exe_name
)) &&
1162 wine_dlopen( unix_name
, RTLD_NOW
, error
, sizeof(error
) ))
1164 static const WCHAR soW
[] = {'.','s','o',0};
1165 if ((p
= strrchrW( main_exe_name
, '.' )) && !strcmpW( p
, soW
))
1168 /* update the unicode string */
1169 RtlInitUnicodeString( &peb
->ProcessParameters
->ImagePathName
, main_exe_name
);
1171 HeapFree( GetProcessHeap(), 0, unix_name
);
1174 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name
), error
);
1180 /* build command line */
1181 set_library_wargv( __wine_main_argv
);
1182 if (!build_command_line( __wine_main_wargv
)) goto error
;
1184 stack_size
= RtlImageNtHeader(peb
->ImageBaseAddress
)->OptionalHeader
.SizeOfStackReserve
;
1186 /* allocate main thread stack */
1187 if (!THREAD_InitStack( NtCurrentTeb(), stack_size
)) goto error
;
1189 /* switch to the new stack */
1190 wine_switch_to_stack( start_process
, NULL
, NtCurrentTeb()->Tib
.StackBase
);
1193 ExitProcess( GetLastError() );
1197 /***********************************************************************
1200 * Build an argv array from a command-line.
1201 * 'reserved' is the number of args to reserve before the first one.
1203 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1207 char *arg
,*s
,*d
,*cmdline
;
1208 int in_quotes
,bcount
,len
;
1210 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1211 if (!(cmdline
= malloc(len
))) return NULL
;
1212 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1219 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1222 /* skip the remaining spaces */
1223 while (*s
==' ' || *s
=='\t') {
1230 } else if (*s
=='\\') {
1231 /* '\', count them */
1233 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1235 in_quotes
=!in_quotes
;
1238 /* a regular character */
1243 argv
=malloc(argc
*sizeof(*argv
));
1252 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1253 /* Close the argument and copy it */
1257 /* skip the remaining spaces */
1260 } while (*s
==' ' || *s
=='\t');
1262 /* Start with a new argument */
1265 } else if (*s
=='\\') {
1269 } else if (*s
=='"') {
1271 if ((bcount
& 1)==0) {
1272 /* Preceded by an even number of '\', this is half that
1273 * number of '\', plus a '"' which we discard.
1277 in_quotes
=!in_quotes
;
1279 /* Preceded by an odd number of '\', this is half that
1280 * number of '\' followed by a '"'
1288 /* a regular character */
1303 /***********************************************************************
1306 * Allocate an environment string; helper for build_envp
1308 static char *alloc_env_string( const char *name
, const char *value
)
1310 char *ret
= malloc( strlen(name
) + strlen(value
) + 1 );
1311 strcpy( ret
, name
);
1312 strcat( ret
, value
);
1316 /***********************************************************************
1319 * Build the environment of a new child process.
1321 static char **build_envp( const WCHAR
*envW
)
1326 int count
= 0, length
;
1328 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1330 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1331 if (!(env
= malloc( length
))) return NULL
;
1332 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1336 if ((envp
= malloc( count
* sizeof(*envp
) )))
1338 char **envptr
= envp
;
1340 /* some variables must not be modified, so we get them directly from the unix env */
1341 if ((p
= getenv("PATH"))) *envptr
++ = alloc_env_string( "PATH=", p
);
1342 if ((p
= getenv("TEMP"))) *envptr
++ = alloc_env_string( "TEMP=", p
);
1343 if ((p
= getenv("TMP"))) *envptr
++ = alloc_env_string( "TMP=", p
);
1344 if ((p
= getenv("HOME"))) *envptr
++ = alloc_env_string( "HOME=", p
);
1345 /* now put the Windows environment strings */
1346 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1348 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1349 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1350 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1351 *envptr
++ = alloc_env_string( "WINE", p
);
1361 /***********************************************************************
1364 * Fork and exec a new Unix binary, checking for errors.
1366 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
,
1367 const WCHAR
*env
, const char *newdir
)
1372 if (!env
) env
= GetEnvironmentStringsW();
1376 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1379 fcntl( fd
[1], F_SETFD
, 1 ); /* set close on exec */
1380 if (!(pid
= fork())) /* child */
1382 char **argv
= build_argv( cmdline
, 0 );
1383 char **envp
= build_envp( env
);
1386 /* Reset signals that we previously set to SIG_IGN */
1387 signal( SIGPIPE
, SIG_DFL
);
1388 signal( SIGCHLD
, SIG_DFL
);
1390 if (newdir
) chdir(newdir
);
1392 if (argv
&& envp
) execve( filename
, argv
, envp
);
1394 write( fd
[1], &err
, sizeof(err
) );
1398 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1403 if (pid
== -1) FILE_SetDosError();
1409 /***********************************************************************
1410 * create_user_params
1412 static RTL_USER_PROCESS_PARAMETERS
*create_user_params( LPCWSTR filename
, LPCWSTR cmdline
,
1413 LPCWSTR cur_dir
, LPWSTR env
,
1414 const STARTUPINFOW
*startup
)
1416 RTL_USER_PROCESS_PARAMETERS
*params
;
1417 UNICODE_STRING image_str
, cmdline_str
, curdir_str
, desktop
, title
, runtime
;
1419 WCHAR buffer
[MAX_PATH
];
1421 if(!GetLongPathNameW( filename
, buffer
, MAX_PATH
))
1422 lstrcpynW( buffer
, filename
, MAX_PATH
);
1423 if(!GetFullPathNameW( buffer
, MAX_PATH
, buffer
, NULL
))
1424 lstrcpynW( buffer
, filename
, MAX_PATH
);
1425 RtlInitUnicodeString( &image_str
, buffer
);
1427 RtlInitUnicodeString( &cmdline_str
, cmdline
);
1428 if (cur_dir
) RtlInitUnicodeString( &curdir_str
, cur_dir
);
1429 if (startup
->lpDesktop
) RtlInitUnicodeString( &desktop
, startup
->lpDesktop
);
1430 if (startup
->lpTitle
) RtlInitUnicodeString( &title
, startup
->lpTitle
);
1431 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1434 runtime
.MaximumLength
= startup
->cbReserved2
;
1435 runtime
.Buffer
= (WCHAR
*)startup
->lpReserved2
;
1438 status
= RtlCreateProcessParameters( ¶ms
, &image_str
, NULL
,
1439 cur_dir
? &curdir_str
: NULL
,
1441 startup
->lpTitle
? &title
: NULL
,
1442 startup
->lpDesktop
? &desktop
: NULL
,
1444 (startup
->lpReserved2
&& startup
->cbReserved2
) ? &runtime
: NULL
);
1445 if (status
!= STATUS_SUCCESS
)
1447 SetLastError( RtlNtStatusToDosError(status
) );
1451 params
->hStdInput
= startup
->hStdInput
;
1452 params
->hStdOutput
= startup
->hStdOutput
;
1453 params
->hStdError
= startup
->hStdError
;
1454 params
->dwX
= startup
->dwX
;
1455 params
->dwY
= startup
->dwY
;
1456 params
->dwXSize
= startup
->dwXSize
;
1457 params
->dwYSize
= startup
->dwYSize
;
1458 params
->dwXCountChars
= startup
->dwXCountChars
;
1459 params
->dwYCountChars
= startup
->dwYCountChars
;
1460 params
->dwFillAttribute
= startup
->dwFillAttribute
;
1461 params
->dwFlags
= startup
->dwFlags
;
1462 params
->wShowWindow
= startup
->wShowWindow
;
1467 /***********************************************************************
1470 * Create a new process. If hFile is a valid handle we have an exe
1471 * file, otherwise it is a Winelib app.
1473 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1474 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1475 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1476 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1477 void *res_start
, void *res_end
)
1479 BOOL ret
, success
= FALSE
;
1480 HANDLE process_info
;
1482 RTL_USER_PROCESS_PARAMETERS
*params
;
1488 char preloader_reserve
[64];
1490 if (!env
) RtlAcquirePebLock();
1492 if (!(params
= create_user_params( filename
, cmd_line
, cur_dir
, env
, startup
)))
1494 if (!env
) RtlReleasePebLock();
1497 env_end
= params
->Environment
;
1498 while (*env_end
) env_end
+= strlenW(env_end
) + 1;
1501 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx%c",
1502 (unsigned long)res_start
, (unsigned long)res_end
, 0 );
1504 /* create the synchronization pipes */
1506 if (pipe( startfd
) == -1)
1508 if (!env
) RtlReleasePebLock();
1509 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1510 RtlDestroyProcessParameters( params
);
1513 if (pipe( execfd
) == -1)
1515 if (!env
) RtlReleasePebLock();
1516 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1517 close( startfd
[0] );
1518 close( startfd
[1] );
1519 RtlDestroyProcessParameters( params
);
1522 fcntl( execfd
[1], F_SETFD
, 1 ); /* set close on exec */
1524 /* create the child process */
1526 if (!(pid
= fork())) /* child */
1528 char **argv
= build_argv( cmd_line
, 1 );
1530 close( startfd
[1] );
1533 /* wait for parent to tell us to start */
1534 if (read( startfd
[0], &dummy
, 1 ) != 1) _exit(1);
1536 close( startfd
[0] );
1537 /* Reset signals that we previously set to SIG_IGN */
1538 signal( SIGPIPE
, SIG_DFL
);
1539 signal( SIGCHLD
, SIG_DFL
);
1541 putenv( preloader_reserve
);
1542 if (unixdir
) chdir(unixdir
);
1546 /* first, try for a WINELOADER environment variable */
1547 const char *loader
= getenv("WINELOADER");
1548 if (loader
) wine_exec_wine_binary( loader
, argv
, NULL
, TRUE
);
1549 /* now use the standard search strategy */
1550 wine_exec_wine_binary( NULL
, argv
, NULL
, TRUE
);
1553 write( execfd
[1], &err
, sizeof(err
) );
1557 /* this is the parent */
1559 close( startfd
[0] );
1563 if (!env
) RtlReleasePebLock();
1564 close( startfd
[1] );
1567 RtlDestroyProcessParameters( params
);
1571 /* create the process on the server side */
1573 SERVER_START_REQ( new_process
)
1575 req
->inherit_all
= inherit
;
1576 req
->create_flags
= flags
;
1577 req
->unix_pid
= pid
;
1578 req
->exe_file
= hFile
;
1579 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1581 req
->hstdin
= startup
->hStdInput
;
1582 req
->hstdout
= startup
->hStdOutput
;
1583 req
->hstderr
= startup
->hStdError
;
1587 req
->hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1588 req
->hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1589 req
->hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1592 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1594 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1595 if (is_console_handle(req
->hstdin
)) req
->hstdin
= INVALID_HANDLE_VALUE
;
1596 if (is_console_handle(req
->hstdout
)) req
->hstdout
= INVALID_HANDLE_VALUE
;
1597 if (is_console_handle(req
->hstderr
)) req
->hstderr
= INVALID_HANDLE_VALUE
;
1601 if (is_console_handle(req
->hstdin
)) req
->hstdin
= console_handle_unmap(req
->hstdin
);
1602 if (is_console_handle(req
->hstdout
)) req
->hstdout
= console_handle_unmap(req
->hstdout
);
1603 if (is_console_handle(req
->hstderr
)) req
->hstderr
= console_handle_unmap(req
->hstderr
);
1606 wine_server_add_data( req
, params
, params
->Size
);
1607 wine_server_add_data( req
, params
->Environment
, (env_end
-params
->Environment
)*sizeof(WCHAR
) );
1608 ret
= !wine_server_call_err( req
);
1609 process_info
= reply
->info
;
1613 if (!env
) RtlReleasePebLock();
1614 RtlDestroyProcessParameters( params
);
1617 close( startfd
[1] );
1622 /* tell child to start and wait for it to exec */
1624 write( startfd
[1], &dummy
, 1 );
1625 close( startfd
[1] );
1627 if (read( execfd
[0], &err
, sizeof(err
) ) > 0) /* exec failed */
1632 CloseHandle( process_info
);
1637 /* wait for the new process info to be ready */
1639 WaitForSingleObject( process_info
, INFINITE
);
1640 SERVER_START_REQ( get_new_process_info
)
1642 req
->info
= process_info
;
1643 req
->pinherit
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
);
1644 req
->tinherit
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
);
1645 if ((ret
= !wine_server_call_err( req
)))
1647 info
->dwProcessId
= (DWORD
)reply
->pid
;
1648 info
->dwThreadId
= (DWORD
)reply
->tid
;
1649 info
->hProcess
= reply
->phandle
;
1650 info
->hThread
= reply
->thandle
;
1651 success
= reply
->success
;
1656 if (ret
&& !success
) /* new process failed to start */
1659 if (GetExitCodeProcess( info
->hProcess
, &exitcode
)) SetLastError( exitcode
);
1660 CloseHandle( info
->hThread
);
1661 CloseHandle( info
->hProcess
);
1664 CloseHandle( process_info
);
1669 /***********************************************************************
1670 * create_vdm_process
1672 * Create a new VDM process for a 16-bit or DOS application.
1674 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
1675 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1676 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1677 LPPROCESS_INFORMATION info
, LPCSTR unixdir
)
1679 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1682 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
1683 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
1687 SetLastError( ERROR_OUTOFMEMORY
);
1690 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
1691 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
1692 flags
, startup
, info
, unixdir
, NULL
, NULL
);
1693 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
1698 /***********************************************************************
1699 * create_cmd_process
1701 * Create a new cmd shell process for a .BAT file.
1703 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
1704 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1705 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1706 LPPROCESS_INFORMATION info
)
1709 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
1710 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
1711 WCHAR comspec
[MAX_PATH
];
1715 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
1717 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
1718 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
1721 strcpyW( newcmdline
, comspec
);
1722 strcatW( newcmdline
, slashcW
);
1723 strcatW( newcmdline
, cmd_line
);
1724 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
1725 flags
, env
, cur_dir
, startup
, info
);
1726 HeapFree( GetProcessHeap(), 0, newcmdline
);
1731 /*************************************************************************
1734 * Helper for CreateProcess: retrieve the file name to load from the
1735 * app name and command line. Store the file name in buffer, and
1736 * return a possibly modified command line.
1737 * Also returns a handle to the opened file if it's a Windows binary.
1739 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
1740 int buflen
, HANDLE
*handle
)
1742 static const WCHAR quotesW
[] = {'"','%','s','"',0};
1744 WCHAR
*name
, *pos
, *ret
= NULL
;
1747 /* if we have an app name, everything is easy */
1751 /* use the unmodified app name as file name */
1752 lstrcpynW( buffer
, appname
, buflen
);
1753 *handle
= open_exe_file( buffer
);
1754 if (!(ret
= cmdline
) || !cmdline
[0])
1756 /* no command-line, create one */
1757 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
1758 sprintfW( ret
, quotesW
, appname
);
1765 SetLastError( ERROR_INVALID_PARAMETER
);
1769 /* first check for a quoted file name */
1771 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
1773 int len
= p
- cmdline
- 1;
1774 /* extract the quoted portion as file name */
1775 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1776 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
1779 if (find_exe_file( name
, buffer
, buflen
, handle
))
1780 ret
= cmdline
; /* no change necessary */
1784 /* now try the command-line word by word */
1786 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
1793 do *pos
++ = *p
++; while (*p
&& *p
!= ' ');
1795 if (find_exe_file( name
, buffer
, buflen
, handle
))
1802 if (!ret
|| !strchrW( name
, ' ' )) goto done
; /* no change necessary */
1804 /* now build a new command-line with quotes */
1806 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
1808 sprintfW( ret
, quotesW
, name
);
1812 HeapFree( GetProcessHeap(), 0, name
);
1817 /**********************************************************************
1818 * CreateProcessA (KERNEL32.@)
1820 BOOL WINAPI
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1821 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
1822 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
1823 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
1826 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
1827 UNICODE_STRING desktopW
, titleW
;
1830 desktopW
.Buffer
= NULL
;
1831 titleW
.Buffer
= NULL
;
1832 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
1833 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
1834 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
1836 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
1837 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
1839 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
1840 infoW
.lpDesktop
= desktopW
.Buffer
;
1841 infoW
.lpTitle
= titleW
.Buffer
;
1843 if (startup_info
->lpReserved
)
1844 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1845 debugstr_a(startup_info
->lpReserved
));
1847 ret
= CreateProcessW( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
1848 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
1850 HeapFree( GetProcessHeap(), 0, app_nameW
);
1851 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
1852 HeapFree( GetProcessHeap(), 0, cur_dirW
);
1853 RtlFreeUnicodeString( &desktopW
);
1854 RtlFreeUnicodeString( &titleW
);
1859 /**********************************************************************
1860 * CreateProcessW (KERNEL32.@)
1862 BOOL WINAPI
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1863 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
1864 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
1865 LPPROCESS_INFORMATION info
)
1869 char *unixdir
= NULL
;
1870 WCHAR name
[MAX_PATH
];
1871 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
1872 void *res_start
, *res_end
;
1874 /* Process the AppName and/or CmdLine to get module name and path */
1876 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
1878 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
), &hFile
)))
1880 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
1882 /* Warn if unsupported features are used */
1884 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
1885 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
1886 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
1887 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
1888 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name
), flags
);
1892 unixdir
= wine_get_unix_file_name( cur_dir
);
1896 WCHAR buf
[MAX_PATH
];
1897 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
1900 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
1905 while (*p
) p
+= strlen(p
) + 1;
1906 p
++; /* final null */
1907 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
1908 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
1909 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
1910 flags
|= CREATE_UNICODE_ENVIRONMENT
;
1913 info
->hThread
= info
->hProcess
= 0;
1914 info
->dwProcessId
= info
->dwThreadId
= 0;
1916 /* Determine executable type */
1918 if (!hFile
) /* builtin exe */
1920 TRACE( "starting %s as Winelib app\n", debugstr_w(name
) );
1921 retv
= create_process( 0, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1922 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
);
1926 switch( MODULE_GetBinaryType( hFile
, &res_start
, &res_end
))
1929 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name
), res_start
, res_end
);
1930 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1931 inherit
, flags
, startup_info
, info
, unixdir
, res_start
, res_end
);
1936 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
1937 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1938 inherit
, flags
, startup_info
, info
, unixdir
);
1941 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
1942 SetLastError( ERROR_BAD_EXE_FORMAT
);
1944 case BINARY_UNIX_LIB
:
1945 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
1946 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1947 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
);
1949 case BINARY_UNKNOWN
:
1950 /* check for .com or .bat extension */
1951 if ((p
= strrchrW( name
, '.' )))
1953 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
1955 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
1956 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1957 inherit
, flags
, startup_info
, info
, unixdir
);
1960 if (!strcmpiW( p
, batW
))
1962 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
1963 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1964 inherit
, flags
, startup_info
, info
);
1969 case BINARY_UNIX_EXE
:
1971 /* unknown file, try as unix executable */
1974 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
1976 if ((unix_name
= wine_get_unix_file_name( name
)))
1978 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
) != -1);
1979 HeapFree( GetProcessHeap(), 0, unix_name
);
1984 CloseHandle( hFile
);
1987 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
1988 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
1989 HeapFree( GetProcessHeap(), 0, unixdir
);
1994 /***********************************************************************
1997 * Wrapper to call WaitForInputIdle USER function
1999 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2001 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2003 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2006 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2007 if (ptr
) return ptr( process
, timeout
);
2013 /***********************************************************************
2014 * WinExec (KERNEL32.@)
2016 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2018 PROCESS_INFORMATION info
;
2019 STARTUPINFOA startup
;
2023 memset( &startup
, 0, sizeof(startup
) );
2024 startup
.cb
= sizeof(startup
);
2025 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2026 startup
.wShowWindow
= nCmdShow
;
2028 /* cmdline needs to be writeable for CreateProcess */
2029 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2030 strcpy( cmdline
, lpCmdLine
);
2032 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2033 0, NULL
, NULL
, &startup
, &info
))
2035 /* Give 30 seconds to the app to come up */
2036 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2037 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2039 /* Close off the handles */
2040 CloseHandle( info
.hThread
);
2041 CloseHandle( info
.hProcess
);
2043 else if ((ret
= GetLastError()) >= 32)
2045 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2048 HeapFree( GetProcessHeap(), 0, cmdline
);
2053 /**********************************************************************
2054 * LoadModule (KERNEL32.@)
2056 HINSTANCE WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2058 LOADPARMS32
*params
= paramBlock
;
2059 PROCESS_INFORMATION info
;
2060 STARTUPINFOA startup
;
2061 HINSTANCE hInstance
;
2063 char filename
[MAX_PATH
];
2066 if (!name
) return (HINSTANCE
)ERROR_FILE_NOT_FOUND
;
2068 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2069 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2070 return (HINSTANCE
)GetLastError();
2072 len
= (BYTE
)params
->lpCmdLine
[0];
2073 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2074 return (HINSTANCE
)ERROR_NOT_ENOUGH_MEMORY
;
2076 strcpy( cmdline
, filename
);
2077 p
= cmdline
+ strlen(cmdline
);
2079 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2082 memset( &startup
, 0, sizeof(startup
) );
2083 startup
.cb
= sizeof(startup
);
2084 if (params
->lpCmdShow
)
2086 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2087 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2090 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2091 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2093 /* Give 30 seconds to the app to come up */
2094 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2095 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2096 hInstance
= (HINSTANCE
)33;
2097 /* Close off the handles */
2098 CloseHandle( info
.hThread
);
2099 CloseHandle( info
.hProcess
);
2101 else if ((hInstance
= (HINSTANCE
)GetLastError()) >= (HINSTANCE
)32)
2103 FIXME("Strange error set by CreateProcess: %p\n", hInstance
);
2104 hInstance
= (HINSTANCE
)11;
2107 HeapFree( GetProcessHeap(), 0, cmdline
);
2112 /******************************************************************************
2113 * TerminateProcess (KERNEL32.@)
2115 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2117 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2118 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2123 /***********************************************************************
2124 * ExitProcess (KERNEL32.@)
2126 void WINAPI
ExitProcess( DWORD status
)
2128 LdrShutdownProcess();
2129 SERVER_START_REQ( terminate_process
)
2131 /* send the exit code to the server */
2132 req
->handle
= GetCurrentProcess();
2133 req
->exit_code
= status
;
2134 wine_server_call( req
);
2141 /***********************************************************************
2142 * GetExitCodeProcess [KERNEL32.@]
2144 * Gets termination status of specified process
2150 BOOL WINAPI
GetExitCodeProcess(
2151 HANDLE hProcess
, /* [in] handle to the process */
2152 LPDWORD lpExitCode
) /* [out] address to receive termination status */
2155 PROCESS_BASIC_INFORMATION pbi
;
2157 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2159 if (status
== STATUS_SUCCESS
)
2161 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2164 SetLastError( RtlNtStatusToDosError(status
) );
2169 /***********************************************************************
2170 * SetErrorMode (KERNEL32.@)
2172 UINT WINAPI
SetErrorMode( UINT mode
)
2174 UINT old
= process_error_mode
;
2175 process_error_mode
= mode
;
2180 /**********************************************************************
2181 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2183 * Allocates a thread local storage index
2186 * Success: TLS Index
2187 * Failure: 0xFFFFFFFF
2189 DWORD WINAPI
TlsAlloc( void )
2192 PEB
* const peb
= NtCurrentTeb()->Peb
;
2194 RtlAcquirePebLock();
2195 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 0 );
2196 if (index
!= ~0UL) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2199 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2202 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2203 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2204 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2206 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2208 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2212 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2213 index
+= TLS_MINIMUM_AVAILABLE
;
2216 else SetLastError( ERROR_NO_MORE_ITEMS
);
2218 RtlReleasePebLock();
2223 /**********************************************************************
2224 * TlsFree [KERNEL32.@] Releases a TLS index.
2226 * Releases a thread local storage index, making it available for reuse
2232 BOOL WINAPI
TlsFree(
2233 DWORD index
) /* [in] TLS Index to free */
2237 RtlAcquirePebLock();
2238 if (index
>= TLS_MINIMUM_AVAILABLE
)
2240 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2241 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2245 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2246 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2248 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2249 else SetLastError( ERROR_INVALID_PARAMETER
);
2250 RtlReleasePebLock();
2255 /**********************************************************************
2256 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2259 * Success: Value stored in calling thread's TLS slot for index
2260 * Failure: 0 and GetLastError() returns NO_ERROR
2262 LPVOID WINAPI
TlsGetValue(
2263 DWORD index
) /* [in] TLS index to retrieve value for */
2267 if (index
< TLS_MINIMUM_AVAILABLE
)
2269 ret
= NtCurrentTeb()->TlsSlots
[index
];
2273 index
-= TLS_MINIMUM_AVAILABLE
;
2274 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2276 SetLastError( ERROR_INVALID_PARAMETER
);
2279 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2280 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2282 SetLastError( ERROR_SUCCESS
);
2287 /**********************************************************************
2288 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2294 BOOL WINAPI
TlsSetValue(
2295 DWORD index
, /* [in] TLS index to set value for */
2296 LPVOID value
) /* [in] Value to be stored */
2298 if (index
< TLS_MINIMUM_AVAILABLE
)
2300 NtCurrentTeb()->TlsSlots
[index
] = value
;
2304 index
-= TLS_MINIMUM_AVAILABLE
;
2305 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2307 SetLastError( ERROR_INVALID_PARAMETER
);
2310 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2311 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2312 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2314 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2317 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2323 /***********************************************************************
2324 * GetProcessFlags (KERNEL32.@)
2326 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2328 IMAGE_NT_HEADERS
*nt
;
2331 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2333 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2335 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2336 flags
|= PDB32_CONSOLE_PROC
;
2338 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2339 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2344 /***********************************************************************
2345 * GetProcessDword (KERNEL.485)
2346 * GetProcessDword (KERNEL32.18)
2347 * 'Of course you cannot directly access Windows internal structures'
2349 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
2354 TRACE("(%ld, %d)\n", dwProcessID
, offset
);
2356 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2358 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
2364 case GPD_APP_COMPAT_FLAGS
:
2365 return GetAppCompatFlags16(0);
2366 case GPD_LOAD_DONE_EVENT
:
2368 case GPD_HINSTANCE16
:
2369 return GetTaskDS16();
2370 case GPD_WINDOWS_VERSION
:
2371 return GetExeVersion16();
2373 return (DWORD
)NtCurrentTeb() - 0x10 /* FIXME */;
2375 return (DWORD
)NtCurrentTeb()->Peb
;
2376 case GPD_STARTF_SHELLDATA
: /* return stdoutput handle from startupinfo ??? */
2377 GetStartupInfoW(&siw
);
2378 return (DWORD
)siw
.hStdOutput
;
2379 case GPD_STARTF_HOTKEY
: /* return stdinput handle from startupinfo ??? */
2380 GetStartupInfoW(&siw
);
2381 return (DWORD
)siw
.hStdInput
;
2382 case GPD_STARTF_SHOWWINDOW
:
2383 GetStartupInfoW(&siw
);
2384 return siw
.wShowWindow
;
2385 case GPD_STARTF_SIZE
:
2386 GetStartupInfoW(&siw
);
2388 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2390 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2391 return MAKELONG( x
, y
);
2392 case GPD_STARTF_POSITION
:
2393 GetStartupInfoW(&siw
);
2395 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2397 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2398 return MAKELONG( x
, y
);
2399 case GPD_STARTF_FLAGS
:
2400 GetStartupInfoW(&siw
);
2405 return GetProcessFlags(0);
2407 return process_dword
;
2409 ERR("Unknown offset %d\n", offset
);
2414 /***********************************************************************
2415 * SetProcessDword (KERNEL.484)
2416 * 'Of course you cannot directly access Windows internal structures'
2418 void WINAPI
SetProcessDword( DWORD dwProcessID
, INT offset
, DWORD value
)
2420 TRACE("(%ld, %d)\n", dwProcessID
, offset
);
2422 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2424 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
2430 case GPD_APP_COMPAT_FLAGS
:
2431 case GPD_LOAD_DONE_EVENT
:
2432 case GPD_HINSTANCE16
:
2433 case GPD_WINDOWS_VERSION
:
2436 case GPD_STARTF_SHELLDATA
:
2437 case GPD_STARTF_HOTKEY
:
2438 case GPD_STARTF_SHOWWINDOW
:
2439 case GPD_STARTF_SIZE
:
2440 case GPD_STARTF_POSITION
:
2441 case GPD_STARTF_FLAGS
:
2444 ERR("Not allowed to modify offset %d\n", offset
);
2447 process_dword
= value
;
2450 ERR("Unknown offset %d\n", offset
);
2456 /***********************************************************************
2457 * ExitProcess (KERNEL.466)
2459 void WINAPI
ExitProcess16( WORD status
)
2462 ReleaseThunkLock( &count
);
2463 ExitProcess( status
);
2467 /*********************************************************************
2468 * OpenProcess (KERNEL32.@)
2470 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2473 SERVER_START_REQ( open_process
)
2476 req
->access
= access
;
2477 req
->inherit
= inherit
;
2478 if (!wine_server_call_err( req
)) ret
= reply
->handle
;
2485 /*********************************************************************
2486 * MapProcessHandle (KERNEL.483)
2487 * GetProcessId (KERNEL32.@)
2489 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2492 PROCESS_BASIC_INFORMATION pbi
;
2494 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2496 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2497 SetLastError( RtlNtStatusToDosError(status
) );
2502 /*********************************************************************
2503 * CloseW32Handle (KERNEL.474)
2504 * CloseHandle (KERNEL32.@)
2506 BOOL WINAPI
CloseHandle( HANDLE handle
)
2510 /* stdio handles need special treatment */
2511 if ((handle
== (HANDLE
)STD_INPUT_HANDLE
) ||
2512 (handle
== (HANDLE
)STD_OUTPUT_HANDLE
) ||
2513 (handle
== (HANDLE
)STD_ERROR_HANDLE
))
2514 handle
= GetStdHandle( (DWORD
)handle
);
2516 if (is_console_handle(handle
))
2517 return CloseConsoleHandle(handle
);
2519 status
= NtClose( handle
);
2520 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2525 /*********************************************************************
2526 * GetHandleInformation (KERNEL32.@)
2528 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2531 SERVER_START_REQ( set_handle_info
)
2533 req
->handle
= handle
;
2537 ret
= !wine_server_call_err( req
);
2538 if (ret
&& flags
) *flags
= reply
->old_flags
;
2545 /*********************************************************************
2546 * SetHandleInformation (KERNEL32.@)
2548 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2551 SERVER_START_REQ( set_handle_info
)
2553 req
->handle
= handle
;
2557 ret
= !wine_server_call_err( req
);
2564 /*********************************************************************
2565 * DuplicateHandle (KERNEL32.@)
2567 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2568 HANDLE dest_process
, HANDLE
*dest
,
2569 DWORD access
, BOOL inherit
, DWORD options
)
2573 if (is_console_handle(source
))
2575 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2576 if (source_process
!= dest_process
||
2577 source_process
!= GetCurrentProcess())
2579 SetLastError(ERROR_INVALID_PARAMETER
);
2582 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2583 return (*dest
!= INVALID_HANDLE_VALUE
);
2585 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2586 access
, inherit
? OBJ_INHERIT
: 0, options
);
2587 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2592 /***********************************************************************
2593 * ConvertToGlobalHandle (KERNEL.476)
2594 * ConvertToGlobalHandle (KERNEL32.@)
2596 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
2598 HANDLE ret
= INVALID_HANDLE_VALUE
;
2599 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
2600 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
2605 /***********************************************************************
2606 * SetHandleContext (KERNEL32.@)
2608 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
2610 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2611 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
2612 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2617 /***********************************************************************
2618 * GetHandleContext (KERNEL32.@)
2620 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
2622 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2623 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
2624 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2629 /***********************************************************************
2630 * CreateSocketHandle (KERNEL32.@)
2632 HANDLE WINAPI
CreateSocketHandle(void)
2634 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2635 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2636 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2637 return INVALID_HANDLE_VALUE
;
2641 /***********************************************************************
2642 * SetPriorityClass (KERNEL32.@)
2644 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
2647 SERVER_START_REQ( set_process_info
)
2649 req
->handle
= hprocess
;
2650 req
->priority
= priorityclass
;
2651 req
->mask
= SET_PROCESS_INFO_PRIORITY
;
2652 ret
= !wine_server_call_err( req
);
2659 /***********************************************************************
2660 * GetPriorityClass (KERNEL32.@)
2662 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
2665 PROCESS_BASIC_INFORMATION pbi
;
2667 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2669 if (status
== STATUS_SUCCESS
) return pbi
.BasePriority
;
2670 SetLastError( RtlNtStatusToDosError(status
) );
2675 /***********************************************************************
2676 * SetProcessAffinityMask (KERNEL32.@)
2678 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
2681 SERVER_START_REQ( set_process_info
)
2683 req
->handle
= hProcess
;
2684 req
->affinity
= affmask
;
2685 req
->mask
= SET_PROCESS_INFO_AFFINITY
;
2686 ret
= !wine_server_call_err( req
);
2693 /**********************************************************************
2694 * GetProcessAffinityMask (KERNEL32.@)
2696 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
2697 LPDWORD lpProcessAffinityMask
,
2698 LPDWORD lpSystemAffinityMask
)
2701 SERVER_START_REQ( get_process_info
)
2703 req
->handle
= hProcess
;
2704 if (!wine_server_call_err( req
))
2706 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= reply
->process_affinity
;
2707 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= reply
->system_affinity
;
2716 /***********************************************************************
2717 * GetProcessVersion (KERNEL32.@)
2719 DWORD WINAPI
GetProcessVersion( DWORD processid
)
2721 IMAGE_NT_HEADERS
*nt
;
2723 if (processid
&& processid
!= GetCurrentProcessId())
2725 FIXME("should use ReadProcessMemory\n");
2728 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2729 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
2730 nt
->OptionalHeader
.MinorSubsystemVersion
);
2735 /***********************************************************************
2736 * SetProcessWorkingSetSize [KERNEL32.@]
2737 * Sets the min/max working set sizes for a specified process.
2740 * hProcess [I] Handle to the process of interest
2741 * minset [I] Specifies minimum working set size
2742 * maxset [I] Specifies maximum working set size
2748 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
2751 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
2752 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
2753 /* Trim the working set to zero */
2754 /* Swap the process out of physical RAM */
2759 /***********************************************************************
2760 * GetProcessWorkingSetSize (KERNEL32.@)
2762 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
2765 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
2766 /* 32 MB working set size */
2767 if (minset
) *minset
= 32*1024*1024;
2768 if (maxset
) *maxset
= 32*1024*1024;
2773 /***********************************************************************
2774 * SetProcessShutdownParameters (KERNEL32.@)
2776 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
2778 FIXME("(%08lx, %08lx): partial stub.\n", level
, flags
);
2779 shutdown_flags
= flags
;
2780 shutdown_priority
= level
;
2785 /***********************************************************************
2786 * GetProcessShutdownParameters (KERNEL32.@)
2789 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
2791 *lpdwLevel
= shutdown_priority
;
2792 *lpdwFlags
= shutdown_flags
;
2797 /***********************************************************************
2798 * GetProcessPriorityBoost (KERNEL32.@)
2800 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
2802 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
2804 /* Report that no boost is present.. */
2805 *pDisablePriorityBoost
= FALSE
;
2810 /***********************************************************************
2811 * SetProcessPriorityBoost (KERNEL32.@)
2813 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
2815 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
2816 /* Say we can do it. I doubt the program will notice that we don't. */
2821 /***********************************************************************
2822 * ReadProcessMemory (KERNEL32.@)
2824 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
2825 SIZE_T
*bytes_read
)
2827 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
2828 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2833 /***********************************************************************
2834 * WriteProcessMemory (KERNEL32.@)
2836 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
2837 SIZE_T
*bytes_written
)
2839 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
2840 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2845 /****************************************************************************
2846 * FlushInstructionCache (KERNEL32.@)
2848 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
2851 if (GetVersion() & 0x80000000) return TRUE
; /* not NT, always TRUE */
2852 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
2853 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2858 /******************************************************************
2859 * GetProcessIoCounters (KERNEL32.@)
2861 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
2865 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
2866 ioc
, sizeof(*ioc
), NULL
);
2867 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2871 /***********************************************************************
2872 * ProcessIdToSessionId (KERNEL32.@)
2873 * This function is available on Terminal Server 4SP4 and Windows 2000
2875 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
2877 /* According to MSDN, if the calling process is not in a terminal
2878 * services environment, then the sessionid returned is zero.
2885 /***********************************************************************
2886 * RegisterServiceProcess (KERNEL.491)
2887 * RegisterServiceProcess (KERNEL32.@)
2889 * A service process calls this function to ensure that it continues to run
2890 * even after a user logged off.
2892 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
2894 /* I don't think that Wine needs to do anything in this function */
2895 return 1; /* success */
2899 /***********************************************************************
2900 * GetSystemMSecCount (SYSTEM.6)
2901 * GetTickCount (KERNEL32.@)
2903 * Get the number of milliseconds the system has been running.
2909 * The current tick count.
2912 * -The value returned will wrap arounf every 2^32 milliseconds.
2913 * -Under Windows, tick 0 is the moment at which the system is rebooted.
2914 * Under Wine, tick 0 begins at the moment the wineserver process is started,
2916 DWORD WINAPI
GetTickCount(void)
2919 gettimeofday( &t
, NULL
);
2920 return ((t
.tv_sec
* 1000) + (t
.tv_usec
/ 1000)) - server_startticks
;
2924 /***********************************************************************
2925 * GetCurrentProcess (KERNEL32.@)
2927 * Get a handle to the current process.
2933 * A handle representing the current process.
2935 #undef GetCurrentProcess
2936 HANDLE WINAPI
GetCurrentProcess(void)
2938 return (HANDLE
)0xffffffff;