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"
43 #include "kernel_private.h"
44 #include "wine/exception.h"
45 #include "wine/server.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(process
);
50 WINE_DECLARE_DEBUG_CHANNEL(file
);
51 WINE_DECLARE_DEBUG_CHANNEL(server
);
52 WINE_DECLARE_DEBUG_CHANNEL(relay
);
62 static UINT process_error_mode
;
64 static HANDLE main_exe_file
;
65 static DWORD shutdown_flags
= 0;
66 static DWORD shutdown_priority
= 0x280;
67 static DWORD process_dword
;
69 static unsigned int server_startticks
;
70 int main_create_flags
= 0;
71 HMODULE kernel32_handle
= 0;
73 const WCHAR
*DIR_Windows
= NULL
;
74 const WCHAR
*DIR_System
= NULL
;
77 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
78 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
79 #define PDB32_DOS_PROC 0x0010 /* Dos process */
80 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
81 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
82 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
84 static const WCHAR comW
[] = {'.','c','o','m',0};
85 static const WCHAR batW
[] = {'.','b','a','t',0};
86 static const WCHAR pifW
[] = {'.','p','i','f',0};
87 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
89 extern void SHELL_LoadRegistry(void);
90 extern void convert_old_config(void);
91 extern void VERSION_Init( const WCHAR
*appname
);
92 extern void LOCALE_Init(void);
94 /***********************************************************************
97 inline static int contains_path( LPCWSTR name
)
99 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
103 /***********************************************************************
106 * Check if an environment variable needs to be handled specially when
107 * passed through the Unix environment (i.e. prefixed with "WINE").
109 inline static int is_special_env_var( const char *var
)
111 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
112 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
113 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
114 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
118 /***************************************************************************
121 * Get the path of a builtin module when the native file does not exist.
123 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
, UINT size
)
126 UINT len
= strlenW( DIR_System
);
128 if (contains_path( libname
))
130 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
131 filename
, &file_part
) > size
* sizeof(WCHAR
))
132 return FALSE
; /* too long */
134 if (strncmpiW( filename
, DIR_System
, len
) || filename
[len
] != '\\')
136 while (filename
[len
] == '\\') len
++;
137 if (filename
+ len
!= file_part
) return FALSE
;
141 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
142 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
143 file_part
= filename
+ len
;
144 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
145 strcpyW( file_part
, libname
);
147 if (ext
&& !strchrW( file_part
, '.' ))
149 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
150 return FALSE
; /* too long */
151 strcatW( file_part
, ext
);
157 /***********************************************************************
158 * open_builtin_exe_file
160 * Open an exe file for a builtin exe.
162 static void *open_builtin_exe_file( const WCHAR
*name
, char *error
, int error_size
,
163 int test_only
, int *file_exists
)
165 char exename
[MAX_PATH
];
169 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
170 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
172 /* we don't want to depend on the current codepage here */
173 len
= strlenW( name
) + 1;
174 if (len
>= sizeof(exename
)) return NULL
;
175 for (i
= 0; i
< len
; i
++)
177 if (name
[i
] > 127) return NULL
;
178 exename
[i
] = (char)name
[i
];
179 if (exename
[i
] >= 'A' && exename
[i
] <= 'Z') exename
[i
] += 'a' - 'A';
181 return wine_dll_load_main_exe( exename
, error
, error_size
, test_only
, file_exists
);
185 /***********************************************************************
188 * Open a specific exe file, taking load order into account.
189 * Returns the file handle or 0 for a builtin exe.
191 static HANDLE
open_exe_file( const WCHAR
*name
)
193 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
194 WCHAR buffer
[MAX_PATH
];
198 TRACE("looking for %s\n", debugstr_w(name
) );
200 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
201 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
203 /* file doesn't exist, check for builtin */
204 if (!contains_path( name
)) goto error
;
205 if (!get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
) )) goto error
;
209 MODULE_GetLoadOrderW( loadorder
, NULL
, name
);
211 for(i
= 0; i
< LOADORDER_NTYPES
; i
++)
213 if (loadorder
[i
] == LOADORDER_INVALID
) break;
217 TRACE( "Trying native exe %s\n", debugstr_w(name
) );
218 if (handle
!= INVALID_HANDLE_VALUE
) return handle
;
221 TRACE( "Trying built-in exe %s\n", debugstr_w(name
) );
222 open_builtin_exe_file( name
, NULL
, 0, 1, &file_exists
);
225 if (handle
!= INVALID_HANDLE_VALUE
) CloseHandle(handle
);
232 if (handle
!= INVALID_HANDLE_VALUE
) CloseHandle(handle
);
235 SetLastError( ERROR_FILE_NOT_FOUND
);
236 return INVALID_HANDLE_VALUE
;
240 /***********************************************************************
243 * Open an exe file, and return the full name and file handle.
244 * Returns FALSE if file could not be found.
245 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
246 * If file is a builtin exe, returns TRUE and sets handle to 0.
248 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
, HANDLE
*handle
)
250 static const WCHAR exeW
[] = {'.','e','x','e',0};
252 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
255 TRACE("looking for %s\n", debugstr_w(name
) );
257 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
) &&
258 !get_builtin_path( name
, exeW
, buffer
, buflen
))
260 /* no builtin found, try native without extension in case it is a Unix app */
262 if (SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
))
264 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer
) );
265 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
266 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
272 MODULE_GetLoadOrderW( loadorder
, NULL
, buffer
);
274 for(i
= 0; i
< LOADORDER_NTYPES
; i
++)
276 if (loadorder
[i
] == LOADORDER_INVALID
) break;
280 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
281 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_DELETE
,
282 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
284 if (GetLastError() != ERROR_FILE_NOT_FOUND
) return TRUE
;
287 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer
) );
288 open_builtin_exe_file( buffer
, NULL
, 0, 1, &file_exists
);
299 SetLastError( ERROR_FILE_NOT_FOUND
);
304 /**********************************************************************
307 * Load a PE format EXE file.
309 static HMODULE
load_pe_exe( const WCHAR
*name
, HANDLE file
)
312 FILE_FS_DEVICE_INFORMATION device_info
;
313 IMAGE_NT_HEADERS
*nt
;
316 OBJECT_ATTRIBUTES attr
;
320 attr
.Length
= sizeof(attr
);
321 attr
.RootDirectory
= 0;
322 attr
.ObjectName
= NULL
;
324 attr
.SecurityDescriptor
= NULL
;
325 attr
.SecurityQualityOfService
= NULL
;
328 if (NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
329 &attr
, &size
, 0, SEC_IMAGE
, file
) != STATUS_SUCCESS
)
333 if (NtMapViewOfSection( mapping
, GetCurrentProcess(), &module
, 0, 0, &size
, &len
,
334 ViewShare
, 0, PAGE_READONLY
) != STATUS_SUCCESS
)
340 nt
= RtlImageNtHeader( module
);
341 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
343 if (!RtlImageRvaToSection( nt
, module
, nt
->OptionalHeader
.AddressOfEntryPoint
))
344 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
345 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
346 debugstr_w(name
), nt
->OptionalHeader
.AddressOfEntryPoint
);
349 if (NtQueryVolumeInformationFile( file
, &io
, &device_info
, sizeof(device_info
),
350 FileFsDeviceInformation
) == STATUS_SUCCESS
)
352 /* don't keep the file handle open on removable media */
353 if (device_info
.Characteristics
& FILE_REMOVABLE_MEDIA
)
355 CloseHandle( main_exe_file
);
363 /***********************************************************************
364 * build_initial_environment
366 * Build the Win32 environment from the Unix environment
368 static BOOL
build_initial_environment( char **environ
)
375 /* Compute the total size of the Unix environment */
376 for (e
= environ
; *e
; e
++)
378 if (is_special_env_var( *e
)) continue;
379 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
381 size
*= sizeof(WCHAR
);
383 /* Now allocate the environment */
385 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
386 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
389 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
390 endptr
= p
+ size
/ sizeof(WCHAR
);
392 /* And fill it with the Unix environment */
393 for (e
= environ
; *e
; e
++)
397 /* skip Unix special variables and use the Wine variants instead */
398 if (!strncmp( str
, "WINE", 4 ))
400 if (is_special_env_var( str
+ 4 )) str
+= 4;
401 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
403 else if (is_special_env_var( str
)) continue; /* skip it */
405 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
413 /***********************************************************************
414 * set_registry_variables
416 * Set environment variables by enumerating the values of a key;
417 * helper for set_registry_environment().
418 * Note that Windows happily truncates the value if it's too big.
420 static void set_registry_variables( HKEY hkey
, ULONG type
)
422 UNICODE_STRING env_name
, env_value
;
426 char buffer
[1024*sizeof(WCHAR
) + sizeof(KEY_VALUE_FULL_INFORMATION
)];
427 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
429 for (index
= 0; ; index
++)
431 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
432 buffer
, sizeof(buffer
), &size
);
433 if (status
!= STATUS_SUCCESS
&& status
!= STATUS_BUFFER_OVERFLOW
)
435 if (info
->Type
!= type
)
437 env_name
.Buffer
= info
->Name
;
438 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
439 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
440 env_value
.Length
= env_value
.MaximumLength
= info
->DataLength
;
441 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
442 env_value
.Length
--; /* don't count terminating null if any */
443 if (info
->Type
== REG_EXPAND_SZ
)
445 WCHAR buf_expanded
[1024];
446 UNICODE_STRING env_expanded
;
447 env_expanded
.Length
= env_expanded
.MaximumLength
= sizeof(buf_expanded
);
448 env_expanded
.Buffer
=buf_expanded
;
449 status
= RtlExpandEnvironmentStrings_U(NULL
, &env_value
, &env_expanded
, NULL
);
450 if (status
== STATUS_SUCCESS
|| status
== STATUS_BUFFER_OVERFLOW
)
451 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_expanded
);
455 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
461 /***********************************************************************
462 * set_registry_environment
464 * Set the environment variables specified in the registry.
466 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
467 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
468 * on the order in which the variables are processed. But on Windows it
469 * does not really matter since they only use %SystemDrive% and
470 * %SystemRoot% which are predefined. But Wine defines these in the
471 * registry, so we need two passes.
473 static void set_registry_environment(void)
475 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
476 'S','y','s','t','e','m','\\',
477 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
478 'C','o','n','t','r','o','l','\\',
479 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
480 'E','n','v','i','r','o','n','m','e','n','t',0};
481 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
483 OBJECT_ATTRIBUTES attr
;
484 UNICODE_STRING nameW
;
487 attr
.Length
= sizeof(attr
);
488 attr
.RootDirectory
= 0;
489 attr
.ObjectName
= &nameW
;
491 attr
.SecurityDescriptor
= NULL
;
492 attr
.SecurityQualityOfService
= NULL
;
494 /* first the system environment variables */
495 RtlInitUnicodeString( &nameW
, env_keyW
);
496 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
498 set_registry_variables( hkey
, REG_SZ
);
499 set_registry_variables( hkey
, REG_EXPAND_SZ
);
503 /* then the ones for the current user */
504 if (RtlOpenCurrentUser( KEY_ALL_ACCESS
, (HKEY
*)&attr
.RootDirectory
) != STATUS_SUCCESS
) return;
505 RtlInitUnicodeString( &nameW
, envW
);
506 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
508 set_registry_variables( hkey
, REG_SZ
);
509 set_registry_variables( hkey
, REG_EXPAND_SZ
);
512 NtClose( attr
.RootDirectory
);
516 /***********************************************************************
519 * Set the Wine library Unicode argv global variables.
521 static void set_library_wargv( char **argv
)
529 for (argc
= 0; argv
[argc
]; argc
++)
530 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
532 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
533 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
534 p
= (WCHAR
*)(wargv
+ argc
+ 1);
535 for (argc
= 0; argv
[argc
]; argc
++)
537 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
544 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
546 for (argc
= 0; wargv
[argc
]; argc
++)
547 total
+= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, NULL
, 0, NULL
, NULL
);
549 argv
= RtlAllocateHeap( GetProcessHeap(), 0, total
+ (argc
+ 1) * sizeof(*argv
) );
550 q
= (char *)(argv
+ argc
+ 1);
551 for (argc
= 0; wargv
[argc
]; argc
++)
553 DWORD reslen
= WideCharToMultiByte( CP_ACP
, 0, wargv
[argc
], -1, q
, total
, NULL
, NULL
);
560 __wine_main_argv
= argv
;
561 __wine_main_wargv
= wargv
;
565 /***********************************************************************
568 * Build the command line of a process from the argv array.
570 * Note that it does NOT necessarily include the file name.
571 * Sometimes we don't even have any command line options at all.
573 * We must quote and escape characters so that the argv array can be rebuilt
574 * from the command line:
575 * - spaces and tabs must be quoted
577 * - quotes must be escaped
579 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
580 * resulting in an odd number of '\' followed by a '"'
583 * - '\'s that are not followed by a '"' can be left as is
587 static BOOL
build_command_line( WCHAR
**argv
)
592 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
594 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
597 for (arg
= argv
; *arg
; arg
++)
599 int has_space
,bcount
;
605 if( !*a
) has_space
=1;
610 if (*a
==' ' || *a
=='\t') {
612 } else if (*a
=='"') {
613 /* doubling of '\' preceding a '"',
614 * plus escaping of said '"'
622 len
+=(a
-*arg
)+1 /* for the separating space */;
624 len
+=2; /* for the quotes */
627 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
630 p
= rupp
->CommandLine
.Buffer
;
631 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
632 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
633 for (arg
= argv
; *arg
; arg
++)
635 int has_space
,has_quote
;
638 /* Check for quotes and spaces in this argument */
639 has_space
=has_quote
=0;
641 if( !*a
) has_space
=1;
643 if (*a
==' ' || *a
=='\t') {
647 } else if (*a
=='"') {
655 /* Now transfer it to the command line */
672 /* Double all the '\\' preceding this '"', plus one */
673 for (i
=0;i
<=bcount
;i
++)
685 while ((*p
=*x
++)) p
++;
691 if (p
> rupp
->CommandLine
.Buffer
)
692 p
--; /* remove last space */
699 /* make sure the unicode string doesn't point beyond the end pointer */
700 static inline void fix_unicode_string( UNICODE_STRING
*str
, char *end_ptr
)
702 if ((char *)str
->Buffer
>= end_ptr
)
704 str
->Length
= str
->MaximumLength
= 0;
708 if ((char *)str
->Buffer
+ str
->MaximumLength
> end_ptr
)
710 str
->MaximumLength
= (end_ptr
- (char *)str
->Buffer
) & ~(sizeof(WCHAR
) - 1);
712 if (str
->Length
>= str
->MaximumLength
)
714 if (str
->MaximumLength
>= sizeof(WCHAR
))
715 str
->Length
= str
->MaximumLength
- sizeof(WCHAR
);
717 str
->Length
= str
->MaximumLength
= 0;
721 static void version(void)
723 MESSAGE( "%s\n", PACKAGE_STRING
);
727 static void usage(void)
729 MESSAGE( "%s\n", PACKAGE_STRING
);
730 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
731 MESSAGE( " wine --help Display this help and exit\n");
732 MESSAGE( " wine --version Output version information and exit\n");
737 /***********************************************************************
738 * init_user_process_params
740 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
742 static RTL_USER_PROCESS_PARAMETERS
*init_user_process_params( size_t info_size
)
745 DWORD size
, env_size
;
746 RTL_USER_PROCESS_PARAMETERS
*params
;
750 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0, &size
,
751 MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
754 SERVER_START_REQ( get_startup_info
)
756 wine_server_set_reply( req
, ptr
, info_size
);
757 wine_server_call( req
);
758 info_size
= wine_server_reply_size( reply
);
763 params
->AllocationSize
= size
;
764 if (params
->Size
> info_size
) params
->Size
= info_size
;
766 /* make sure the strings are valid */
767 fix_unicode_string( ¶ms
->CurrentDirectory
.DosPath
, (char *)info_size
);
768 fix_unicode_string( ¶ms
->DllPath
, (char *)info_size
);
769 fix_unicode_string( ¶ms
->ImagePathName
, (char *)info_size
);
770 fix_unicode_string( ¶ms
->CommandLine
, (char *)info_size
);
771 fix_unicode_string( ¶ms
->WindowTitle
, (char *)info_size
);
772 fix_unicode_string( ¶ms
->Desktop
, (char *)info_size
);
773 fix_unicode_string( ¶ms
->ShellInfo
, (char *)info_size
);
774 fix_unicode_string( ¶ms
->RuntimeInfo
, (char *)info_size
);
776 /* environment needs to be a separate memory block */
777 env_size
= info_size
- params
->Size
;
778 if (!env_size
) env_size
= 1;
780 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0, &env_size
,
781 MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
783 memcpy( ptr
, (char *)params
+ params
->Size
, info_size
- params
->Size
);
784 params
->Environment
= ptr
;
786 return RtlNormalizeProcessParams( params
);
790 /***********************************************************************
791 * init_current_directory
793 * Initialize the current directory from the Unix cwd or the parent info.
795 static void init_current_directory( CURDIR
*cur_dir
)
797 UNICODE_STRING dir_str
;
801 /* if we received a cur dir from the parent, try this first */
803 if (cur_dir
->DosPath
.Length
)
805 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
808 /* now try to get it from the Unix cwd */
810 for (size
= 256; ; size
*= 2)
812 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
813 if (getcwd( cwd
, size
)) break;
814 HeapFree( GetProcessHeap(), 0, cwd
);
815 if (errno
== ERANGE
) continue;
823 int lenW
= MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, NULL
, 0 );
824 if ((dirW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) )))
826 MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, dirW
, lenW
);
827 RtlInitUnicodeString( &dir_str
, dirW
);
828 RtlSetCurrentDirectory_U( &dir_str
);
829 RtlFreeUnicodeString( &dir_str
);
833 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
835 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
836 "starting in the Windows directory.\n", cwd
? cwd
: "" );
837 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
838 RtlSetCurrentDirectory_U( &dir_str
);
840 HeapFree( GetProcessHeap(), 0, cwd
);
843 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
844 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
848 /***********************************************************************
851 * Initialize the windows and system directories from the environment.
853 static void init_windows_dirs(void)
855 extern void __wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
857 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
858 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
859 static const WCHAR default_windirW
[] = {'c',':','\\','w','i','n','d','o','w','s',0};
860 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m',0};
865 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
867 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
868 GetEnvironmentVariableW( windirW
, buffer
, len
);
869 DIR_Windows
= buffer
;
871 else DIR_Windows
= default_windirW
;
873 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
875 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
876 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
881 len
= strlenW( DIR_Windows
);
882 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
883 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
884 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
888 if (GetFileAttributesW( DIR_Windows
) == INVALID_FILE_ATTRIBUTES
)
889 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
890 debugstr_w(DIR_Windows
) );
891 if (GetFileAttributesW( DIR_System
) == INVALID_FILE_ATTRIBUTES
)
892 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
893 debugstr_w(DIR_System
) );
895 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
896 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
898 /* set the directories in ntdll too */
899 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
903 /***********************************************************************
906 * Main process initialisation code
908 static BOOL
process_init(void)
910 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
912 size_t info_size
= 0;
913 RTL_USER_PROCESS_PARAMETERS
*params
;
914 PEB
*peb
= NtCurrentTeb()->Peb
;
915 HANDLE hstdin
, hstdout
, hstderr
;
916 extern void __wine_dbg_kernel32_init(void);
920 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
924 setlocale(LC_CTYPE
,"");
926 /* Retrieve startup info from the server */
927 SERVER_START_REQ( init_process
)
930 req
->ldt_copy
= &wine_ldt_copy
;
931 if ((ret
= !wine_server_call_err( req
)))
933 main_exe_file
= reply
->exe_file
;
934 main_create_flags
= reply
->create_flags
;
935 info_size
= reply
->info_size
;
936 server_startticks
= reply
->server_start
;
937 hstdin
= reply
->hstdin
;
938 hstdout
= reply
->hstdout
;
939 hstderr
= reply
->hstderr
;
943 if (!ret
) return FALSE
;
947 params
= peb
->ProcessParameters
;
949 /* This is wine specific: we have no parent (we're started from unix)
950 * so, create a simple console with bare handles to unix stdio
951 * input & output streams (aka simple console)
953 wine_server_fd_to_handle( 0, GENERIC_READ
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdInput
);
954 wine_server_fd_to_handle( 1, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdOutput
);
955 wine_server_fd_to_handle( 2, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdError
);
957 params
->CurrentDirectory
.DosPath
.Length
= 0;
958 params
->CurrentDirectory
.DosPath
.MaximumLength
= RtlGetLongestNtPathLength() * sizeof(WCHAR
);
959 params
->CurrentDirectory
.DosPath
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, params
->CurrentDirectory
.DosPath
.MaximumLength
);
963 if (!(params
= init_user_process_params( info_size
))) return FALSE
;
964 peb
->ProcessParameters
= params
;
966 /* convert value from server:
967 * + 0 => INVALID_HANDLE_VALUE
968 * + console handle need to be mapped
971 hstdin
= INVALID_HANDLE_VALUE
;
972 else if (VerifyConsoleIoHandle(console_handle_map(hstdin
)))
973 hstdin
= console_handle_map(hstdin
);
976 hstdout
= INVALID_HANDLE_VALUE
;
977 else if (VerifyConsoleIoHandle(console_handle_map(hstdout
)))
978 hstdout
= console_handle_map(hstdout
);
981 hstderr
= INVALID_HANDLE_VALUE
;
982 else if (VerifyConsoleIoHandle(console_handle_map(hstderr
)))
983 hstderr
= console_handle_map(hstderr
);
985 params
->hStdInput
= hstdin
;
986 params
->hStdOutput
= hstdout
;
987 params
->hStdError
= hstderr
;
990 kernel32_handle
= GetModuleHandleW(kernel32W
);
996 /* Copy the parent environment */
997 if (!build_initial_environment( __wine_main_environ
)) return FALSE
;
999 /* convert old configuration to new format */
1000 convert_old_config();
1002 /* global boot finished, the rest is process-local */
1003 SERVER_START_REQ( boot_done
)
1005 req
->debug_level
= TRACE_ON(server
);
1006 wine_server_call( req
);
1010 set_registry_environment();
1013 init_windows_dirs();
1014 init_current_directory( ¶ms
->CurrentDirectory
);
1020 /***********************************************************************
1023 * Startup routine of a new process. Runs on the new process stack.
1025 static void start_process( void *arg
)
1029 PEB
*peb
= NtCurrentTeb()->Peb
;
1030 IMAGE_NT_HEADERS
*nt
;
1031 LPTHREAD_START_ROUTINE entry
;
1033 LdrInitializeThunk( main_exe_file
, 0, 0, 0 );
1035 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1036 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
1037 nt
->OptionalHeader
.AddressOfEntryPoint
);
1039 if (TRACE_ON(relay
))
1040 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1041 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
1043 SetLastError( 0 ); /* clear error code */
1044 if (peb
->BeingDebugged
) DbgBreakPoint();
1045 ExitProcess( entry( peb
) );
1047 __EXCEPT(UnhandledExceptionFilter
)
1049 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1055 /***********************************************************************
1056 * __wine_kernel_init
1058 * Wine initialisation: load and start the main exe file.
1060 void __wine_kernel_init(void)
1062 WCHAR
*main_exe_name
, *p
;
1064 DWORD stack_size
= 0;
1066 PEB
*peb
= NtCurrentTeb()->Peb
;
1068 /* Initialize everything */
1069 if (!process_init()) exit(1);
1071 __wine_main_argv
++; /* remove argv[0] (wine itself) */
1074 if (!(main_exe_name
= peb
->ProcessParameters
->ImagePathName
.Buffer
))
1076 WCHAR buffer
[MAX_PATH
];
1077 WCHAR exe_nameW
[MAX_PATH
];
1079 if (!__wine_main_argv
[0]) usage();
1080 if (__wine_main_argc
== 1)
1082 if (strcmp(__wine_main_argv
[0], "--help") == 0) usage();
1083 if (strcmp(__wine_main_argv
[0], "--version") == 0) version();
1086 MultiByteToWideChar( CP_UNIXCP
, 0, __wine_main_argv
[0], -1, exe_nameW
, MAX_PATH
);
1087 if (!find_exe_file( exe_nameW
, buffer
, MAX_PATH
, &main_exe_file
))
1089 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1092 if (main_exe_file
== INVALID_HANDLE_VALUE
)
1094 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name
) );
1097 RtlCreateUnicodeString( &peb
->ProcessParameters
->ImagePathName
, buffer
);
1098 main_exe_name
= peb
->ProcessParameters
->ImagePathName
.Buffer
;
1101 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1102 debugstr_w(main_exe_name
), main_exe_file
, debugstr_a(__wine_main_argv
[0]) );
1104 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1105 MODULE_get_dll_load_path(NULL
) );
1106 VERSION_Init( main_exe_name
);
1108 if (!main_exe_file
) /* no file handle -> Winelib app */
1110 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name
) );
1111 if (open_builtin_exe_file( main_exe_name
, error
, sizeof(error
), 0, &file_exists
))
1113 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1114 debugstr_w(main_exe_name
), error
);
1118 switch( MODULE_GetBinaryType( main_exe_file
, NULL
, NULL
))
1121 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name
) );
1122 if ((peb
->ImageBaseAddress
= load_pe_exe( main_exe_name
, main_exe_file
)))
1124 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name
) );
1127 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name
) );
1129 case BINARY_UNKNOWN
:
1130 /* check for .com extension */
1131 if (!(p
= strrchrW( main_exe_name
, '.' )) || strcmpiW( p
, comW
))
1133 MESSAGE( "wine: cannot determine executable type for %s\n",
1134 debugstr_w(main_exe_name
) );
1141 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name
) );
1142 CloseHandle( main_exe_file
);
1146 __wine_main_argv
[0] = "winevdm.exe";
1147 if (open_builtin_exe_file( winevdmW
, error
, sizeof(error
), 0, &file_exists
))
1149 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1150 debugstr_w(main_exe_name
), error
);
1152 case BINARY_UNIX_EXE
:
1153 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name
) );
1155 case BINARY_UNIX_LIB
:
1159 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name
) );
1160 CloseHandle( main_exe_file
);
1162 if ((unix_name
= wine_get_unix_file_name( main_exe_name
)) &&
1163 wine_dlopen( unix_name
, RTLD_NOW
, error
, sizeof(error
) ))
1165 static const WCHAR soW
[] = {'.','s','o',0};
1166 if ((p
= strrchrW( main_exe_name
, '.' )) && !strcmpW( p
, soW
))
1169 /* update the unicode string */
1170 RtlInitUnicodeString( &peb
->ProcessParameters
->ImagePathName
, main_exe_name
);
1172 HeapFree( GetProcessHeap(), 0, unix_name
);
1175 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name
), error
);
1181 /* build command line */
1182 set_library_wargv( __wine_main_argv
);
1183 if (!build_command_line( __wine_main_wargv
)) goto error
;
1185 stack_size
= RtlImageNtHeader(peb
->ImageBaseAddress
)->OptionalHeader
.SizeOfStackReserve
;
1187 /* allocate main thread stack */
1188 if (!THREAD_InitStack( NtCurrentTeb(), stack_size
)) goto error
;
1190 /* switch to the new stack */
1191 wine_switch_to_stack( start_process
, NULL
, NtCurrentTeb()->Tib
.StackBase
);
1194 ExitProcess( GetLastError() );
1198 /***********************************************************************
1201 * Build an argv array from a command-line.
1202 * 'reserved' is the number of args to reserve before the first one.
1204 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1208 char *arg
,*s
,*d
,*cmdline
;
1209 int in_quotes
,bcount
,len
;
1211 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1212 if (!(cmdline
= malloc(len
))) return NULL
;
1213 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1220 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1223 /* skip the remaining spaces */
1224 while (*s
==' ' || *s
=='\t') {
1231 } else if (*s
=='\\') {
1232 /* '\', count them */
1234 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1236 in_quotes
=!in_quotes
;
1239 /* a regular character */
1244 argv
=malloc(argc
*sizeof(*argv
));
1253 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1254 /* Close the argument and copy it */
1258 /* skip the remaining spaces */
1261 } while (*s
==' ' || *s
=='\t');
1263 /* Start with a new argument */
1266 } else if (*s
=='\\') {
1270 } else if (*s
=='"') {
1272 if ((bcount
& 1)==0) {
1273 /* Preceded by an even number of '\', this is half that
1274 * number of '\', plus a '"' which we discard.
1278 in_quotes
=!in_quotes
;
1280 /* Preceded by an odd number of '\', this is half that
1281 * number of '\' followed by a '"'
1289 /* a regular character */
1304 /***********************************************************************
1307 * Allocate an environment string; helper for build_envp
1309 static char *alloc_env_string( const char *name
, const char *value
)
1311 char *ret
= malloc( strlen(name
) + strlen(value
) + 1 );
1312 strcpy( ret
, name
);
1313 strcat( ret
, value
);
1317 /***********************************************************************
1320 * Build the environment of a new child process.
1322 static char **build_envp( const WCHAR
*envW
)
1327 int count
= 0, length
;
1329 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1331 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1332 if (!(env
= malloc( length
))) return NULL
;
1333 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1337 if ((envp
= malloc( count
* sizeof(*envp
) )))
1339 char **envptr
= envp
;
1341 /* some variables must not be modified, so we get them directly from the unix env */
1342 if ((p
= getenv("PATH"))) *envptr
++ = alloc_env_string( "PATH=", p
);
1343 if ((p
= getenv("TEMP"))) *envptr
++ = alloc_env_string( "TEMP=", p
);
1344 if ((p
= getenv("TMP"))) *envptr
++ = alloc_env_string( "TMP=", p
);
1345 if ((p
= getenv("HOME"))) *envptr
++ = alloc_env_string( "HOME=", p
);
1346 /* now put the Windows environment strings */
1347 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1349 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1350 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1351 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1352 *envptr
++ = alloc_env_string( "WINE", p
);
1362 /***********************************************************************
1365 * Fork and exec a new Unix binary, checking for errors.
1367 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
,
1368 const WCHAR
*env
, const char *newdir
)
1373 if (!env
) env
= GetEnvironmentStringsW();
1377 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1380 fcntl( fd
[1], F_SETFD
, 1 ); /* set close on exec */
1381 if (!(pid
= fork())) /* child */
1383 char **argv
= build_argv( cmdline
, 0 );
1384 char **envp
= build_envp( env
);
1387 /* Reset signals that we previously set to SIG_IGN */
1388 signal( SIGPIPE
, SIG_DFL
);
1389 signal( SIGCHLD
, SIG_DFL
);
1391 if (newdir
) chdir(newdir
);
1393 if (argv
&& envp
) execve( filename
, argv
, envp
);
1395 write( fd
[1], &err
, sizeof(err
) );
1399 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1404 if (pid
== -1) FILE_SetDosError();
1410 /***********************************************************************
1411 * create_user_params
1413 static RTL_USER_PROCESS_PARAMETERS
*create_user_params( LPCWSTR filename
, LPCWSTR cmdline
,
1414 LPCWSTR cur_dir
, LPWSTR env
,
1415 const STARTUPINFOW
*startup
)
1417 RTL_USER_PROCESS_PARAMETERS
*params
;
1418 UNICODE_STRING image_str
, cmdline_str
, curdir_str
, desktop
, title
, runtime
;
1420 WCHAR buffer
[MAX_PATH
];
1422 if(!GetLongPathNameW( filename
, buffer
, MAX_PATH
))
1423 lstrcpynW( buffer
, filename
, MAX_PATH
);
1424 if(!GetFullPathNameW( buffer
, MAX_PATH
, buffer
, NULL
))
1425 lstrcpynW( buffer
, filename
, MAX_PATH
);
1426 RtlInitUnicodeString( &image_str
, buffer
);
1428 RtlInitUnicodeString( &cmdline_str
, cmdline
);
1429 if (cur_dir
) RtlInitUnicodeString( &curdir_str
, cur_dir
);
1430 if (startup
->lpDesktop
) RtlInitUnicodeString( &desktop
, startup
->lpDesktop
);
1431 if (startup
->lpTitle
) RtlInitUnicodeString( &title
, startup
->lpTitle
);
1432 if (startup
->lpReserved2
&& startup
->cbReserved2
)
1435 runtime
.MaximumLength
= startup
->cbReserved2
;
1436 runtime
.Buffer
= (WCHAR
*)startup
->lpReserved2
;
1439 status
= RtlCreateProcessParameters( ¶ms
, &image_str
, NULL
,
1440 cur_dir
? &curdir_str
: NULL
,
1442 startup
->lpTitle
? &title
: NULL
,
1443 startup
->lpDesktop
? &desktop
: NULL
,
1445 (startup
->lpReserved2
&& startup
->cbReserved2
) ? &runtime
: NULL
);
1446 if (status
!= STATUS_SUCCESS
)
1448 SetLastError( RtlNtStatusToDosError(status
) );
1452 params
->hStdInput
= startup
->hStdInput
;
1453 params
->hStdOutput
= startup
->hStdOutput
;
1454 params
->hStdError
= startup
->hStdError
;
1455 params
->dwX
= startup
->dwX
;
1456 params
->dwY
= startup
->dwY
;
1457 params
->dwXSize
= startup
->dwXSize
;
1458 params
->dwYSize
= startup
->dwYSize
;
1459 params
->dwXCountChars
= startup
->dwXCountChars
;
1460 params
->dwYCountChars
= startup
->dwYCountChars
;
1461 params
->dwFillAttribute
= startup
->dwFillAttribute
;
1462 params
->dwFlags
= startup
->dwFlags
;
1463 params
->wShowWindow
= startup
->wShowWindow
;
1468 /***********************************************************************
1471 * Create a new process. If hFile is a valid handle we have an exe
1472 * file, otherwise it is a Winelib app.
1474 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1475 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1476 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1477 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1478 void *res_start
, void *res_end
)
1480 BOOL ret
, success
= FALSE
;
1481 HANDLE process_info
;
1483 RTL_USER_PROCESS_PARAMETERS
*params
;
1489 char preloader_reserve
[64];
1491 if (!env
) RtlAcquirePebLock();
1493 if (!(params
= create_user_params( filename
, cmd_line
, cur_dir
, env
, startup
)))
1495 if (!env
) RtlReleasePebLock();
1498 env_end
= params
->Environment
;
1499 while (*env_end
) env_end
+= strlenW(env_end
) + 1;
1502 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx%c",
1503 (unsigned long)res_start
, (unsigned long)res_end
, 0 );
1505 /* create the synchronization pipes */
1507 if (pipe( startfd
) == -1)
1509 if (!env
) RtlReleasePebLock();
1510 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1511 RtlDestroyProcessParameters( params
);
1514 if (pipe( execfd
) == -1)
1516 if (!env
) RtlReleasePebLock();
1517 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1518 close( startfd
[0] );
1519 close( startfd
[1] );
1520 RtlDestroyProcessParameters( params
);
1523 fcntl( execfd
[1], F_SETFD
, 1 ); /* set close on exec */
1525 /* create the child process */
1527 if (!(pid
= fork())) /* child */
1529 char **argv
= build_argv( cmd_line
, 1 );
1531 close( startfd
[1] );
1534 /* wait for parent to tell us to start */
1535 if (read( startfd
[0], &dummy
, 1 ) != 1) _exit(1);
1537 close( startfd
[0] );
1538 /* Reset signals that we previously set to SIG_IGN */
1539 signal( SIGPIPE
, SIG_DFL
);
1540 signal( SIGCHLD
, SIG_DFL
);
1542 putenv( preloader_reserve
);
1543 if (unixdir
) chdir(unixdir
);
1547 /* first, try for a WINELOADER environment variable */
1548 const char *loader
= getenv("WINELOADER");
1549 if (loader
) wine_exec_wine_binary( loader
, argv
, NULL
, TRUE
);
1550 /* now use the standard search strategy */
1551 wine_exec_wine_binary( NULL
, argv
, NULL
, TRUE
);
1554 write( execfd
[1], &err
, sizeof(err
) );
1558 /* this is the parent */
1560 close( startfd
[0] );
1564 if (!env
) RtlReleasePebLock();
1565 close( startfd
[1] );
1568 RtlDestroyProcessParameters( params
);
1572 /* create the process on the server side */
1574 SERVER_START_REQ( new_process
)
1576 req
->inherit_all
= inherit
;
1577 req
->create_flags
= flags
;
1578 req
->unix_pid
= pid
;
1579 req
->exe_file
= hFile
;
1580 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1582 req
->hstdin
= startup
->hStdInput
;
1583 req
->hstdout
= startup
->hStdOutput
;
1584 req
->hstderr
= startup
->hStdError
;
1588 req
->hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1589 req
->hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1590 req
->hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1593 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1595 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1596 if (is_console_handle(req
->hstdin
)) req
->hstdin
= INVALID_HANDLE_VALUE
;
1597 if (is_console_handle(req
->hstdout
)) req
->hstdout
= INVALID_HANDLE_VALUE
;
1598 if (is_console_handle(req
->hstderr
)) req
->hstderr
= INVALID_HANDLE_VALUE
;
1602 if (is_console_handle(req
->hstdin
)) req
->hstdin
= console_handle_unmap(req
->hstdin
);
1603 if (is_console_handle(req
->hstdout
)) req
->hstdout
= console_handle_unmap(req
->hstdout
);
1604 if (is_console_handle(req
->hstderr
)) req
->hstderr
= console_handle_unmap(req
->hstderr
);
1607 wine_server_add_data( req
, params
, params
->Size
);
1608 wine_server_add_data( req
, params
->Environment
, (env_end
-params
->Environment
)*sizeof(WCHAR
) );
1609 ret
= !wine_server_call_err( req
);
1610 process_info
= reply
->info
;
1614 if (!env
) RtlReleasePebLock();
1615 RtlDestroyProcessParameters( params
);
1618 close( startfd
[1] );
1623 /* tell child to start and wait for it to exec */
1625 write( startfd
[1], &dummy
, 1 );
1626 close( startfd
[1] );
1628 if (read( execfd
[0], &err
, sizeof(err
) ) > 0) /* exec failed */
1633 CloseHandle( process_info
);
1638 /* wait for the new process info to be ready */
1640 WaitForSingleObject( process_info
, INFINITE
);
1641 SERVER_START_REQ( get_new_process_info
)
1643 req
->info
= process_info
;
1644 req
->pinherit
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
);
1645 req
->tinherit
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
);
1646 if ((ret
= !wine_server_call_err( req
)))
1648 info
->dwProcessId
= (DWORD
)reply
->pid
;
1649 info
->dwThreadId
= (DWORD
)reply
->tid
;
1650 info
->hProcess
= reply
->phandle
;
1651 info
->hThread
= reply
->thandle
;
1652 success
= reply
->success
;
1657 if (ret
&& !success
) /* new process failed to start */
1660 if (GetExitCodeProcess( info
->hProcess
, &exitcode
)) SetLastError( exitcode
);
1661 CloseHandle( info
->hThread
);
1662 CloseHandle( info
->hProcess
);
1665 CloseHandle( process_info
);
1670 /***********************************************************************
1671 * create_vdm_process
1673 * Create a new VDM process for a 16-bit or DOS application.
1675 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
1676 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1677 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1678 LPPROCESS_INFORMATION info
, LPCSTR unixdir
)
1680 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1683 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
1684 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
1688 SetLastError( ERROR_OUTOFMEMORY
);
1691 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
1692 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
1693 flags
, startup
, info
, unixdir
, NULL
, NULL
);
1694 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
1699 /***********************************************************************
1700 * create_cmd_process
1702 * Create a new cmd shell process for a .BAT file.
1704 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
1705 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1706 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1707 LPPROCESS_INFORMATION info
)
1710 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
1711 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
1712 WCHAR comspec
[MAX_PATH
];
1716 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
1718 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
1719 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
1722 strcpyW( newcmdline
, comspec
);
1723 strcatW( newcmdline
, slashcW
);
1724 strcatW( newcmdline
, cmd_line
);
1725 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
1726 flags
, env
, cur_dir
, startup
, info
);
1727 HeapFree( GetProcessHeap(), 0, newcmdline
);
1732 /*************************************************************************
1735 * Helper for CreateProcess: retrieve the file name to load from the
1736 * app name and command line. Store the file name in buffer, and
1737 * return a possibly modified command line.
1738 * Also returns a handle to the opened file if it's a Windows binary.
1740 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
1741 int buflen
, HANDLE
*handle
)
1743 static const WCHAR quotesW
[] = {'"','%','s','"',0};
1745 WCHAR
*name
, *pos
, *ret
= NULL
;
1748 /* if we have an app name, everything is easy */
1752 /* use the unmodified app name as file name */
1753 lstrcpynW( buffer
, appname
, buflen
);
1754 *handle
= open_exe_file( buffer
);
1755 if (!(ret
= cmdline
) || !cmdline
[0])
1757 /* no command-line, create one */
1758 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
1759 sprintfW( ret
, quotesW
, appname
);
1766 SetLastError( ERROR_INVALID_PARAMETER
);
1770 /* first check for a quoted file name */
1772 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
1774 int len
= p
- cmdline
- 1;
1775 /* extract the quoted portion as file name */
1776 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1777 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
1780 if (find_exe_file( name
, buffer
, buflen
, handle
))
1781 ret
= cmdline
; /* no change necessary */
1785 /* now try the command-line word by word */
1787 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
1794 do *pos
++ = *p
++; while (*p
&& *p
!= ' ');
1796 if (find_exe_file( name
, buffer
, buflen
, handle
))
1803 if (!ret
|| !strchrW( name
, ' ' )) goto done
; /* no change necessary */
1805 /* now build a new command-line with quotes */
1807 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
1809 sprintfW( ret
, quotesW
, name
);
1813 HeapFree( GetProcessHeap(), 0, name
);
1818 /**********************************************************************
1819 * CreateProcessA (KERNEL32.@)
1821 BOOL WINAPI
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1822 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
1823 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
1824 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
1827 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
1828 UNICODE_STRING desktopW
, titleW
;
1831 desktopW
.Buffer
= NULL
;
1832 titleW
.Buffer
= NULL
;
1833 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
1834 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
1835 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
1837 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
1838 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
1840 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
1841 infoW
.lpDesktop
= desktopW
.Buffer
;
1842 infoW
.lpTitle
= titleW
.Buffer
;
1844 if (startup_info
->lpReserved
)
1845 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1846 debugstr_a(startup_info
->lpReserved
));
1848 ret
= CreateProcessW( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
1849 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
1851 HeapFree( GetProcessHeap(), 0, app_nameW
);
1852 HeapFree( GetProcessHeap(), 0, cmd_lineW
);
1853 HeapFree( GetProcessHeap(), 0, cur_dirW
);
1854 RtlFreeUnicodeString( &desktopW
);
1855 RtlFreeUnicodeString( &titleW
);
1860 /**********************************************************************
1861 * CreateProcessW (KERNEL32.@)
1863 BOOL WINAPI
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1864 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
1865 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
1866 LPPROCESS_INFORMATION info
)
1870 char *unixdir
= NULL
;
1871 WCHAR name
[MAX_PATH
];
1872 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
1873 void *res_start
, *res_end
;
1875 /* Process the AppName and/or CmdLine to get module name and path */
1877 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
1879 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
), &hFile
)))
1881 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
1883 /* Warn if unsupported features are used */
1885 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
1886 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
1887 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
1888 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
1889 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name
), flags
);
1893 unixdir
= wine_get_unix_file_name( cur_dir
);
1897 WCHAR buf
[MAX_PATH
];
1898 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
1901 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
1906 while (*p
) p
+= strlen(p
) + 1;
1907 p
++; /* final null */
1908 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
1909 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
1910 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
1911 flags
|= CREATE_UNICODE_ENVIRONMENT
;
1914 info
->hThread
= info
->hProcess
= 0;
1915 info
->dwProcessId
= info
->dwThreadId
= 0;
1917 /* Determine executable type */
1919 if (!hFile
) /* builtin exe */
1921 TRACE( "starting %s as Winelib app\n", debugstr_w(name
) );
1922 retv
= create_process( 0, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1923 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
);
1927 switch( MODULE_GetBinaryType( hFile
, &res_start
, &res_end
))
1930 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name
), res_start
, res_end
);
1931 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1932 inherit
, flags
, startup_info
, info
, unixdir
, res_start
, res_end
);
1937 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
1938 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1939 inherit
, flags
, startup_info
, info
, unixdir
);
1942 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
1943 SetLastError( ERROR_BAD_EXE_FORMAT
);
1945 case BINARY_UNIX_LIB
:
1946 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
1947 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1948 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
);
1950 case BINARY_UNKNOWN
:
1951 /* check for .com or .bat extension */
1952 if ((p
= strrchrW( name
, '.' )))
1954 if (!strcmpiW( p
, comW
) || !strcmpiW( p
, pifW
))
1956 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
1957 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1958 inherit
, flags
, startup_info
, info
, unixdir
);
1961 if (!strcmpiW( p
, batW
))
1963 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
1964 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1965 inherit
, flags
, startup_info
, info
);
1970 case BINARY_UNIX_EXE
:
1972 /* unknown file, try as unix executable */
1975 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
1977 if ((unix_name
= wine_get_unix_file_name( name
)))
1979 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
) != -1);
1980 HeapFree( GetProcessHeap(), 0, unix_name
);
1985 CloseHandle( hFile
);
1988 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
1989 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
1990 HeapFree( GetProcessHeap(), 0, unixdir
);
1995 /***********************************************************************
1998 * Wrapper to call WaitForInputIdle USER function
2000 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
2002 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
2004 HMODULE mod
= GetModuleHandleA( "user32.dll" );
2007 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
2008 if (ptr
) return ptr( process
, timeout
);
2014 /***********************************************************************
2015 * WinExec (KERNEL32.@)
2017 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
2019 PROCESS_INFORMATION info
;
2020 STARTUPINFOA startup
;
2024 memset( &startup
, 0, sizeof(startup
) );
2025 startup
.cb
= sizeof(startup
);
2026 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2027 startup
.wShowWindow
= nCmdShow
;
2029 /* cmdline needs to be writeable for CreateProcess */
2030 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
2031 strcpy( cmdline
, lpCmdLine
);
2033 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
2034 0, NULL
, NULL
, &startup
, &info
))
2036 /* Give 30 seconds to the app to come up */
2037 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2038 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2040 /* Close off the handles */
2041 CloseHandle( info
.hThread
);
2042 CloseHandle( info
.hProcess
);
2044 else if ((ret
= GetLastError()) >= 32)
2046 FIXME("Strange error set by CreateProcess: %d\n", ret
);
2049 HeapFree( GetProcessHeap(), 0, cmdline
);
2054 /**********************************************************************
2055 * LoadModule (KERNEL32.@)
2057 HINSTANCE WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2059 LOADPARMS32
*params
= paramBlock
;
2060 PROCESS_INFORMATION info
;
2061 STARTUPINFOA startup
;
2062 HINSTANCE hInstance
;
2064 char filename
[MAX_PATH
];
2067 if (!name
) return (HINSTANCE
)ERROR_FILE_NOT_FOUND
;
2069 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2070 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2071 return (HINSTANCE
)GetLastError();
2073 len
= (BYTE
)params
->lpCmdLine
[0];
2074 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2075 return (HINSTANCE
)ERROR_NOT_ENOUGH_MEMORY
;
2077 strcpy( cmdline
, filename
);
2078 p
= cmdline
+ strlen(cmdline
);
2080 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2083 memset( &startup
, 0, sizeof(startup
) );
2084 startup
.cb
= sizeof(startup
);
2085 if (params
->lpCmdShow
)
2087 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2088 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2091 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2092 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2094 /* Give 30 seconds to the app to come up */
2095 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2096 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2097 hInstance
= (HINSTANCE
)33;
2098 /* Close off the handles */
2099 CloseHandle( info
.hThread
);
2100 CloseHandle( info
.hProcess
);
2102 else if ((hInstance
= (HINSTANCE
)GetLastError()) >= (HINSTANCE
)32)
2104 FIXME("Strange error set by CreateProcess: %p\n", hInstance
);
2105 hInstance
= (HINSTANCE
)11;
2108 HeapFree( GetProcessHeap(), 0, cmdline
);
2113 /******************************************************************************
2114 * TerminateProcess (KERNEL32.@)
2116 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2118 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2119 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2124 /***********************************************************************
2125 * ExitProcess (KERNEL32.@)
2127 void WINAPI
ExitProcess( DWORD status
)
2129 LdrShutdownProcess();
2130 SERVER_START_REQ( terminate_process
)
2132 /* send the exit code to the server */
2133 req
->handle
= GetCurrentProcess();
2134 req
->exit_code
= status
;
2135 wine_server_call( req
);
2142 /***********************************************************************
2143 * GetExitCodeProcess [KERNEL32.@]
2145 * Gets termination status of specified process
2151 BOOL WINAPI
GetExitCodeProcess(
2152 HANDLE hProcess
, /* [in] handle to the process */
2153 LPDWORD lpExitCode
) /* [out] address to receive termination status */
2156 PROCESS_BASIC_INFORMATION pbi
;
2158 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2160 if (status
== STATUS_SUCCESS
)
2162 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2165 SetLastError( RtlNtStatusToDosError(status
) );
2170 /***********************************************************************
2171 * SetErrorMode (KERNEL32.@)
2173 UINT WINAPI
SetErrorMode( UINT mode
)
2175 UINT old
= process_error_mode
;
2176 process_error_mode
= mode
;
2181 /**********************************************************************
2182 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2184 * Allocates a thread local storage index
2187 * Success: TLS Index
2188 * Failure: 0xFFFFFFFF
2190 DWORD WINAPI
TlsAlloc( void )
2193 PEB
* const peb
= NtCurrentTeb()->Peb
;
2195 RtlAcquirePebLock();
2196 index
= RtlFindClearBitsAndSet( peb
->TlsBitmap
, 1, 0 );
2197 if (index
!= ~0UL) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2200 index
= RtlFindClearBitsAndSet( peb
->TlsExpansionBitmap
, 1, 0 );
2203 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2204 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2205 8 * sizeof(peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2207 RtlClearBits( peb
->TlsExpansionBitmap
, index
, 1 );
2209 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2213 NtCurrentTeb()->TlsExpansionSlots
[index
] = 0; /* clear the value */
2214 index
+= TLS_MINIMUM_AVAILABLE
;
2217 else SetLastError( ERROR_NO_MORE_ITEMS
);
2219 RtlReleasePebLock();
2224 /**********************************************************************
2225 * TlsFree [KERNEL32.@] Releases a TLS index.
2227 * Releases a thread local storage index, making it available for reuse
2233 BOOL WINAPI
TlsFree(
2234 DWORD index
) /* [in] TLS Index to free */
2238 RtlAcquirePebLock();
2239 if (index
>= TLS_MINIMUM_AVAILABLE
)
2241 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2242 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsExpansionBitmap
, index
- TLS_MINIMUM_AVAILABLE
, 1 );
2246 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2247 if (ret
) RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2249 if (ret
) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2250 else SetLastError( ERROR_INVALID_PARAMETER
);
2251 RtlReleasePebLock();
2256 /**********************************************************************
2257 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2260 * Success: Value stored in calling thread's TLS slot for index
2261 * Failure: 0 and GetLastError() returns NO_ERROR
2263 LPVOID WINAPI
TlsGetValue(
2264 DWORD index
) /* [in] TLS index to retrieve value for */
2268 if (index
< TLS_MINIMUM_AVAILABLE
)
2270 ret
= NtCurrentTeb()->TlsSlots
[index
];
2274 index
-= TLS_MINIMUM_AVAILABLE
;
2275 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2277 SetLastError( ERROR_INVALID_PARAMETER
);
2280 if (!NtCurrentTeb()->TlsExpansionSlots
) ret
= NULL
;
2281 else ret
= NtCurrentTeb()->TlsExpansionSlots
[index
];
2283 SetLastError( ERROR_SUCCESS
);
2288 /**********************************************************************
2289 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2295 BOOL WINAPI
TlsSetValue(
2296 DWORD index
, /* [in] TLS index to set value for */
2297 LPVOID value
) /* [in] Value to be stored */
2299 if (index
< TLS_MINIMUM_AVAILABLE
)
2301 NtCurrentTeb()->TlsSlots
[index
] = value
;
2305 index
-= TLS_MINIMUM_AVAILABLE
;
2306 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
2308 SetLastError( ERROR_INVALID_PARAMETER
);
2311 if (!NtCurrentTeb()->TlsExpansionSlots
&&
2312 !(NtCurrentTeb()->TlsExpansionSlots
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
,
2313 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
) * sizeof(void*) )))
2315 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
2318 NtCurrentTeb()->TlsExpansionSlots
[index
] = value
;
2324 /***********************************************************************
2325 * GetProcessFlags (KERNEL32.@)
2327 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2329 IMAGE_NT_HEADERS
*nt
;
2332 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2334 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2336 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2337 flags
|= PDB32_CONSOLE_PROC
;
2339 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2340 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2345 /***********************************************************************
2346 * GetProcessDword (KERNEL.485)
2347 * GetProcessDword (KERNEL32.18)
2348 * 'Of course you cannot directly access Windows internal structures'
2350 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
2355 TRACE("(%ld, %d)\n", dwProcessID
, offset
);
2357 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2359 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
2365 case GPD_APP_COMPAT_FLAGS
:
2366 return GetAppCompatFlags16(0);
2367 case GPD_LOAD_DONE_EVENT
:
2369 case GPD_HINSTANCE16
:
2370 return GetTaskDS16();
2371 case GPD_WINDOWS_VERSION
:
2372 return GetExeVersion16();
2374 return (DWORD
)NtCurrentTeb() - 0x10 /* FIXME */;
2376 return (DWORD
)NtCurrentTeb()->Peb
;
2377 case GPD_STARTF_SHELLDATA
: /* return stdoutput handle from startupinfo ??? */
2378 GetStartupInfoW(&siw
);
2379 return (DWORD
)siw
.hStdOutput
;
2380 case GPD_STARTF_HOTKEY
: /* return stdinput handle from startupinfo ??? */
2381 GetStartupInfoW(&siw
);
2382 return (DWORD
)siw
.hStdInput
;
2383 case GPD_STARTF_SHOWWINDOW
:
2384 GetStartupInfoW(&siw
);
2385 return siw
.wShowWindow
;
2386 case GPD_STARTF_SIZE
:
2387 GetStartupInfoW(&siw
);
2389 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2391 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2392 return MAKELONG( x
, y
);
2393 case GPD_STARTF_POSITION
:
2394 GetStartupInfoW(&siw
);
2396 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2398 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2399 return MAKELONG( x
, y
);
2400 case GPD_STARTF_FLAGS
:
2401 GetStartupInfoW(&siw
);
2406 return GetProcessFlags(0);
2408 return process_dword
;
2410 ERR("Unknown offset %d\n", offset
);
2415 /***********************************************************************
2416 * SetProcessDword (KERNEL.484)
2417 * 'Of course you cannot directly access Windows internal structures'
2419 void WINAPI
SetProcessDword( DWORD dwProcessID
, INT offset
, DWORD value
)
2421 TRACE("(%ld, %d)\n", dwProcessID
, offset
);
2423 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2425 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
2431 case GPD_APP_COMPAT_FLAGS
:
2432 case GPD_LOAD_DONE_EVENT
:
2433 case GPD_HINSTANCE16
:
2434 case GPD_WINDOWS_VERSION
:
2437 case GPD_STARTF_SHELLDATA
:
2438 case GPD_STARTF_HOTKEY
:
2439 case GPD_STARTF_SHOWWINDOW
:
2440 case GPD_STARTF_SIZE
:
2441 case GPD_STARTF_POSITION
:
2442 case GPD_STARTF_FLAGS
:
2445 ERR("Not allowed to modify offset %d\n", offset
);
2448 process_dword
= value
;
2451 ERR("Unknown offset %d\n", offset
);
2457 /***********************************************************************
2458 * ExitProcess (KERNEL.466)
2460 void WINAPI
ExitProcess16( WORD status
)
2463 ReleaseThunkLock( &count
);
2464 ExitProcess( status
);
2468 /*********************************************************************
2469 * OpenProcess (KERNEL32.@)
2471 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2474 SERVER_START_REQ( open_process
)
2477 req
->access
= access
;
2478 req
->inherit
= inherit
;
2479 if (!wine_server_call_err( req
)) ret
= reply
->handle
;
2486 /*********************************************************************
2487 * MapProcessHandle (KERNEL.483)
2488 * GetProcessId (KERNEL32.@)
2490 DWORD WINAPI
GetProcessId( HANDLE hProcess
)
2493 PROCESS_BASIC_INFORMATION pbi
;
2495 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2497 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2498 SetLastError( RtlNtStatusToDosError(status
) );
2503 /*********************************************************************
2504 * CloseW32Handle (KERNEL.474)
2505 * CloseHandle (KERNEL32.@)
2507 BOOL WINAPI
CloseHandle( HANDLE handle
)
2511 /* stdio handles need special treatment */
2512 if ((handle
== (HANDLE
)STD_INPUT_HANDLE
) ||
2513 (handle
== (HANDLE
)STD_OUTPUT_HANDLE
) ||
2514 (handle
== (HANDLE
)STD_ERROR_HANDLE
))
2515 handle
= GetStdHandle( (DWORD
)handle
);
2517 if (is_console_handle(handle
))
2518 return CloseConsoleHandle(handle
);
2520 status
= NtClose( handle
);
2521 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2526 /*********************************************************************
2527 * GetHandleInformation (KERNEL32.@)
2529 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2532 SERVER_START_REQ( set_handle_info
)
2534 req
->handle
= handle
;
2538 ret
= !wine_server_call_err( req
);
2539 if (ret
&& flags
) *flags
= reply
->old_flags
;
2546 /*********************************************************************
2547 * SetHandleInformation (KERNEL32.@)
2549 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2552 SERVER_START_REQ( set_handle_info
)
2554 req
->handle
= handle
;
2558 ret
= !wine_server_call_err( req
);
2565 /*********************************************************************
2566 * DuplicateHandle (KERNEL32.@)
2568 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2569 HANDLE dest_process
, HANDLE
*dest
,
2570 DWORD access
, BOOL inherit
, DWORD options
)
2574 if (is_console_handle(source
))
2576 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2577 if (source_process
!= dest_process
||
2578 source_process
!= GetCurrentProcess())
2580 SetLastError(ERROR_INVALID_PARAMETER
);
2583 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2584 return (*dest
!= INVALID_HANDLE_VALUE
);
2586 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2587 access
, inherit
? OBJ_INHERIT
: 0, options
);
2588 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2593 /***********************************************************************
2594 * ConvertToGlobalHandle (KERNEL.476)
2595 * ConvertToGlobalHandle (KERNEL32.@)
2597 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
2599 HANDLE ret
= INVALID_HANDLE_VALUE
;
2600 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
2601 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
2606 /***********************************************************************
2607 * SetHandleContext (KERNEL32.@)
2609 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
2611 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2612 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
2613 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2618 /***********************************************************************
2619 * GetHandleContext (KERNEL32.@)
2621 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
2623 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2624 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
2625 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2630 /***********************************************************************
2631 * CreateSocketHandle (KERNEL32.@)
2633 HANDLE WINAPI
CreateSocketHandle(void)
2635 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2636 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2637 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2638 return INVALID_HANDLE_VALUE
;
2642 /***********************************************************************
2643 * SetPriorityClass (KERNEL32.@)
2645 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
2648 SERVER_START_REQ( set_process_info
)
2650 req
->handle
= hprocess
;
2651 req
->priority
= priorityclass
;
2652 req
->mask
= SET_PROCESS_INFO_PRIORITY
;
2653 ret
= !wine_server_call_err( req
);
2660 /***********************************************************************
2661 * GetPriorityClass (KERNEL32.@)
2663 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
2666 PROCESS_BASIC_INFORMATION pbi
;
2668 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2670 if (status
== STATUS_SUCCESS
) return pbi
.BasePriority
;
2671 SetLastError( RtlNtStatusToDosError(status
) );
2676 /***********************************************************************
2677 * SetProcessAffinityMask (KERNEL32.@)
2679 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD_PTR affmask
)
2682 SERVER_START_REQ( set_process_info
)
2684 req
->handle
= hProcess
;
2685 req
->affinity
= affmask
;
2686 req
->mask
= SET_PROCESS_INFO_AFFINITY
;
2687 ret
= !wine_server_call_err( req
);
2694 /**********************************************************************
2695 * GetProcessAffinityMask (KERNEL32.@)
2697 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
2698 LPDWORD lpProcessAffinityMask
,
2699 LPDWORD lpSystemAffinityMask
)
2702 SERVER_START_REQ( get_process_info
)
2704 req
->handle
= hProcess
;
2705 if (!wine_server_call_err( req
))
2707 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= reply
->process_affinity
;
2708 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= reply
->system_affinity
;
2717 /***********************************************************************
2718 * GetProcessVersion (KERNEL32.@)
2720 DWORD WINAPI
GetProcessVersion( DWORD processid
)
2722 IMAGE_NT_HEADERS
*nt
;
2724 if (processid
&& processid
!= GetCurrentProcessId())
2726 FIXME("should use ReadProcessMemory\n");
2729 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2730 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
2731 nt
->OptionalHeader
.MinorSubsystemVersion
);
2736 /***********************************************************************
2737 * SetProcessWorkingSetSize [KERNEL32.@]
2738 * Sets the min/max working set sizes for a specified process.
2741 * hProcess [I] Handle to the process of interest
2742 * minset [I] Specifies minimum working set size
2743 * maxset [I] Specifies maximum working set size
2749 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
2752 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
2753 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
2754 /* Trim the working set to zero */
2755 /* Swap the process out of physical RAM */
2760 /***********************************************************************
2761 * GetProcessWorkingSetSize (KERNEL32.@)
2763 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
2766 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
2767 /* 32 MB working set size */
2768 if (minset
) *minset
= 32*1024*1024;
2769 if (maxset
) *maxset
= 32*1024*1024;
2774 /***********************************************************************
2775 * SetProcessShutdownParameters (KERNEL32.@)
2777 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
2779 FIXME("(%08lx, %08lx): partial stub.\n", level
, flags
);
2780 shutdown_flags
= flags
;
2781 shutdown_priority
= level
;
2786 /***********************************************************************
2787 * GetProcessShutdownParameters (KERNEL32.@)
2790 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
2792 *lpdwLevel
= shutdown_priority
;
2793 *lpdwFlags
= shutdown_flags
;
2798 /***********************************************************************
2799 * GetProcessPriorityBoost (KERNEL32.@)
2801 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
2803 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
2805 /* Report that no boost is present.. */
2806 *pDisablePriorityBoost
= FALSE
;
2811 /***********************************************************************
2812 * SetProcessPriorityBoost (KERNEL32.@)
2814 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
2816 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
2817 /* Say we can do it. I doubt the program will notice that we don't. */
2822 /***********************************************************************
2823 * ReadProcessMemory (KERNEL32.@)
2825 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
2826 SIZE_T
*bytes_read
)
2828 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
2829 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2834 /***********************************************************************
2835 * WriteProcessMemory (KERNEL32.@)
2837 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
2838 SIZE_T
*bytes_written
)
2840 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
2841 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2846 /****************************************************************************
2847 * FlushInstructionCache (KERNEL32.@)
2849 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
2852 if (GetVersion() & 0x80000000) return TRUE
; /* not NT, always TRUE */
2853 status
= NtFlushInstructionCache( hProcess
, lpBaseAddress
, dwSize
);
2854 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2859 /******************************************************************
2860 * GetProcessIoCounters (KERNEL32.@)
2862 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
2866 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
2867 ioc
, sizeof(*ioc
), NULL
);
2868 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2872 /***********************************************************************
2873 * ProcessIdToSessionId (KERNEL32.@)
2874 * This function is available on Terminal Server 4SP4 and Windows 2000
2876 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
2878 /* According to MSDN, if the calling process is not in a terminal
2879 * services environment, then the sessionid returned is zero.
2886 /***********************************************************************
2887 * RegisterServiceProcess (KERNEL.491)
2888 * RegisterServiceProcess (KERNEL32.@)
2890 * A service process calls this function to ensure that it continues to run
2891 * even after a user logged off.
2893 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
2895 /* I don't think that Wine needs to do anything in this function */
2896 return 1; /* success */
2900 /***********************************************************************
2901 * GetSystemMSecCount (SYSTEM.6)
2902 * GetTickCount (KERNEL32.@)
2904 * Get the number of milliseconds the system has been running.
2910 * The current tick count.
2913 * -The value returned will wrap arounf every 2^32 milliseconds.
2914 * -Under Windows, tick 0 is the moment at which the system is rebooted.
2915 * Under Wine, tick 0 begins at the moment the wineserver process is started,
2917 DWORD WINAPI
GetTickCount(void)
2920 gettimeofday( &t
, NULL
);
2921 return ((t
.tv_sec
* 1000) + (t
.tv_usec
/ 1000)) - server_startticks
;
2925 /***********************************************************************
2926 * GetCurrentProcess (KERNEL32.@)
2928 * Get a handle to the current process.
2934 * A handle representing the current process.
2936 #undef GetCurrentProcess
2937 HANDLE WINAPI
GetCurrentProcess(void)
2939 return (HANDLE
)0xffffffff;