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"
41 #include "kernel_private.h"
42 #include "wine/exception.h"
43 #include "wine/server.h"
44 #include "wine/unicode.h"
45 #include "wine/debug.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(process
);
48 WINE_DECLARE_DEBUG_CHANNEL(file
);
49 WINE_DECLARE_DEBUG_CHANNEL(server
);
50 WINE_DECLARE_DEBUG_CHANNEL(relay
);
60 static UINT process_error_mode
;
62 static HANDLE main_exe_file
;
63 static DWORD shutdown_flags
= 0;
64 static DWORD shutdown_priority
= 0x280;
65 static DWORD process_dword
;
67 static unsigned int server_startticks
;
68 int main_create_flags
= 0;
69 HMODULE kernel32_handle
= 0;
71 const WCHAR
*DIR_Windows
= NULL
;
72 const WCHAR
*DIR_System
= NULL
;
75 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
76 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
77 #define PDB32_DOS_PROC 0x0010 /* Dos process */
78 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
79 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
80 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
82 static const WCHAR comW
[] = {'.','c','o','m',0};
83 static const WCHAR batW
[] = {'.','b','a','t',0};
84 static const WCHAR winevdmW
[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
86 extern void SHELL_LoadRegistry(void);
87 extern void VOLUME_CreateDevices(void);
88 extern void VERSION_Init( const WCHAR
*appname
);
89 extern void LOCALE_Init(void);
91 /***********************************************************************
94 inline static int contains_path( LPCWSTR name
)
96 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
100 /***********************************************************************
103 * Check if an environment variable needs to be handled specially when
104 * passed through the Unix environment (i.e. prefixed with "WINE").
106 inline static int is_special_env_var( const char *var
)
108 return (!strncmp( var
, "PATH=", sizeof("PATH=")-1 ) ||
109 !strncmp( var
, "HOME=", sizeof("HOME=")-1 ) ||
110 !strncmp( var
, "TEMP=", sizeof("TEMP=")-1 ) ||
111 !strncmp( var
, "TMP=", sizeof("TMP=")-1 ));
115 /***************************************************************************
118 * Get the path of a builtin module when the native file does not exist.
120 static BOOL
get_builtin_path( const WCHAR
*libname
, const WCHAR
*ext
, WCHAR
*filename
, UINT size
)
123 UINT len
= strlenW( DIR_System
);
125 if (contains_path( libname
))
127 if (RtlGetFullPathName_U( libname
, size
* sizeof(WCHAR
),
128 filename
, &file_part
) > size
* sizeof(WCHAR
))
129 return FALSE
; /* too long */
131 if (strncmpiW( filename
, DIR_System
, len
) || filename
[len
] != '\\')
133 while (filename
[len
] == '\\') len
++;
134 if (filename
+ len
!= file_part
) return FALSE
;
138 if (strlenW(libname
) + len
+ 2 >= size
) return FALSE
; /* too long */
139 memcpy( filename
, DIR_System
, len
* sizeof(WCHAR
) );
140 file_part
= filename
+ len
;
141 if (file_part
> filename
&& file_part
[-1] != '\\') *file_part
++ = '\\';
142 strcpyW( file_part
, libname
);
144 if (ext
&& !strchrW( file_part
, '.' ))
146 if (file_part
+ strlenW(file_part
) + strlenW(ext
) + 1 > filename
+ size
)
147 return FALSE
; /* too long */
148 strcatW( file_part
, ext
);
154 /***********************************************************************
155 * open_builtin_exe_file
157 * Open an exe file for a builtin exe.
159 static void *open_builtin_exe_file( const WCHAR
*name
, char *error
, int error_size
,
160 int test_only
, int *file_exists
)
162 char exename
[MAX_PATH
];
166 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
167 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
169 /* we don't want to depend on the current codepage here */
170 len
= strlenW( name
) + 1;
171 if (len
>= sizeof(exename
)) return NULL
;
172 for (i
= 0; i
< len
; i
++)
174 if (name
[i
] > 127) return NULL
;
175 exename
[i
] = (char)name
[i
];
176 if (exename
[i
] >= 'A' && exename
[i
] <= 'Z') exename
[i
] += 'a' - 'A';
178 return wine_dll_load_main_exe( exename
, error
, error_size
, test_only
, file_exists
);
182 /***********************************************************************
185 * Open a specific exe file, taking load order into account.
186 * Returns the file handle or 0 for a builtin exe.
188 static HANDLE
open_exe_file( const WCHAR
*name
)
190 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
191 WCHAR buffer
[MAX_PATH
];
195 TRACE("looking for %s\n", debugstr_w(name
) );
197 if ((handle
= CreateFileW( name
, GENERIC_READ
, FILE_SHARE_READ
,
198 NULL
, OPEN_EXISTING
, 0, 0 )) == INVALID_HANDLE_VALUE
)
200 /* file doesn't exist, check for builtin */
201 if (!contains_path( name
)) goto error
;
202 if (!get_builtin_path( name
, NULL
, buffer
, sizeof(buffer
) )) goto error
;
206 MODULE_GetLoadOrderW( loadorder
, NULL
, name
);
208 for(i
= 0; i
< LOADORDER_NTYPES
; i
++)
210 if (loadorder
[i
] == LOADORDER_INVALID
) break;
214 TRACE( "Trying native exe %s\n", debugstr_w(name
) );
215 if (handle
!= INVALID_HANDLE_VALUE
) return handle
;
218 TRACE( "Trying built-in exe %s\n", debugstr_w(name
) );
219 open_builtin_exe_file( name
, NULL
, 0, 1, &file_exists
);
222 if (handle
!= INVALID_HANDLE_VALUE
) CloseHandle(handle
);
229 if (handle
!= INVALID_HANDLE_VALUE
) CloseHandle(handle
);
232 SetLastError( ERROR_FILE_NOT_FOUND
);
233 return INVALID_HANDLE_VALUE
;
237 /***********************************************************************
240 * Open an exe file, and return the full name and file handle.
241 * Returns FALSE if file could not be found.
242 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
243 * If file is a builtin exe, returns TRUE and sets handle to 0.
245 static BOOL
find_exe_file( const WCHAR
*name
, WCHAR
*buffer
, int buflen
, HANDLE
*handle
)
247 static const WCHAR exeW
[] = {'.','e','x','e',0};
249 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
252 TRACE("looking for %s\n", debugstr_w(name
) );
254 if (!SearchPathW( NULL
, name
, exeW
, buflen
, buffer
, NULL
) &&
255 !get_builtin_path( name
, exeW
, buffer
, buflen
))
257 /* no builtin found, try native without extension in case it is a Unix app */
259 if (SearchPathW( NULL
, name
, NULL
, buflen
, buffer
, NULL
))
261 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer
) );
262 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
,
263 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
269 MODULE_GetLoadOrderW( loadorder
, NULL
, buffer
);
271 for(i
= 0; i
< LOADORDER_NTYPES
; i
++)
273 if (loadorder
[i
] == LOADORDER_INVALID
) break;
277 TRACE( "Trying native exe %s\n", debugstr_w(buffer
) );
278 if ((*handle
= CreateFileW( buffer
, GENERIC_READ
, FILE_SHARE_READ
,
279 NULL
, OPEN_EXISTING
, 0, 0 )) != INVALID_HANDLE_VALUE
)
281 if (GetLastError() != ERROR_FILE_NOT_FOUND
) return TRUE
;
284 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer
) );
285 open_builtin_exe_file( buffer
, NULL
, 0, 1, &file_exists
);
296 SetLastError( ERROR_FILE_NOT_FOUND
);
301 /**********************************************************************
304 * Load a PE format EXE file.
306 static HMODULE
load_pe_exe( const WCHAR
*name
, HANDLE file
)
308 IMAGE_NT_HEADERS
*nt
;
311 OBJECT_ATTRIBUTES attr
;
316 attr
.Length
= sizeof(attr
);
317 attr
.RootDirectory
= 0;
318 attr
.ObjectName
= NULL
;
320 attr
.SecurityDescriptor
= NULL
;
321 attr
.SecurityQualityOfService
= NULL
;
324 if (NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
325 &attr
, &size
, 0, SEC_IMAGE
, file
) != STATUS_SUCCESS
)
329 if (NtMapViewOfSection( mapping
, GetCurrentProcess(), &module
, 0, 0, &size
, &len
,
330 ViewShare
, 0, PAGE_READONLY
) != STATUS_SUCCESS
)
336 nt
= RtlImageNtHeader( module
);
337 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
339 if (!RtlImageRvaToSection( nt
, module
, nt
->OptionalHeader
.AddressOfEntryPoint
))
340 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
341 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
342 debugstr_w(name
), nt
->OptionalHeader
.AddressOfEntryPoint
);
345 drive_type
= GetDriveTypeW( name
);
346 /* don't keep the file handle open on removable media */
347 if (drive_type
== DRIVE_REMOVABLE
|| drive_type
== DRIVE_CDROM
)
349 CloseHandle( main_exe_file
);
356 /***********************************************************************
357 * build_initial_environment
359 * Build the Win32 environment from the Unix environment
361 static BOOL
build_initial_environment( char **environ
)
368 /* Compute the total size of the Unix environment */
369 for (e
= environ
; *e
; e
++)
371 if (is_special_env_var( *e
)) continue;
372 size
+= MultiByteToWideChar( CP_UNIXCP
, 0, *e
, -1, NULL
, 0 );
374 size
*= sizeof(WCHAR
);
376 /* Now allocate the environment */
377 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr
, 0, &size
,
378 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
381 NtCurrentTeb()->Peb
->ProcessParameters
->Environment
= p
= ptr
;
382 endptr
= p
+ size
/ sizeof(WCHAR
);
384 /* And fill it with the Unix environment */
385 for (e
= environ
; *e
; e
++)
389 /* skip Unix special variables and use the Wine variants instead */
390 if (!strncmp( str
, "WINE", 4 ))
392 if (is_special_env_var( str
+ 4 )) str
+= 4;
393 else if (!strncmp( str
, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
395 else if (is_special_env_var( str
)) continue; /* skip it */
397 MultiByteToWideChar( CP_UNIXCP
, 0, str
, -1, p
, endptr
- p
);
405 /***********************************************************************
406 * set_registry_variables
408 * Set environment variables by enumerating the values of a key;
409 * helper for set_registry_environment().
411 static void set_registry_variables( HKEY hkey
)
413 UNICODE_STRING env_name
, env_value
;
417 char buffer
[1024 + sizeof(KEY_VALUE_FULL_INFORMATION
)];
418 KEY_VALUE_FULL_INFORMATION
*info
= (KEY_VALUE_FULL_INFORMATION
*)buffer
;
420 for (index
= 0; ; index
++)
422 status
= NtEnumerateValueKey( hkey
, index
, KeyValueFullInformation
,
423 buffer
, sizeof(buffer
), &size
);
424 if (status
== STATUS_BUFFER_OVERFLOW
) continue;
425 if (status
!= STATUS_SUCCESS
) break;
426 if (info
->Type
!= REG_SZ
) continue; /* FIXME: handle REG_EXPAND_SZ */
427 env_name
.Buffer
= info
->Name
;
428 env_name
.Length
= env_name
.MaximumLength
= info
->NameLength
;
429 env_value
.Buffer
= (WCHAR
*)(buffer
+ info
->DataOffset
);
430 env_value
.Length
= env_value
.MaximumLength
= info
->DataLength
;
431 if (env_value
.Length
&& !env_value
.Buffer
[env_value
.Length
/sizeof(WCHAR
)-1])
432 env_value
.Length
--; /* don't count terminating null if any */
433 RtlSetEnvironmentVariable( NULL
, &env_name
, &env_value
);
438 /***********************************************************************
439 * set_registry_environment
441 * Set the environment variables specified in the registry.
443 static void set_registry_environment(void)
445 static const WCHAR env_keyW
[] = {'M','a','c','h','i','n','e','\\',
446 'S','y','s','t','e','m','\\',
447 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
448 'C','o','n','t','r','o','l','\\',
449 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
450 'E','n','v','i','r','o','n','m','e','n','t',0};
451 static const WCHAR envW
[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
453 OBJECT_ATTRIBUTES attr
;
454 UNICODE_STRING nameW
;
457 attr
.Length
= sizeof(attr
);
458 attr
.RootDirectory
= 0;
459 attr
.ObjectName
= &nameW
;
461 attr
.SecurityDescriptor
= NULL
;
462 attr
.SecurityQualityOfService
= NULL
;
464 /* first the system environment variables */
465 RtlInitUnicodeString( &nameW
, env_keyW
);
466 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
468 set_registry_variables( hkey
);
472 /* then the ones for the current user */
473 if (RtlOpenCurrentUser( KEY_ALL_ACCESS
, (HKEY
*)&attr
.RootDirectory
) != STATUS_SUCCESS
) return;
474 RtlInitUnicodeString( &nameW
, envW
);
475 if (NtOpenKey( &hkey
, KEY_ALL_ACCESS
, &attr
) == STATUS_SUCCESS
)
477 set_registry_variables( hkey
);
480 NtClose( attr
.RootDirectory
);
484 /***********************************************************************
487 * Set the Wine library Unicode argv global variables.
489 static void set_library_wargv( char **argv
)
496 for (argc
= 0; argv
[argc
]; argc
++)
497 total
+= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, NULL
, 0 );
499 wargv
= RtlAllocateHeap( GetProcessHeap(), 0,
500 total
* sizeof(WCHAR
) + (argc
+ 1) * sizeof(*wargv
) );
501 p
= (WCHAR
*)(wargv
+ argc
+ 1);
502 for (argc
= 0; argv
[argc
]; argc
++)
504 DWORD reslen
= MultiByteToWideChar( CP_UNIXCP
, 0, argv
[argc
], -1, p
, total
);
510 __wine_main_wargv
= wargv
;
514 /***********************************************************************
517 * Build the command line of a process from the argv array.
519 * Note that it does NOT necessarily include the file name.
520 * Sometimes we don't even have any command line options at all.
522 * We must quote and escape characters so that the argv array can be rebuilt
523 * from the command line:
524 * - spaces and tabs must be quoted
526 * - quotes must be escaped
528 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
529 * resulting in an odd number of '\' followed by a '"'
532 * - '\'s that are not followed by a '"' can be left as is
536 static BOOL
build_command_line( WCHAR
**argv
)
541 RTL_USER_PROCESS_PARAMETERS
* rupp
= NtCurrentTeb()->Peb
->ProcessParameters
;
543 if (rupp
->CommandLine
.Buffer
) return TRUE
; /* already got it from the server */
546 for (arg
= argv
; *arg
; arg
++)
548 int has_space
,bcount
;
554 if( !*a
) has_space
=1;
559 if (*a
==' ' || *a
=='\t') {
561 } else if (*a
=='"') {
562 /* doubling of '\' preceeding a '"',
563 * plus escaping of said '"'
571 len
+=(a
-*arg
)+1 /* for the separating space */;
573 len
+=2; /* for the quotes */
576 if (!(rupp
->CommandLine
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
))))
579 p
= rupp
->CommandLine
.Buffer
;
580 rupp
->CommandLine
.Length
= (len
- 1) * sizeof(WCHAR
);
581 rupp
->CommandLine
.MaximumLength
= len
* sizeof(WCHAR
);
582 for (arg
= argv
; *arg
; arg
++)
584 int has_space
,has_quote
;
587 /* Check for quotes and spaces in this argument */
588 has_space
=has_quote
=0;
590 if( !*a
) has_space
=1;
592 if (*a
==' ' || *a
=='\t') {
596 } else if (*a
=='"') {
604 /* Now transfer it to the command line */
621 /* Double all the '\\' preceeding this '"', plus one */
622 for (i
=0;i
<=bcount
;i
++)
634 while ((*p
=*x
++)) p
++;
640 if (p
> rupp
->CommandLine
.Buffer
)
641 p
--; /* remove last space */
648 /* make sure the unicode string doesn't point beyond the end pointer */
649 static inline void fix_unicode_string( UNICODE_STRING
*str
, char *end_ptr
)
651 if ((char *)str
->Buffer
>= end_ptr
)
653 str
->Length
= str
->MaximumLength
= 0;
657 if ((char *)str
->Buffer
+ str
->MaximumLength
> end_ptr
)
659 str
->MaximumLength
= (end_ptr
- (char *)str
->Buffer
) & ~(sizeof(WCHAR
) - 1);
661 if (str
->Length
>= str
->MaximumLength
)
663 if (str
->MaximumLength
>= sizeof(WCHAR
))
664 str
->Length
= str
->MaximumLength
- sizeof(WCHAR
);
666 str
->Length
= str
->MaximumLength
= 0;
670 static void version(void)
672 MESSAGE( "%s\n", PACKAGE_STRING
);
676 static void usage(void)
678 MESSAGE( "%s\n", PACKAGE_STRING
);
679 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
680 MESSAGE( " wine --help Display this help and exit\n");
681 MESSAGE( " wine --version Output version information and exit\n");
686 /***********************************************************************
687 * init_user_process_params
689 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
691 static RTL_USER_PROCESS_PARAMETERS
*init_user_process_params( size_t info_size
)
694 DWORD size
, env_size
;
695 RTL_USER_PROCESS_PARAMETERS
*params
;
698 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, NULL
, &size
,
699 MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
702 SERVER_START_REQ( get_startup_info
)
704 wine_server_set_reply( req
, ptr
, info_size
);
705 wine_server_call( req
);
706 info_size
= wine_server_reply_size( reply
);
711 params
->AllocationSize
= size
;
712 if (params
->Size
> info_size
) params
->Size
= info_size
;
714 /* make sure the strings are valid */
715 fix_unicode_string( ¶ms
->CurrentDirectory
.DosPath
, (char *)info_size
);
716 fix_unicode_string( ¶ms
->DllPath
, (char *)info_size
);
717 fix_unicode_string( ¶ms
->ImagePathName
, (char *)info_size
);
718 fix_unicode_string( ¶ms
->CommandLine
, (char *)info_size
);
719 fix_unicode_string( ¶ms
->WindowTitle
, (char *)info_size
);
720 fix_unicode_string( ¶ms
->Desktop
, (char *)info_size
);
721 fix_unicode_string( ¶ms
->ShellInfo
, (char *)info_size
);
722 fix_unicode_string( ¶ms
->RuntimeInfo
, (char *)info_size
);
724 /* environment needs to be a separate memory block */
725 env_size
= info_size
- params
->Size
;
726 if (!env_size
) env_size
= 1;
727 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, NULL
, &env_size
,
728 MEM_COMMIT
, PAGE_READWRITE
) != STATUS_SUCCESS
)
730 memcpy( ptr
, (char *)params
+ params
->Size
, info_size
- params
->Size
);
731 params
->Environment
= ptr
;
733 return RtlNormalizeProcessParams( params
);
737 /***********************************************************************
738 * init_current_directory
740 * Initialize the current directory from the Unix cwd or the parent info.
742 static void init_current_directory( CURDIR
*cur_dir
)
744 UNICODE_STRING dir_str
;
748 /* if we received a cur dir from the parent, try this first */
750 if (cur_dir
->DosPath
.Length
)
752 if (RtlSetCurrentDirectory_U( &cur_dir
->DosPath
) == STATUS_SUCCESS
) goto done
;
755 /* now try to get it from the Unix cwd */
757 for (size
= 256; ; size
*= 2)
759 if (!(cwd
= HeapAlloc( GetProcessHeap(), 0, size
))) break;
760 if (getcwd( cwd
, size
)) break;
761 HeapFree( GetProcessHeap(), 0, cwd
);
762 if (errno
== ERANGE
) continue;
770 int lenW
= MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, NULL
, 0 );
771 if ((dirW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) )))
773 MultiByteToWideChar( CP_UNIXCP
, 0, cwd
, -1, dirW
, lenW
);
774 RtlInitUnicodeString( &dir_str
, dirW
);
775 RtlSetCurrentDirectory_U( &dir_str
);
776 RtlFreeUnicodeString( &dir_str
);
780 if (!cur_dir
->DosPath
.Length
) /* still not initialized */
782 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
783 "starting in the Windows directory.\n", cwd
? cwd
: "" );
784 RtlInitUnicodeString( &dir_str
, DIR_Windows
);
785 RtlSetCurrentDirectory_U( &dir_str
);
787 if (cwd
) HeapFree( GetProcessHeap(), 0, cwd
);
790 if (!cur_dir
->Handle
) chdir("/"); /* change to root directory so as not to lock cdroms */
791 TRACE( "starting in %s %p\n", debugstr_w( cur_dir
->DosPath
.Buffer
), cur_dir
->Handle
);
795 /***********************************************************************
798 * Initialize the windows and system directories from the environment.
800 static void init_windows_dirs(void)
802 extern void __wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
);
804 static const WCHAR windirW
[] = {'w','i','n','d','i','r',0};
805 static const WCHAR winsysdirW
[] = {'w','i','n','s','y','s','d','i','r',0};
806 static const WCHAR default_windirW
[] = {'c',':','\\','w','i','n','d','o','w','s',0};
807 static const WCHAR default_sysdirW
[] = {'\\','s','y','s','t','e','m',0};
812 if ((len
= GetEnvironmentVariableW( windirW
, NULL
, 0 )))
814 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
815 GetEnvironmentVariableW( windirW
, buffer
, len
);
816 DIR_Windows
= buffer
;
818 else DIR_Windows
= default_windirW
;
820 if ((len
= GetEnvironmentVariableW( winsysdirW
, NULL
, 0 )))
822 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
823 GetEnvironmentVariableW( winsysdirW
, buffer
, len
);
828 len
= strlenW( DIR_Windows
);
829 buffer
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) + sizeof(default_sysdirW
) );
830 memcpy( buffer
, DIR_Windows
, len
* sizeof(WCHAR
) );
831 memcpy( buffer
+ len
, default_sysdirW
, sizeof(default_sysdirW
) );
835 if (GetFileAttributesW( DIR_Windows
) == INVALID_FILE_ATTRIBUTES
)
836 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
837 debugstr_w(DIR_Windows
) );
838 if (GetFileAttributesW( DIR_System
) == INVALID_FILE_ATTRIBUTES
)
839 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
840 debugstr_w(DIR_System
) );
842 TRACE_(file
)( "WindowsDir = %s\n", debugstr_w(DIR_Windows
) );
843 TRACE_(file
)( "SystemDir = %s\n", debugstr_w(DIR_System
) );
845 /* set the directories in ntdll too */
846 __wine_init_windows_dir( DIR_Windows
, DIR_System
);
850 /***********************************************************************
853 * Main process initialisation code
855 static BOOL
process_init(void)
857 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2',0};
859 size_t info_size
= 0;
860 RTL_USER_PROCESS_PARAMETERS
*params
;
861 PEB
*peb
= NtCurrentTeb()->Peb
;
862 HANDLE hstdin
, hstdout
, hstderr
;
863 extern void __wine_dbg_kernel32_init(void);
867 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
871 setlocale(LC_CTYPE
,"");
873 /* Retrieve startup info from the server */
874 SERVER_START_REQ( init_process
)
877 req
->ldt_copy
= &wine_ldt_copy
;
878 if ((ret
= !wine_server_call_err( req
)))
880 main_exe_file
= reply
->exe_file
;
881 main_create_flags
= reply
->create_flags
;
882 info_size
= reply
->info_size
;
883 server_startticks
= reply
->server_start
;
884 hstdin
= reply
->hstdin
;
885 hstdout
= reply
->hstdout
;
886 hstderr
= reply
->hstderr
;
890 if (!ret
) return FALSE
;
894 params
= peb
->ProcessParameters
;
896 /* This is wine specific: we have no parent (we're started from unix)
897 * so, create a simple console with bare handles to unix stdio
898 * input & output streams (aka simple console)
900 wine_server_fd_to_handle( 0, GENERIC_READ
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdInput
);
901 wine_server_fd_to_handle( 1, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdOutput
);
902 wine_server_fd_to_handle( 2, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
, ¶ms
->hStdError
);
904 params
->CurrentDirectory
.DosPath
.Length
= 0;
905 params
->CurrentDirectory
.DosPath
.MaximumLength
= RtlGetLongestNtPathLength() * sizeof(WCHAR
);
906 params
->CurrentDirectory
.DosPath
.Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, params
->CurrentDirectory
.DosPath
.MaximumLength
);
910 if (!(params
= init_user_process_params( info_size
))) return FALSE
;
911 peb
->ProcessParameters
= params
;
913 /* convert value from server:
914 * + 0 => INVALID_HANDLE_VALUE
915 * + console handle need to be mapped
918 hstdin
= INVALID_HANDLE_VALUE
;
919 else if (VerifyConsoleIoHandle(console_handle_map(hstdin
)))
920 hstdin
= console_handle_map(hstdin
);
923 hstdout
= INVALID_HANDLE_VALUE
;
924 else if (VerifyConsoleIoHandle(console_handle_map(hstdout
)))
925 hstdout
= console_handle_map(hstdout
);
928 hstderr
= INVALID_HANDLE_VALUE
;
929 else if (VerifyConsoleIoHandle(console_handle_map(hstderr
)))
930 hstderr
= console_handle_map(hstderr
);
932 params
->hStdInput
= hstdin
;
933 params
->hStdOutput
= hstdout
;
934 params
->hStdError
= hstderr
;
937 kernel32_handle
= GetModuleHandleW(kernel32W
);
943 /* Copy the parent environment */
944 if (!build_initial_environment( __wine_main_environ
)) return FALSE
;
946 /* Create device symlinks */
947 VOLUME_CreateDevices();
949 /* registry initialisation */
950 SHELL_LoadRegistry();
952 /* global boot finished, the rest is process-local */
953 SERVER_START_REQ( boot_done
)
955 req
->debug_level
= TRACE_ON(server
);
956 wine_server_call( req
);
960 set_registry_environment();
964 init_current_directory( ¶ms
->CurrentDirectory
);
970 /***********************************************************************
973 * Startup routine of a new process. Runs on the new process stack.
975 static void start_process( void *arg
)
979 PEB
*peb
= NtCurrentTeb()->Peb
;
980 IMAGE_NT_HEADERS
*nt
;
981 LPTHREAD_START_ROUTINE entry
;
983 LdrInitializeThunk( main_exe_file
, 0, 0, 0 );
985 nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
986 entry
= (LPTHREAD_START_ROUTINE
)((char *)peb
->ImageBaseAddress
+
987 nt
->OptionalHeader
.AddressOfEntryPoint
);
990 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
991 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
993 SetLastError( 0 ); /* clear error code */
994 if (peb
->BeingDebugged
) DbgBreakPoint();
995 ExitProcess( entry( peb
) );
997 __EXCEPT(UnhandledExceptionFilter
)
999 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1005 /***********************************************************************
1006 * __wine_kernel_init
1008 * Wine initialisation: load and start the main exe file.
1010 void __wine_kernel_init(void)
1012 WCHAR
*main_exe_name
, *p
;
1014 DWORD stack_size
= 0;
1016 PEB
*peb
= NtCurrentTeb()->Peb
;
1018 /* Initialize everything */
1019 if (!process_init()) exit(1);
1021 __wine_main_argv
++; /* remove argv[0] (wine itself) */
1024 if (!(main_exe_name
= peb
->ProcessParameters
->ImagePathName
.Buffer
))
1026 WCHAR buffer
[MAX_PATH
];
1027 WCHAR exe_nameW
[MAX_PATH
];
1029 if (!__wine_main_argv
[0]) usage();
1030 if (__wine_main_argc
== 1)
1032 if (strcmp(__wine_main_argv
[0], "--help") == 0) usage();
1033 if (strcmp(__wine_main_argv
[0], "--version") == 0) version();
1036 MultiByteToWideChar( CP_UNIXCP
, 0, __wine_main_argv
[0], -1, exe_nameW
, MAX_PATH
);
1037 if (!find_exe_file( exe_nameW
, buffer
, MAX_PATH
, &main_exe_file
))
1039 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv
[0] );
1042 if (main_exe_file
== INVALID_HANDLE_VALUE
)
1044 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name
) );
1047 RtlCreateUnicodeString( &peb
->ProcessParameters
->ImagePathName
, buffer
);
1048 main_exe_name
= peb
->ProcessParameters
->ImagePathName
.Buffer
;
1051 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1052 debugstr_w(main_exe_name
), main_exe_file
, debugstr_a(__wine_main_argv
[0]) );
1054 RtlInitUnicodeString( &NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
,
1055 MODULE_get_dll_load_path(NULL
) );
1056 VERSION_Init( main_exe_name
);
1058 if (!main_exe_file
) /* no file handle -> Winelib app */
1060 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name
) );
1061 if (open_builtin_exe_file( main_exe_name
, error
, sizeof(error
), 0, &file_exists
))
1063 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1064 debugstr_w(main_exe_name
), error
);
1068 switch( MODULE_GetBinaryType( main_exe_file
, NULL
, NULL
))
1071 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name
) );
1072 if ((peb
->ImageBaseAddress
= load_pe_exe( main_exe_name
, main_exe_file
)))
1074 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name
) );
1077 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name
) );
1079 case BINARY_UNKNOWN
:
1080 /* check for .com extension */
1081 if (!(p
= strrchrW( main_exe_name
, '.' )) || strcmpiW( p
, comW
))
1083 MESSAGE( "wine: cannot determine executable type for %s\n",
1084 debugstr_w(main_exe_name
) );
1090 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name
) );
1091 CloseHandle( main_exe_file
);
1095 __wine_main_argv
[0] = "winevdm.exe";
1096 if (open_builtin_exe_file( winevdmW
, error
, sizeof(error
), 0, &file_exists
))
1098 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1099 debugstr_w(main_exe_name
), error
);
1102 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name
) );
1104 case BINARY_UNIX_EXE
:
1105 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name
) );
1107 case BINARY_UNIX_LIB
:
1111 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name
) );
1112 CloseHandle( main_exe_file
);
1114 if ((unix_name
= wine_get_unix_file_name( main_exe_name
)) &&
1115 wine_dlopen( unix_name
, RTLD_NOW
, error
, sizeof(error
) ))
1117 static const WCHAR soW
[] = {'.','s','o',0};
1118 if ((p
= strrchrW( main_exe_name
, '.' )) && !strcmpW( p
, soW
))
1121 /* update the unicode string */
1122 RtlInitUnicodeString( &peb
->ProcessParameters
->ImagePathName
, main_exe_name
);
1124 HeapFree( GetProcessHeap(), 0, unix_name
);
1127 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name
), error
);
1133 /* build command line */
1134 set_library_wargv( __wine_main_argv
);
1135 if (!build_command_line( __wine_main_wargv
)) goto error
;
1137 stack_size
= RtlImageNtHeader(peb
->ImageBaseAddress
)->OptionalHeader
.SizeOfStackReserve
;
1139 /* allocate main thread stack */
1140 if (!THREAD_InitStack( NtCurrentTeb(), stack_size
)) goto error
;
1142 /* switch to the new stack */
1143 wine_switch_to_stack( start_process
, NULL
, NtCurrentTeb()->Tib
.StackBase
);
1146 ExitProcess( GetLastError() );
1150 /***********************************************************************
1153 * Build an argv array from a command-line.
1154 * 'reserved' is the number of args to reserve before the first one.
1156 static char **build_argv( const WCHAR
*cmdlineW
, int reserved
)
1160 char *arg
,*s
,*d
,*cmdline
;
1161 int in_quotes
,bcount
,len
;
1163 len
= WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, NULL
, 0, NULL
, NULL
);
1164 if (!(cmdline
= malloc(len
))) return NULL
;
1165 WideCharToMultiByte( CP_UNIXCP
, 0, cmdlineW
, -1, cmdline
, len
, NULL
, NULL
);
1172 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
1175 /* skip the remaining spaces */
1176 while (*s
==' ' || *s
=='\t') {
1183 } else if (*s
=='\\') {
1184 /* '\', count them */
1186 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
1188 in_quotes
=!in_quotes
;
1191 /* a regular character */
1196 argv
=malloc(argc
*sizeof(*argv
));
1205 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
1206 /* Close the argument and copy it */
1210 /* skip the remaining spaces */
1213 } while (*s
==' ' || *s
=='\t');
1215 /* Start with a new argument */
1218 } else if (*s
=='\\') {
1222 } else if (*s
=='"') {
1224 if ((bcount
& 1)==0) {
1225 /* Preceeded by an even number of '\', this is half that
1226 * number of '\', plus a '"' which we discard.
1230 in_quotes
=!in_quotes
;
1232 /* Preceeded by an odd number of '\', this is half that
1233 * number of '\' followed by a '"'
1241 /* a regular character */
1256 /***********************************************************************
1259 * Allocate an environment string; helper for build_envp
1261 static char *alloc_env_string( const char *name
, const char *value
)
1263 char *ret
= malloc( strlen(name
) + strlen(value
) + 1 );
1264 strcpy( ret
, name
);
1265 strcat( ret
, value
);
1269 /***********************************************************************
1272 * Build the environment of a new child process.
1274 static char **build_envp( const WCHAR
*envW
)
1279 int count
= 0, length
;
1281 for (end
= envW
; *end
; count
++) end
+= strlenW(end
) + 1;
1283 length
= WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, NULL
, 0, NULL
, NULL
);
1284 if (!(env
= malloc( length
))) return NULL
;
1285 WideCharToMultiByte( CP_UNIXCP
, 0, envW
, end
- envW
, env
, length
, NULL
, NULL
);
1289 if ((envp
= malloc( count
* sizeof(*envp
) )))
1291 char **envptr
= envp
;
1293 /* some variables must not be modified, so we get them directly from the unix env */
1294 if ((p
= getenv("PATH"))) *envptr
++ = alloc_env_string( "PATH=", p
);
1295 if ((p
= getenv("TEMP"))) *envptr
++ = alloc_env_string( "TEMP=", p
);
1296 if ((p
= getenv("TMP"))) *envptr
++ = alloc_env_string( "TMP=", p
);
1297 if ((p
= getenv("HOME"))) *envptr
++ = alloc_env_string( "HOME=", p
);
1298 /* now put the Windows environment strings */
1299 for (p
= env
; *p
; p
+= strlen(p
) + 1)
1301 if (*p
== '=') continue; /* skip drive curdirs, this crashes some unix apps */
1302 if (!strncmp( p
, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1303 if (is_special_env_var( p
)) /* prefix it with "WINE" */
1304 *envptr
++ = alloc_env_string( "WINE", p
);
1314 /***********************************************************************
1317 * Fork and exec a new Unix binary, checking for errors.
1319 static int fork_and_exec( const char *filename
, const WCHAR
*cmdline
,
1320 const WCHAR
*env
, const char *newdir
)
1325 if (!env
) env
= GetEnvironmentStringsW();
1329 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1332 fcntl( fd
[1], F_SETFD
, 1 ); /* set close on exec */
1333 if (!(pid
= fork())) /* child */
1335 char **argv
= build_argv( cmdline
, 0 );
1336 char **envp
= build_envp( env
);
1339 /* Reset signals that we previously set to SIG_IGN */
1340 signal( SIGPIPE
, SIG_DFL
);
1341 signal( SIGCHLD
, SIG_DFL
);
1343 if (newdir
) chdir(newdir
);
1345 if (argv
&& envp
) execve( filename
, argv
, envp
);
1347 write( fd
[1], &err
, sizeof(err
) );
1351 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
1356 if (pid
== -1) FILE_SetDosError();
1362 /***********************************************************************
1363 * create_user_params
1365 static RTL_USER_PROCESS_PARAMETERS
*create_user_params( LPCWSTR filename
, LPCWSTR cmdline
,
1366 LPCWSTR cur_dir
, LPWSTR env
,
1367 const STARTUPINFOW
*startup
)
1369 RTL_USER_PROCESS_PARAMETERS
*params
;
1370 UNICODE_STRING image_str
, cmdline_str
, curdir_str
, desktop
, title
;
1372 WCHAR buffer
[MAX_PATH
];
1374 if(!GetLongPathNameW( filename
, buffer
, MAX_PATH
))
1375 lstrcpynW( buffer
, filename
, MAX_PATH
);
1376 if(!GetFullPathNameW( buffer
, MAX_PATH
, buffer
, NULL
))
1377 lstrcpynW( buffer
, filename
, MAX_PATH
);
1378 RtlInitUnicodeString( &image_str
, buffer
);
1380 RtlInitUnicodeString( &cmdline_str
, cmdline
);
1381 if (cur_dir
) RtlInitUnicodeString( &curdir_str
, cur_dir
);
1382 if (startup
->lpDesktop
) RtlInitUnicodeString( &desktop
, startup
->lpDesktop
);
1383 if (startup
->lpTitle
) RtlInitUnicodeString( &title
, startup
->lpTitle
);
1385 status
= RtlCreateProcessParameters( ¶ms
, &image_str
, NULL
,
1386 cur_dir
? &curdir_str
: NULL
,
1388 startup
->lpTitle
? &title
: NULL
,
1389 startup
->lpDesktop
? &desktop
: NULL
,
1391 if (status
!= STATUS_SUCCESS
)
1393 SetLastError( RtlNtStatusToDosError(status
) );
1397 params
->hStdInput
= startup
->hStdInput
;
1398 params
->hStdOutput
= startup
->hStdOutput
;
1399 params
->hStdError
= startup
->hStdError
;
1400 params
->dwX
= startup
->dwX
;
1401 params
->dwY
= startup
->dwY
;
1402 params
->dwXSize
= startup
->dwXSize
;
1403 params
->dwYSize
= startup
->dwYSize
;
1404 params
->dwXCountChars
= startup
->dwXCountChars
;
1405 params
->dwYCountChars
= startup
->dwYCountChars
;
1406 params
->dwFillAttribute
= startup
->dwFillAttribute
;
1407 params
->dwFlags
= startup
->dwFlags
;
1408 params
->wShowWindow
= startup
->wShowWindow
;
1413 /***********************************************************************
1416 * Create a new process. If hFile is a valid handle we have an exe
1417 * file, otherwise it is a Winelib app.
1419 static BOOL
create_process( HANDLE hFile
, LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
,
1420 LPCWSTR cur_dir
, LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1421 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1422 LPPROCESS_INFORMATION info
, LPCSTR unixdir
,
1423 void *res_start
, void *res_end
)
1425 BOOL ret
, success
= FALSE
;
1426 HANDLE process_info
;
1428 RTL_USER_PROCESS_PARAMETERS
*params
;
1434 char preloader_reserve
[64];
1436 if (!env
) RtlAcquirePebLock();
1438 if (!(params
= create_user_params( filename
, cmd_line
, cur_dir
, env
, startup
)))
1440 if (!env
) RtlReleasePebLock();
1443 env_end
= params
->Environment
;
1444 while (*env_end
) env_end
+= strlenW(env_end
) + 1;
1447 sprintf( preloader_reserve
, "WINEPRELOADRESERVE=%lx-%lx%c",
1448 (unsigned long)res_start
, (unsigned long)res_end
, 0 );
1450 /* create the synchronization pipes */
1452 if (pipe( startfd
) == -1)
1454 if (!env
) RtlReleasePebLock();
1455 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1456 RtlDestroyProcessParameters( params
);
1459 if (pipe( execfd
) == -1)
1461 if (!env
) RtlReleasePebLock();
1462 SetLastError( ERROR_TOO_MANY_OPEN_FILES
);
1463 close( startfd
[0] );
1464 close( startfd
[1] );
1465 RtlDestroyProcessParameters( params
);
1468 fcntl( execfd
[1], F_SETFD
, 1 ); /* set close on exec */
1470 /* create the child process */
1472 if (!(pid
= fork())) /* child */
1474 char **argv
= build_argv( cmd_line
, 1 );
1476 close( startfd
[1] );
1479 /* wait for parent to tell us to start */
1480 if (read( startfd
[0], &dummy
, 1 ) != 1) _exit(1);
1482 close( startfd
[0] );
1483 /* Reset signals that we previously set to SIG_IGN */
1484 signal( SIGPIPE
, SIG_DFL
);
1485 signal( SIGCHLD
, SIG_DFL
);
1487 putenv( preloader_reserve
);
1488 if (unixdir
) chdir(unixdir
);
1492 /* first, try for a WINELOADER environment variable */
1493 const char *loader
= getenv("WINELOADER");
1494 if (loader
) wine_exec_wine_binary( loader
, argv
, NULL
, TRUE
);
1495 /* now use the standard search strategy */
1496 wine_exec_wine_binary( NULL
, argv
, NULL
, TRUE
);
1499 write( execfd
[1], &err
, sizeof(err
) );
1503 /* this is the parent */
1505 close( startfd
[0] );
1509 if (!env
) RtlReleasePebLock();
1510 close( startfd
[1] );
1513 RtlDestroyProcessParameters( params
);
1517 /* create the process on the server side */
1519 SERVER_START_REQ( new_process
)
1521 req
->inherit_all
= inherit
;
1522 req
->create_flags
= flags
;
1523 req
->unix_pid
= pid
;
1524 req
->exe_file
= hFile
;
1525 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
1527 req
->hstdin
= startup
->hStdInput
;
1528 req
->hstdout
= startup
->hStdOutput
;
1529 req
->hstderr
= startup
->hStdError
;
1533 req
->hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
1534 req
->hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
1535 req
->hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
1538 if ((flags
& (CREATE_NEW_CONSOLE
| DETACHED_PROCESS
)) != 0)
1540 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1541 if (is_console_handle(req
->hstdin
)) req
->hstdin
= INVALID_HANDLE_VALUE
;
1542 if (is_console_handle(req
->hstdout
)) req
->hstdout
= INVALID_HANDLE_VALUE
;
1543 if (is_console_handle(req
->hstderr
)) req
->hstderr
= INVALID_HANDLE_VALUE
;
1547 if (is_console_handle(req
->hstdin
)) req
->hstdin
= console_handle_unmap(req
->hstdin
);
1548 if (is_console_handle(req
->hstdout
)) req
->hstdout
= console_handle_unmap(req
->hstdout
);
1549 if (is_console_handle(req
->hstderr
)) req
->hstderr
= console_handle_unmap(req
->hstderr
);
1552 wine_server_add_data( req
, params
, params
->Size
);
1553 wine_server_add_data( req
, params
->Environment
, (env_end
-params
->Environment
)*sizeof(WCHAR
) );
1554 ret
= !wine_server_call_err( req
);
1555 process_info
= reply
->info
;
1559 if (!env
) RtlReleasePebLock();
1560 RtlDestroyProcessParameters( params
);
1563 close( startfd
[1] );
1568 /* tell child to start and wait for it to exec */
1570 write( startfd
[1], &dummy
, 1 );
1571 close( startfd
[1] );
1573 if (read( execfd
[0], &err
, sizeof(err
) ) > 0) /* exec failed */
1578 CloseHandle( process_info
);
1583 /* wait for the new process info to be ready */
1585 WaitForSingleObject( process_info
, INFINITE
);
1586 SERVER_START_REQ( get_new_process_info
)
1588 req
->info
= process_info
;
1589 req
->pinherit
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
);
1590 req
->tinherit
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
);
1591 if ((ret
= !wine_server_call_err( req
)))
1593 info
->dwProcessId
= (DWORD
)reply
->pid
;
1594 info
->dwThreadId
= (DWORD
)reply
->tid
;
1595 info
->hProcess
= reply
->phandle
;
1596 info
->hThread
= reply
->thandle
;
1597 success
= reply
->success
;
1602 if (ret
&& !success
) /* new process failed to start */
1605 if (GetExitCodeProcess( info
->hProcess
, &exitcode
)) SetLastError( exitcode
);
1606 CloseHandle( info
->hThread
);
1607 CloseHandle( info
->hProcess
);
1610 CloseHandle( process_info
);
1615 /***********************************************************************
1616 * create_vdm_process
1618 * Create a new VDM process for a 16-bit or DOS application.
1620 static BOOL
create_vdm_process( LPCWSTR filename
, LPWSTR cmd_line
, LPWSTR env
, LPCWSTR cur_dir
,
1621 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1622 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1623 LPPROCESS_INFORMATION info
, LPCSTR unixdir
)
1625 static const WCHAR argsW
[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1628 LPWSTR new_cmd_line
= HeapAlloc( GetProcessHeap(), 0,
1629 (strlenW(filename
) + strlenW(cmd_line
) + 30) * sizeof(WCHAR
) );
1633 SetLastError( ERROR_OUTOFMEMORY
);
1636 sprintfW( new_cmd_line
, argsW
, winevdmW
, filename
, cmd_line
);
1637 ret
= create_process( 0, winevdmW
, new_cmd_line
, env
, cur_dir
, psa
, tsa
, inherit
,
1638 flags
, startup
, info
, unixdir
, NULL
, NULL
);
1639 HeapFree( GetProcessHeap(), 0, new_cmd_line
);
1644 /***********************************************************************
1645 * create_cmd_process
1647 * Create a new cmd shell process for a .BAT file.
1649 static BOOL
create_cmd_process( LPCWSTR filename
, LPWSTR cmd_line
, LPVOID env
, LPCWSTR cur_dir
,
1650 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
1651 BOOL inherit
, DWORD flags
, LPSTARTUPINFOW startup
,
1652 LPPROCESS_INFORMATION info
)
1655 static const WCHAR comspecW
[] = {'C','O','M','S','P','E','C',0};
1656 static const WCHAR slashcW
[] = {' ','/','c',' ',0};
1657 WCHAR comspec
[MAX_PATH
];
1661 if (!GetEnvironmentVariableW( comspecW
, comspec
, sizeof(comspec
)/sizeof(WCHAR
) ))
1663 if (!(newcmdline
= HeapAlloc( GetProcessHeap(), 0,
1664 (strlenW(comspec
) + 4 + strlenW(cmd_line
) + 1) * sizeof(WCHAR
))))
1667 strcpyW( newcmdline
, comspec
);
1668 strcatW( newcmdline
, slashcW
);
1669 strcatW( newcmdline
, cmd_line
);
1670 ret
= CreateProcessW( comspec
, newcmdline
, psa
, tsa
, inherit
,
1671 flags
, env
, cur_dir
, startup
, info
);
1672 HeapFree( GetProcessHeap(), 0, newcmdline
);
1677 /*************************************************************************
1680 * Helper for CreateProcess: retrieve the file name to load from the
1681 * app name and command line. Store the file name in buffer, and
1682 * return a possibly modified command line.
1683 * Also returns a handle to the opened file if it's a Windows binary.
1685 static LPWSTR
get_file_name( LPCWSTR appname
, LPWSTR cmdline
, LPWSTR buffer
,
1686 int buflen
, HANDLE
*handle
)
1688 static const WCHAR quotesW
[] = {'"','%','s','"',0};
1690 WCHAR
*name
, *pos
, *ret
= NULL
;
1693 /* if we have an app name, everything is easy */
1697 /* use the unmodified app name as file name */
1698 lstrcpynW( buffer
, appname
, buflen
);
1699 *handle
= open_exe_file( buffer
);
1700 if (!(ret
= cmdline
) || !cmdline
[0])
1702 /* no command-line, create one */
1703 if ((ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(appname
) + 3) * sizeof(WCHAR
) )))
1704 sprintfW( ret
, quotesW
, appname
);
1711 SetLastError( ERROR_INVALID_PARAMETER
);
1715 /* first check for a quoted file name */
1717 if ((cmdline
[0] == '"') && ((p
= strchrW( cmdline
+ 1, '"' ))))
1719 int len
= p
- cmdline
- 1;
1720 /* extract the quoted portion as file name */
1721 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) ))) return NULL
;
1722 memcpy( name
, cmdline
+ 1, len
* sizeof(WCHAR
) );
1725 if (find_exe_file( name
, buffer
, buflen
, handle
))
1726 ret
= cmdline
; /* no change necessary */
1730 /* now try the command-line word by word */
1732 if (!(name
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 1) * sizeof(WCHAR
) )))
1739 do *pos
++ = *p
++; while (*p
&& *p
!= ' ');
1741 if (find_exe_file( name
, buffer
, buflen
, handle
))
1748 if (!ret
|| !strchrW( name
, ' ' )) goto done
; /* no change necessary */
1750 /* now build a new command-line with quotes */
1752 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline
) + 3) * sizeof(WCHAR
) )))
1754 sprintfW( ret
, quotesW
, name
);
1758 HeapFree( GetProcessHeap(), 0, name
);
1763 /**********************************************************************
1764 * CreateProcessA (KERNEL32.@)
1766 BOOL WINAPI
CreateProcessA( LPCSTR app_name
, LPSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1767 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
,
1768 DWORD flags
, LPVOID env
, LPCSTR cur_dir
,
1769 LPSTARTUPINFOA startup_info
, LPPROCESS_INFORMATION info
)
1772 WCHAR
*app_nameW
= NULL
, *cmd_lineW
= NULL
, *cur_dirW
= NULL
;
1773 UNICODE_STRING desktopW
, titleW
;
1776 desktopW
.Buffer
= NULL
;
1777 titleW
.Buffer
= NULL
;
1778 if (app_name
&& !(app_nameW
= FILE_name_AtoW( app_name
, TRUE
))) goto done
;
1779 if (cmd_line
&& !(cmd_lineW
= FILE_name_AtoW( cmd_line
, TRUE
))) goto done
;
1780 if (cur_dir
&& !(cur_dirW
= FILE_name_AtoW( cur_dir
, TRUE
))) goto done
;
1782 if (startup_info
->lpDesktop
) RtlCreateUnicodeStringFromAsciiz( &desktopW
, startup_info
->lpDesktop
);
1783 if (startup_info
->lpTitle
) RtlCreateUnicodeStringFromAsciiz( &titleW
, startup_info
->lpTitle
);
1785 memcpy( &infoW
, startup_info
, sizeof(infoW
) );
1786 infoW
.lpDesktop
= desktopW
.Buffer
;
1787 infoW
.lpTitle
= titleW
.Buffer
;
1789 if (startup_info
->lpReserved
)
1790 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1791 debugstr_a(startup_info
->lpReserved
));
1793 ret
= CreateProcessW( app_nameW
, cmd_lineW
, process_attr
, thread_attr
,
1794 inherit
, flags
, env
, cur_dirW
, &infoW
, info
);
1796 if (app_nameW
) HeapFree( GetProcessHeap(), 0, app_nameW
);
1797 if (cmd_lineW
) HeapFree( GetProcessHeap(), 0, cmd_lineW
);
1798 if (cur_dirW
) HeapFree( GetProcessHeap(), 0, cur_dirW
);
1799 RtlFreeUnicodeString( &desktopW
);
1800 RtlFreeUnicodeString( &titleW
);
1805 /**********************************************************************
1806 * CreateProcessW (KERNEL32.@)
1808 BOOL WINAPI
CreateProcessW( LPCWSTR app_name
, LPWSTR cmd_line
, LPSECURITY_ATTRIBUTES process_attr
,
1809 LPSECURITY_ATTRIBUTES thread_attr
, BOOL inherit
, DWORD flags
,
1810 LPVOID env
, LPCWSTR cur_dir
, LPSTARTUPINFOW startup_info
,
1811 LPPROCESS_INFORMATION info
)
1815 char *unixdir
= NULL
;
1816 WCHAR name
[MAX_PATH
];
1817 WCHAR
*tidy_cmdline
, *p
, *envW
= env
;
1818 void *res_start
, *res_end
;
1820 /* Process the AppName and/or CmdLine to get module name and path */
1822 TRACE("app %s cmdline %s\n", debugstr_w(app_name
), debugstr_w(cmd_line
) );
1824 if (!(tidy_cmdline
= get_file_name( app_name
, cmd_line
, name
, sizeof(name
), &hFile
)))
1826 if (hFile
== INVALID_HANDLE_VALUE
) goto done
;
1828 /* Warn if unsupported features are used */
1830 if (flags
& (IDLE_PRIORITY_CLASS
| HIGH_PRIORITY_CLASS
| REALTIME_PRIORITY_CLASS
|
1831 CREATE_NEW_PROCESS_GROUP
| CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
|
1832 CREATE_DEFAULT_ERROR_MODE
| CREATE_NO_WINDOW
|
1833 PROFILE_USER
| PROFILE_KERNEL
| PROFILE_SERVER
))
1834 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name
), flags
);
1838 unixdir
= wine_get_unix_file_name( cur_dir
);
1842 WCHAR buf
[MAX_PATH
];
1843 if (GetCurrentDirectoryW(MAX_PATH
, buf
)) unixdir
= wine_get_unix_file_name( buf
);
1846 if (env
&& !(flags
& CREATE_UNICODE_ENVIRONMENT
)) /* convert environment to unicode */
1851 while (*p
) p
+= strlen(p
) + 1;
1852 p
++; /* final null */
1853 lenW
= MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, NULL
, 0 );
1854 envW
= HeapAlloc( GetProcessHeap(), 0, lenW
* sizeof(WCHAR
) );
1855 MultiByteToWideChar( CP_ACP
, 0, env
, p
- (char*)env
, envW
, lenW
);
1856 flags
|= CREATE_UNICODE_ENVIRONMENT
;
1859 info
->hThread
= info
->hProcess
= 0;
1860 info
->dwProcessId
= info
->dwThreadId
= 0;
1862 /* Determine executable type */
1864 if (!hFile
) /* builtin exe */
1866 TRACE( "starting %s as Winelib app\n", debugstr_w(name
) );
1867 retv
= create_process( 0, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1868 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
);
1872 switch( MODULE_GetBinaryType( hFile
, &res_start
, &res_end
))
1875 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name
), res_start
, res_end
);
1876 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1877 inherit
, flags
, startup_info
, info
, unixdir
, res_start
, res_end
);
1881 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name
) );
1882 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1883 inherit
, flags
, startup_info
, info
, unixdir
);
1886 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name
) );
1887 SetLastError( ERROR_BAD_EXE_FORMAT
);
1890 TRACE( "not starting %s since it is a dll\n", debugstr_w(name
) );
1891 SetLastError( ERROR_BAD_EXE_FORMAT
);
1893 case BINARY_UNIX_LIB
:
1894 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name
) );
1895 retv
= create_process( hFile
, name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1896 inherit
, flags
, startup_info
, info
, unixdir
, NULL
, NULL
);
1898 case BINARY_UNKNOWN
:
1899 /* check for .com or .bat extension */
1900 if ((p
= strrchrW( name
, '.' )))
1902 if (!strcmpiW( p
, comW
))
1904 TRACE( "starting %s as DOS binary\n", debugstr_w(name
) );
1905 retv
= create_vdm_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1906 inherit
, flags
, startup_info
, info
, unixdir
);
1909 if (!strcmpiW( p
, batW
))
1911 TRACE( "starting %s as batch binary\n", debugstr_w(name
) );
1912 retv
= create_cmd_process( name
, tidy_cmdline
, envW
, cur_dir
, process_attr
, thread_attr
,
1913 inherit
, flags
, startup_info
, info
);
1918 case BINARY_UNIX_EXE
:
1920 /* unknown file, try as unix executable */
1923 TRACE( "starting %s as Unix binary\n", debugstr_w(name
) );
1925 if ((unix_name
= wine_get_unix_file_name( name
)))
1927 retv
= (fork_and_exec( unix_name
, tidy_cmdline
, envW
, unixdir
) != -1);
1928 HeapFree( GetProcessHeap(), 0, unix_name
);
1933 CloseHandle( hFile
);
1936 if (tidy_cmdline
!= cmd_line
) HeapFree( GetProcessHeap(), 0, tidy_cmdline
);
1937 if (envW
!= env
) HeapFree( GetProcessHeap(), 0, envW
);
1938 if (unixdir
) HeapFree( GetProcessHeap(), 0, unixdir
);
1943 /***********************************************************************
1946 * Wrapper to call WaitForInputIdle USER function
1948 typedef DWORD (WINAPI
*WaitForInputIdle_ptr
)( HANDLE hProcess
, DWORD dwTimeOut
);
1950 static DWORD
wait_input_idle( HANDLE process
, DWORD timeout
)
1952 HMODULE mod
= GetModuleHandleA( "user32.dll" );
1955 WaitForInputIdle_ptr ptr
= (WaitForInputIdle_ptr
)GetProcAddress( mod
, "WaitForInputIdle" );
1956 if (ptr
) return ptr( process
, timeout
);
1962 /***********************************************************************
1963 * WinExec (KERNEL32.@)
1965 UINT WINAPI
WinExec( LPCSTR lpCmdLine
, UINT nCmdShow
)
1967 PROCESS_INFORMATION info
;
1968 STARTUPINFOA startup
;
1972 memset( &startup
, 0, sizeof(startup
) );
1973 startup
.cb
= sizeof(startup
);
1974 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
1975 startup
.wShowWindow
= nCmdShow
;
1977 /* cmdline needs to be writeable for CreateProcess */
1978 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine
)+1 ))) return 0;
1979 strcpy( cmdline
, lpCmdLine
);
1981 if (CreateProcessA( NULL
, cmdline
, NULL
, NULL
, FALSE
,
1982 0, NULL
, NULL
, &startup
, &info
))
1984 /* Give 30 seconds to the app to come up */
1985 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
1986 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1988 /* Close off the handles */
1989 CloseHandle( info
.hThread
);
1990 CloseHandle( info
.hProcess
);
1992 else if ((ret
= GetLastError()) >= 32)
1994 FIXME("Strange error set by CreateProcess: %d\n", ret
);
1997 HeapFree( GetProcessHeap(), 0, cmdline
);
2002 /**********************************************************************
2003 * LoadModule (KERNEL32.@)
2005 HINSTANCE WINAPI
LoadModule( LPCSTR name
, LPVOID paramBlock
)
2007 LOADPARMS32
*params
= paramBlock
;
2008 PROCESS_INFORMATION info
;
2009 STARTUPINFOA startup
;
2010 HINSTANCE hInstance
;
2012 char filename
[MAX_PATH
];
2015 if (!name
) return (HINSTANCE
)ERROR_FILE_NOT_FOUND
;
2017 if (!SearchPathA( NULL
, name
, ".exe", sizeof(filename
), filename
, NULL
) &&
2018 !SearchPathA( NULL
, name
, NULL
, sizeof(filename
), filename
, NULL
))
2019 return (HINSTANCE
)GetLastError();
2021 len
= (BYTE
)params
->lpCmdLine
[0];
2022 if (!(cmdline
= HeapAlloc( GetProcessHeap(), 0, strlen(filename
) + len
+ 2 )))
2023 return (HINSTANCE
)ERROR_NOT_ENOUGH_MEMORY
;
2025 strcpy( cmdline
, filename
);
2026 p
= cmdline
+ strlen(cmdline
);
2028 memcpy( p
, params
->lpCmdLine
+ 1, len
);
2031 memset( &startup
, 0, sizeof(startup
) );
2032 startup
.cb
= sizeof(startup
);
2033 if (params
->lpCmdShow
)
2035 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
2036 startup
.wShowWindow
= ((WORD
*)params
->lpCmdShow
)[1];
2039 if (CreateProcessA( filename
, cmdline
, NULL
, NULL
, FALSE
, 0,
2040 params
->lpEnvAddress
, NULL
, &startup
, &info
))
2042 /* Give 30 seconds to the app to come up */
2043 if (wait_input_idle( info
.hProcess
, 30000 ) == WAIT_FAILED
)
2044 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2045 hInstance
= (HINSTANCE
)33;
2046 /* Close off the handles */
2047 CloseHandle( info
.hThread
);
2048 CloseHandle( info
.hProcess
);
2050 else if ((hInstance
= (HINSTANCE
)GetLastError()) >= (HINSTANCE
)32)
2052 FIXME("Strange error set by CreateProcess: %p\n", hInstance
);
2053 hInstance
= (HINSTANCE
)11;
2056 HeapFree( GetProcessHeap(), 0, cmdline
);
2061 /******************************************************************************
2062 * TerminateProcess (KERNEL32.@)
2064 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
2066 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
2067 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2072 /***********************************************************************
2073 * ExitProcess (KERNEL32.@)
2075 void WINAPI
ExitProcess( DWORD status
)
2077 LdrShutdownProcess();
2078 SERVER_START_REQ( terminate_process
)
2080 /* send the exit code to the server */
2081 req
->handle
= GetCurrentProcess();
2082 req
->exit_code
= status
;
2083 wine_server_call( req
);
2090 /***********************************************************************
2091 * GetExitCodeProcess [KERNEL32.@]
2093 * Gets termination status of specified process
2099 BOOL WINAPI
GetExitCodeProcess(
2100 HANDLE hProcess
, /* [in] handle to the process */
2101 LPDWORD lpExitCode
) /* [out] address to receive termination status */
2104 PROCESS_BASIC_INFORMATION pbi
;
2106 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2108 if (status
== STATUS_SUCCESS
)
2110 if (lpExitCode
) *lpExitCode
= pbi
.ExitStatus
;
2113 SetLastError( RtlNtStatusToDosError(status
) );
2118 /***********************************************************************
2119 * SetErrorMode (KERNEL32.@)
2121 UINT WINAPI
SetErrorMode( UINT mode
)
2123 UINT old
= process_error_mode
;
2124 process_error_mode
= mode
;
2129 /**********************************************************************
2130 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2132 * Allocates a thread local storage index
2135 * Success: TLS Index
2136 * Failure: 0xFFFFFFFF
2138 DWORD WINAPI
TlsAlloc( void )
2142 RtlAcquirePebLock();
2143 index
= RtlFindClearBitsAndSet( NtCurrentTeb()->Peb
->TlsBitmap
, 1, 0 );
2144 if (index
!= ~0UL) NtCurrentTeb()->TlsSlots
[index
] = 0; /* clear the value */
2145 else SetLastError( ERROR_NO_MORE_ITEMS
);
2146 RtlReleasePebLock();
2151 /**********************************************************************
2152 * TlsFree [KERNEL32.@] Releases a TLS index.
2154 * Releases a thread local storage index, making it available for reuse
2160 BOOL WINAPI
TlsFree(
2161 DWORD index
) /* [in] TLS Index to free */
2165 RtlAcquirePebLock();
2166 ret
= RtlAreBitsSet( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2169 RtlClearBits( NtCurrentTeb()->Peb
->TlsBitmap
, index
, 1 );
2170 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell
, &index
, sizeof(index
) );
2172 else SetLastError( ERROR_INVALID_PARAMETER
);
2173 RtlReleasePebLock();
2178 /**********************************************************************
2179 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2182 * Success: Value stored in calling thread's TLS slot for index
2183 * Failure: 0 and GetLastError returns NO_ERROR
2185 LPVOID WINAPI
TlsGetValue(
2186 DWORD index
) /* [in] TLS index to retrieve value for */
2188 if (index
>= NtCurrentTeb()->Peb
->TlsBitmap
->SizeOfBitMap
)
2190 SetLastError( ERROR_INVALID_PARAMETER
);
2193 SetLastError( ERROR_SUCCESS
);
2194 return NtCurrentTeb()->TlsSlots
[index
];
2198 /**********************************************************************
2199 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2205 BOOL WINAPI
TlsSetValue(
2206 DWORD index
, /* [in] TLS index to set value for */
2207 LPVOID value
) /* [in] Value to be stored */
2209 if (index
>= NtCurrentTeb()->Peb
->TlsBitmap
->SizeOfBitMap
)
2211 SetLastError( ERROR_INVALID_PARAMETER
);
2214 NtCurrentTeb()->TlsSlots
[index
] = value
;
2219 /***********************************************************************
2220 * GetProcessFlags (KERNEL32.@)
2222 DWORD WINAPI
GetProcessFlags( DWORD processid
)
2224 IMAGE_NT_HEADERS
*nt
;
2227 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
2229 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2231 if (nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
2232 flags
|= PDB32_CONSOLE_PROC
;
2234 if (!AreFileApisANSI()) flags
|= PDB32_FILE_APIS_OEM
;
2235 if (IsDebuggerPresent()) flags
|= PDB32_DEBUGGED
;
2240 /***********************************************************************
2241 * GetProcessDword (KERNEL.485)
2242 * GetProcessDword (KERNEL32.18)
2243 * 'Of course you cannot directly access Windows internal structures'
2245 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
2250 TRACE("(%ld, %d)\n", dwProcessID
, offset
);
2252 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2254 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
2260 case GPD_APP_COMPAT_FLAGS
:
2261 return GetAppCompatFlags16(0);
2262 case GPD_LOAD_DONE_EVENT
:
2264 case GPD_HINSTANCE16
:
2265 return GetTaskDS16();
2266 case GPD_WINDOWS_VERSION
:
2267 return GetExeVersion16();
2269 return (DWORD
)NtCurrentTeb() - 0x10 /* FIXME */;
2271 return (DWORD
)NtCurrentTeb()->Peb
;
2272 case GPD_STARTF_SHELLDATA
: /* return stdoutput handle from startupinfo ??? */
2273 GetStartupInfoW(&siw
);
2274 return (DWORD
)siw
.hStdOutput
;
2275 case GPD_STARTF_HOTKEY
: /* return stdinput handle from startupinfo ??? */
2276 GetStartupInfoW(&siw
);
2277 return (DWORD
)siw
.hStdInput
;
2278 case GPD_STARTF_SHOWWINDOW
:
2279 GetStartupInfoW(&siw
);
2280 return siw
.wShowWindow
;
2281 case GPD_STARTF_SIZE
:
2282 GetStartupInfoW(&siw
);
2284 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2286 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2287 return MAKELONG( x
, y
);
2288 case GPD_STARTF_POSITION
:
2289 GetStartupInfoW(&siw
);
2291 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
2293 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
2294 return MAKELONG( x
, y
);
2295 case GPD_STARTF_FLAGS
:
2296 GetStartupInfoW(&siw
);
2301 return GetProcessFlags(0);
2303 return process_dword
;
2305 ERR("Unknown offset %d\n", offset
);
2310 /***********************************************************************
2311 * SetProcessDword (KERNEL.484)
2312 * 'Of course you cannot directly access Windows internal structures'
2314 void WINAPI
SetProcessDword( DWORD dwProcessID
, INT offset
, DWORD value
)
2316 TRACE("(%ld, %d)\n", dwProcessID
, offset
);
2318 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
2320 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
2326 case GPD_APP_COMPAT_FLAGS
:
2327 case GPD_LOAD_DONE_EVENT
:
2328 case GPD_HINSTANCE16
:
2329 case GPD_WINDOWS_VERSION
:
2332 case GPD_STARTF_SHELLDATA
:
2333 case GPD_STARTF_HOTKEY
:
2334 case GPD_STARTF_SHOWWINDOW
:
2335 case GPD_STARTF_SIZE
:
2336 case GPD_STARTF_POSITION
:
2337 case GPD_STARTF_FLAGS
:
2340 ERR("Not allowed to modify offset %d\n", offset
);
2343 process_dword
= value
;
2346 ERR("Unknown offset %d\n", offset
);
2352 /***********************************************************************
2353 * ExitProcess (KERNEL.466)
2355 void WINAPI
ExitProcess16( WORD status
)
2358 ReleaseThunkLock( &count
);
2359 ExitProcess( status
);
2363 /*********************************************************************
2364 * OpenProcess (KERNEL32.@)
2366 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
2369 SERVER_START_REQ( open_process
)
2372 req
->access
= access
;
2373 req
->inherit
= inherit
;
2374 if (!wine_server_call_err( req
)) ret
= reply
->handle
;
2381 /*********************************************************************
2382 * MapProcessHandle (KERNEL.483)
2384 DWORD WINAPI
MapProcessHandle( HANDLE hProcess
)
2387 PROCESS_BASIC_INFORMATION pbi
;
2389 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2391 if (status
== STATUS_SUCCESS
) return pbi
.UniqueProcessId
;
2392 SetLastError( RtlNtStatusToDosError(status
) );
2397 /*********************************************************************
2398 * CloseW32Handle (KERNEL.474)
2399 * CloseHandle (KERNEL32.@)
2401 BOOL WINAPI
CloseHandle( HANDLE handle
)
2405 /* stdio handles need special treatment */
2406 if ((handle
== (HANDLE
)STD_INPUT_HANDLE
) ||
2407 (handle
== (HANDLE
)STD_OUTPUT_HANDLE
) ||
2408 (handle
== (HANDLE
)STD_ERROR_HANDLE
))
2409 handle
= GetStdHandle( (DWORD
)handle
);
2411 if (is_console_handle(handle
))
2412 return CloseConsoleHandle(handle
);
2414 status
= NtClose( handle
);
2415 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2420 /*********************************************************************
2421 * GetHandleInformation (KERNEL32.@)
2423 BOOL WINAPI
GetHandleInformation( HANDLE handle
, LPDWORD flags
)
2426 SERVER_START_REQ( set_handle_info
)
2428 req
->handle
= handle
;
2432 ret
= !wine_server_call_err( req
);
2433 if (ret
&& flags
) *flags
= reply
->old_flags
;
2440 /*********************************************************************
2441 * SetHandleInformation (KERNEL32.@)
2443 BOOL WINAPI
SetHandleInformation( HANDLE handle
, DWORD mask
, DWORD flags
)
2446 SERVER_START_REQ( set_handle_info
)
2448 req
->handle
= handle
;
2452 ret
= !wine_server_call_err( req
);
2459 /*********************************************************************
2460 * DuplicateHandle (KERNEL32.@)
2462 BOOL WINAPI
DuplicateHandle( HANDLE source_process
, HANDLE source
,
2463 HANDLE dest_process
, HANDLE
*dest
,
2464 DWORD access
, BOOL inherit
, DWORD options
)
2468 if (is_console_handle(source
))
2470 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2471 if (source_process
!= dest_process
||
2472 source_process
!= GetCurrentProcess())
2474 SetLastError(ERROR_INVALID_PARAMETER
);
2477 *dest
= DuplicateConsoleHandle( source
, access
, inherit
, options
);
2478 return (*dest
!= INVALID_HANDLE_VALUE
);
2480 status
= NtDuplicateObject( source_process
, source
, dest_process
, dest
,
2481 access
, inherit
? OBJ_INHERIT
: 0, options
);
2482 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2487 /***********************************************************************
2488 * ConvertToGlobalHandle (KERNEL.476)
2489 * ConvertToGlobalHandle (KERNEL32.@)
2491 HANDLE WINAPI
ConvertToGlobalHandle(HANDLE hSrc
)
2493 HANDLE ret
= INVALID_HANDLE_VALUE
;
2494 DuplicateHandle( GetCurrentProcess(), hSrc
, GetCurrentProcess(), &ret
, 0, FALSE
,
2495 DUP_HANDLE_MAKE_GLOBAL
| DUP_HANDLE_SAME_ACCESS
| DUP_HANDLE_CLOSE_SOURCE
);
2500 /***********************************************************************
2501 * SetHandleContext (KERNEL32.@)
2503 BOOL WINAPI
SetHandleContext(HANDLE hnd
,DWORD context
)
2505 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2506 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
,context
);
2507 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2512 /***********************************************************************
2513 * GetHandleContext (KERNEL32.@)
2515 DWORD WINAPI
GetHandleContext(HANDLE hnd
)
2517 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2518 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd
);
2519 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2524 /***********************************************************************
2525 * CreateSocketHandle (KERNEL32.@)
2527 HANDLE WINAPI
CreateSocketHandle(void)
2529 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2530 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2531 SetLastError(ERROR_CALL_NOT_IMPLEMENTED
);
2532 return INVALID_HANDLE_VALUE
;
2536 /***********************************************************************
2537 * SetPriorityClass (KERNEL32.@)
2539 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
2542 SERVER_START_REQ( set_process_info
)
2544 req
->handle
= hprocess
;
2545 req
->priority
= priorityclass
;
2546 req
->mask
= SET_PROCESS_INFO_PRIORITY
;
2547 ret
= !wine_server_call_err( req
);
2554 /***********************************************************************
2555 * GetPriorityClass (KERNEL32.@)
2557 DWORD WINAPI
GetPriorityClass(HANDLE hProcess
)
2560 PROCESS_BASIC_INFORMATION pbi
;
2562 status
= NtQueryInformationProcess(hProcess
, ProcessBasicInformation
, &pbi
,
2564 if (status
== STATUS_SUCCESS
) return pbi
.BasePriority
;
2565 SetLastError( RtlNtStatusToDosError(status
) );
2570 /***********************************************************************
2571 * SetProcessAffinityMask (KERNEL32.@)
2573 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD affmask
)
2576 SERVER_START_REQ( set_process_info
)
2578 req
->handle
= hProcess
;
2579 req
->affinity
= affmask
;
2580 req
->mask
= SET_PROCESS_INFO_AFFINITY
;
2581 ret
= !wine_server_call_err( req
);
2588 /**********************************************************************
2589 * GetProcessAffinityMask (KERNEL32.@)
2591 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
2592 LPDWORD lpProcessAffinityMask
,
2593 LPDWORD lpSystemAffinityMask
)
2596 SERVER_START_REQ( get_process_info
)
2598 req
->handle
= hProcess
;
2599 if (!wine_server_call_err( req
))
2601 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= reply
->process_affinity
;
2602 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= reply
->system_affinity
;
2611 /***********************************************************************
2612 * GetProcessVersion (KERNEL32.@)
2614 DWORD WINAPI
GetProcessVersion( DWORD processid
)
2616 IMAGE_NT_HEADERS
*nt
;
2618 if (processid
&& processid
!= GetCurrentProcessId())
2620 FIXME("should use ReadProcessMemory\n");
2623 if ((nt
= RtlImageNtHeader( NtCurrentTeb()->Peb
->ImageBaseAddress
)))
2624 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
2625 nt
->OptionalHeader
.MinorSubsystemVersion
);
2630 /***********************************************************************
2631 * SetProcessWorkingSetSize [KERNEL32.@]
2632 * Sets the min/max working set sizes for a specified process.
2635 * hProcess [I] Handle to the process of interest
2636 * minset [I] Specifies minimum working set size
2637 * maxset [I] Specifies maximum working set size
2641 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
, SIZE_T minset
,
2644 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
2645 if(( minset
== (SIZE_T
)-1) && (maxset
== (SIZE_T
)-1)) {
2646 /* Trim the working set to zero */
2647 /* Swap the process out of physical RAM */
2652 /***********************************************************************
2653 * GetProcessWorkingSetSize (KERNEL32.@)
2655 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
, PSIZE_T minset
,
2658 FIXME("(%p,%p,%p): stub\n",hProcess
,minset
,maxset
);
2659 /* 32 MB working set size */
2660 if (minset
) *minset
= 32*1024*1024;
2661 if (maxset
) *maxset
= 32*1024*1024;
2666 /***********************************************************************
2667 * SetProcessShutdownParameters (KERNEL32.@)
2669 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
2671 FIXME("(%08lx, %08lx): partial stub.\n", level
, flags
);
2672 shutdown_flags
= flags
;
2673 shutdown_priority
= level
;
2678 /***********************************************************************
2679 * GetProcessShutdownParameters (KERNEL32.@)
2682 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
2684 *lpdwLevel
= shutdown_priority
;
2685 *lpdwFlags
= shutdown_flags
;
2690 /***********************************************************************
2691 * GetProcessPriorityBoost (KERNEL32.@)
2693 BOOL WINAPI
GetProcessPriorityBoost(HANDLE hprocess
,PBOOL pDisablePriorityBoost
)
2695 FIXME("(%p,%p): semi-stub\n", hprocess
, pDisablePriorityBoost
);
2697 /* Report that no boost is present.. */
2698 *pDisablePriorityBoost
= FALSE
;
2703 /***********************************************************************
2704 * SetProcessPriorityBoost (KERNEL32.@)
2706 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
2708 FIXME("(%p,%d): stub\n",hprocess
,disableboost
);
2709 /* Say we can do it. I doubt the program will notice that we don't. */
2714 /***********************************************************************
2715 * ReadProcessMemory (KERNEL32.@)
2717 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, SIZE_T size
,
2718 SIZE_T
*bytes_read
)
2720 NTSTATUS status
= NtReadVirtualMemory( process
, addr
, buffer
, size
, bytes_read
);
2721 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2726 /***********************************************************************
2727 * WriteProcessMemory (KERNEL32.@)
2729 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, SIZE_T size
,
2730 SIZE_T
*bytes_written
)
2732 NTSTATUS status
= NtWriteVirtualMemory( process
, addr
, buffer
, size
, bytes_written
);
2733 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2738 /****************************************************************************
2739 * FlushInstructionCache (KERNEL32.@)
2741 BOOL WINAPI
FlushInstructionCache(HANDLE hProcess
, LPCVOID lpBaseAddress
, SIZE_T dwSize
)
2743 if (GetVersion() & 0x80000000) return TRUE
; /* not NT, always TRUE */
2744 FIXME("(%p,%p,0x%08lx): stub\n",hProcess
, lpBaseAddress
, dwSize
);
2749 /******************************************************************
2750 * GetProcessIoCounters (KERNEL32.@)
2752 BOOL WINAPI
GetProcessIoCounters(HANDLE hProcess
, PIO_COUNTERS ioc
)
2756 status
= NtQueryInformationProcess(hProcess
, ProcessIoCounters
,
2757 ioc
, sizeof(*ioc
), NULL
);
2758 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
2762 /***********************************************************************
2763 * ProcessIdToSessionId (KERNEL32.@)
2764 * This function is available on Terminal Server 4SP4 and Windows 2000
2766 BOOL WINAPI
ProcessIdToSessionId( DWORD procid
, DWORD
*sessionid_ptr
)
2768 /* According to MSDN, if the calling process is not in a terminal
2769 * services environment, then the sessionid returned is zero.
2776 /***********************************************************************
2777 * RegisterServiceProcess (KERNEL.491)
2778 * RegisterServiceProcess (KERNEL32.@)
2780 * A service process calls this function to ensure that it continues to run
2781 * even after a user logged off.
2783 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
2785 /* I don't think that Wine needs to do anything in that function */
2786 return 1; /* success */
2790 /***********************************************************************
2791 * GetSystemMSecCount (SYSTEM.6)
2792 * GetTickCount (KERNEL32.@)
2794 * Returns the number of milliseconds, modulo 2^32, since the start
2795 * of the wineserver.
2797 DWORD WINAPI
GetTickCount(void)
2800 gettimeofday( &t
, NULL
);
2801 return ((t
.tv_sec
* 1000) + (t
.tv_usec
/ 1000)) - server_startticks
;
2805 /***********************************************************************
2806 * GetCurrentProcess (KERNEL32.@)
2808 #undef GetCurrentProcess
2809 HANDLE WINAPI
GetCurrentProcess(void)
2811 return (HANDLE
)0xffffffff;