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 #include "wine/winbase16.h"
32 #include "wine/winuser16.h"
40 #include "kernel_private.h"
41 #include "wine/server.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(process);
46 WINE_DECLARE_DEBUG_CHANNEL(server);
47 WINE_DECLARE_DEBUG_CHANNEL(relay);
49 /* Win32 process database */
52 LONG header[2]; /* 00 Kernel object header */
53 HMODULE module; /* 08 Main exe module (NT) */
54 PPEB_LDR_DATA LdrData; /* 0c Pointer to loader information */
55 RTL_USER_PROCESS_PARAMETERS *ProcessParameters; /* 10 Process parameters */
56 DWORD unknown2; /* 14 Unknown */
57 HANDLE heap; /* 18 Default process heap */
58 HANDLE mem_context; /* 1c Process memory context */
59 DWORD flags; /* 20 Flags */
60 void *pdb16; /* 24 DOS PSP */
61 WORD PSP_sel; /* 28 Selector to DOS PSP */
62 WORD imte; /* 2a IMTE for the process module */
63 WORD threads; /* 2c Number of threads */
64 WORD running_threads; /* 2e Number of running threads */
65 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
66 WORD ring0_threads; /* 32 Number of ring 0 threads */
67 HANDLE system_heap; /* 34 System heap to allocate handles */
68 HTASK task; /* 38 Win16 task */
69 void *mem_map_files; /* 3c Pointer to mem-mapped files */
70 struct _ENVDB *env_db; /* 40 Environment database */
71 void *handle_table; /* 44 Handle table */
72 struct _PDB *parent; /* 48 Parent process */
73 void *modref_list; /* 4c MODREF list */
74 void *thread_list; /* 50 List of threads */
75 void *debuggee_CB; /* 54 Debuggee context block */
76 void *local_heap_free; /* 58 Head of local heap free list */
77 DWORD unknown4; /* 5c Unknown */
78 CRITICAL_SECTION crit_section; /* 60 Critical section */
79 DWORD unknown5[3]; /* 78 Unknown */
80 void *console; /* 84 Console */
81 DWORD tls_bits[2]; /* 88 TLS in-use bits */
82 DWORD process_dword; /* 90 Unknown */
83 struct _PDB *group; /* 94 Process group */
84 void *exe_modref; /* 98 MODREF for the process EXE */
85 void *top_filter; /* 9c Top exception filter */
86 DWORD priority; /* a0 Priority level */
87 HANDLE heap_list; /* a4 Head of process heap list */
88 void *heap_handles; /* a8 Head of heap handles list */
89 DWORD unknown6; /* ac Unknown */
90 void *console_provider; /* b0 Console provider (??) */
91 WORD env_selector; /* b4 Selector to process environment */
92 WORD error_mode; /* b6 Error mode */
93 HANDLE load_done_evt; /* b8 Event for process loading done */
94 void *UTState; /* bc Head of Univeral Thunk list */
95 DWORD unknown8; /* c0 Unknown (NT) */
96 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
101 static PEB_LDR_DATA process_ldr;
103 static HANDLE main_exe_file;
104 static DWORD shutdown_flags = 0;
105 static DWORD shutdown_priority = 0x280;
106 static DWORD process_dword;
107 static BOOL oem_file_apis;
109 extern unsigned int server_startticks;
110 int main_create_flags = 0;
113 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
114 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
115 #define PDB32_DOS_PROC 0x0010 /* Dos process */
116 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
117 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
118 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
120 static const WCHAR comW[] = {'c','o','m',0};
121 static const WCHAR batW[] = {'b','a','t',0};
122 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
124 /* dlls/ntdll/env.c */
125 extern BOOL build_command_line( char **argv );
127 extern void SHELL_LoadRegistry(void);
128 extern void VERSION_Init( const WCHAR *appname );
129 extern void MODULE_InitLoadPath(void);
131 /***********************************************************************
134 inline static int contains_path( LPCWSTR name )
136 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
140 /***************************************************************************
143 * Get the path of a builtin module when the native file does not exist.
145 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
148 WCHAR sysdir[MAX_PATH];
149 UINT len = GetSystemDirectoryW( sysdir, MAX_PATH );
151 if (contains_path( libname ))
153 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
154 filename, &file_part ) > size * sizeof(WCHAR))
155 return FALSE; /* too long */
157 if (strncmpiW( filename, sysdir, len ) || filename[len] != '\\')
159 while (filename[len] == '\\') len++;
160 if (filename != file_part) return FALSE;
164 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
165 memcpy( filename, sysdir, len * sizeof(WCHAR) );
166 file_part = filename + len;
167 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
168 strcpyW( file_part, libname );
170 if (ext && !strchrW( file_part, '.' ))
172 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
173 return FALSE; /* too long */
174 strcatW( file_part, ext );
180 /***********************************************************************
181 * open_builtin_exe_file
183 * Open an exe file for a builtin exe.
185 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
186 int test_only, int *file_exists )
188 char exename[MAX_PATH];
192 if ((p = strrchrW( name, '/' ))) name = p + 1;
193 if ((p = strrchrW( name, '\\' ))) name = p + 1;
195 /* we don't want to depend on the current codepage here */
196 len = strlenW( name ) + 1;
197 if (len >= sizeof(exename)) return NULL;
198 for (i = 0; i < len; i++)
200 if (name[i] > 127) return NULL;
201 exename[i] = (char)name[i];
202 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
204 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
208 /***********************************************************************
211 * Open a specific exe file, taking load order into account.
212 * Returns the file handle or 0 for a builtin exe.
214 static HANDLE open_exe_file( const WCHAR *name )
216 enum loadorder_type loadorder[LOADORDER_NTYPES];
217 WCHAR buffer[MAX_PATH];
221 TRACE("looking for %s\n", debugstr_w(name) );
223 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ,
224 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
226 /* file doesn't exist, check for builtin */
227 if (!contains_path( name )) goto error;
228 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
232 MODULE_GetLoadOrderW( loadorder, NULL, name, TRUE );
234 for(i = 0; i < LOADORDER_NTYPES; i++)
236 if (loadorder[i] == LOADORDER_INVALID) break;
240 TRACE( "Trying native exe %s\n", debugstr_w(name) );
241 if (handle != INVALID_HANDLE_VALUE) return handle;
244 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
245 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
248 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
255 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
258 SetLastError( ERROR_FILE_NOT_FOUND );
259 return INVALID_HANDLE_VALUE;
263 /***********************************************************************
266 * Open an exe file, and return the full name and file handle.
267 * Returns FALSE if file could not be found.
268 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
269 * If file is a builtin exe, returns TRUE and sets handle to 0.
271 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
273 static const WCHAR exeW[] = {'.','e','x','e',0};
275 enum loadorder_type loadorder[LOADORDER_NTYPES];
278 TRACE("looking for %s\n", debugstr_w(name) );
280 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
281 !get_builtin_path( name, exeW, buffer, buflen ))
283 /* no builtin found, try native without extension in case it is a Unix app */
285 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
287 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
288 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
289 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
295 MODULE_GetLoadOrderW( loadorder, NULL, buffer, TRUE );
297 for(i = 0; i < LOADORDER_NTYPES; i++)
299 if (loadorder[i] == LOADORDER_INVALID) break;
303 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
304 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
305 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
307 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
310 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
311 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
322 SetLastError( ERROR_FILE_NOT_FOUND );
327 /**********************************************************************
330 * Load a PE format EXE file.
332 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
334 IMAGE_NT_HEADERS *nt;
337 OBJECT_ATTRIBUTES attr;
342 attr.Length = sizeof(attr);
343 attr.RootDirectory = 0;
344 attr.ObjectName = NULL;
346 attr.SecurityDescriptor = NULL;
347 attr.SecurityQualityOfService = NULL;
350 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
351 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
355 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
356 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
362 nt = RtlImageNtHeader( module );
363 if (nt->OptionalHeader.AddressOfEntryPoint)
365 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
366 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
367 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
368 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
371 drive_type = GetDriveTypeW( name );
372 /* don't keep the file handle open on removable media */
373 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM)
375 CloseHandle( main_exe_file );
382 /***********************************************************************
385 * Build the Win32 environment from the Unix environment
387 static BOOL build_initial_environment(void)
389 extern char **environ;
395 /* Compute the total size of the Unix environment */
396 for (e = environ; *e; e++)
398 if (!memcmp(*e, "PATH=", 5)) continue;
399 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
401 size *= sizeof(WCHAR);
403 /* Now allocate the environment */
404 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
405 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
408 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
409 endptr = p + size / sizeof(WCHAR);
411 /* And fill it with the Unix environment */
412 for (e = environ; *e; e++)
415 /* skip Unix PATH and store WINEPATH as PATH */
416 if (!memcmp(str, "PATH=", 5)) continue;
417 if (!memcmp(str, "WINEPATH=", 9 )) str += 4;
418 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
426 /* make sure the unicode string doesn't point beyond the end pointer */
427 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
429 if ((char *)str->Buffer >= end_ptr)
431 str->Length = str->MaximumLength = 0;
435 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
437 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
439 if (str->Length >= str->MaximumLength)
441 if (str->MaximumLength >= sizeof(WCHAR))
442 str->Length = str->MaximumLength - sizeof(WCHAR);
444 str->Length = str->MaximumLength = 0;
449 /***********************************************************************
450 * init_user_process_params
452 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
454 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
459 RTL_USER_PROCESS_PARAMETERS *params;
462 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
463 MEM_COMMIT, PAGE_READWRITE )) != STATUS_SUCCESS)
466 SERVER_START_REQ( get_startup_info )
468 wine_server_set_reply( req, ptr, info_size );
469 wine_server_call( req );
470 info_size = wine_server_reply_size( reply );
475 params->Size = info_size;
476 params->AllocationSize = size;
478 /* make sure the strings are valid */
479 fix_unicode_string( ¶ms->CurrentDirectoryName, (char *)info_size );
480 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
481 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
482 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
483 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
484 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
485 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
486 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
488 return RtlNormalizeProcessParams( params );
492 /***********************************************************************
495 * Main process initialisation code
497 static BOOL process_init( char *argv[] )
499 static RTL_USER_PROCESS_PARAMETERS default_params; /* default parameters if no parent */
502 size_t info_size = 0;
503 RTL_USER_PROCESS_PARAMETERS *params = &default_params;
504 HANDLE hstdin, hstdout, hstderr;
508 setlocale(LC_CTYPE,"");
510 /* Fill the initial process structure */
511 current_process.threads = 1;
512 current_process.running_threads = 1;
513 current_process.ring0_threads = 1;
514 current_process.group = ¤t_process;
515 current_process.priority = 8; /* Normal */
516 current_process.ProcessParameters = &default_params;
517 current_process.LdrData = &process_ldr;
518 InitializeListHead(&process_ldr.InLoadOrderModuleList);
519 InitializeListHead(&process_ldr.InMemoryOrderModuleList);
520 InitializeListHead(&process_ldr.InInitializationOrderModuleList);
522 /* Setup the server connection */
523 wine_server_init_thread();
525 /* Retrieve startup info from the server */
526 SERVER_START_REQ( init_process )
528 req->ldt_copy = &wine_ldt_copy;
529 if ((ret = !wine_server_call_err( req )))
531 main_exe_file = reply->exe_file;
532 main_create_flags = reply->create_flags;
533 info_size = reply->info_size;
534 server_startticks = reply->server_start;
535 hstdin = reply->hstdin;
536 hstdout = reply->hstdout;
537 hstderr = reply->hstderr;
541 if (!ret) return FALSE;
543 /* Create the process heap */
544 current_process.heap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL );
548 /* This is wine specific: we have no parent (we're started from unix)
549 * so, create a simple console with bare handles to unix stdio
550 * input & output streams (aka simple console)
552 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, ¶ms->hStdInput );
553 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdOutput );
554 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdError );
556 /* <hack: to be changed later on> */
557 params->CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
558 params->CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
559 params->CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectoryName.MaximumLength);
560 params->CurrentDirectoryName.Buffer[0] = 'C';
561 params->CurrentDirectoryName.Buffer[1] = ':';
562 params->CurrentDirectoryName.Buffer[2] = '\\';
563 params->CurrentDirectoryName.Buffer[3] = '\0';
564 /* </hack: to be changed later on> */
568 if (!(params = init_user_process_params( info_size ))) return FALSE;
569 current_process.ProcessParameters = params;
571 /* convert value from server:
572 * + 0 => INVALID_HANDLE_VALUE
573 * + console handle need to be mapped
576 hstdin = INVALID_HANDLE_VALUE;
577 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
578 hstdin = console_handle_map(hstdin);
581 hstdout = INVALID_HANDLE_VALUE;
582 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
583 hstdout = console_handle_map(hstdout);
586 hstderr = INVALID_HANDLE_VALUE;
587 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
588 hstderr = console_handle_map(hstderr);
590 params->hStdInput = hstdin;
591 params->hStdOutput = hstdout;
592 params->hStdError = hstderr;
595 /* Copy the parent environment */
596 if (!build_initial_environment()) return FALSE;
598 /* Parse command line arguments */
599 OPTIONS_ParseOptions( !info_size ? argv : NULL );
601 /* initialise DOS drives */
602 if (!DRIVE_Init()) return FALSE;
604 /* initialise DOS directories */
605 if (!DIR_Init()) return FALSE;
607 /* registry initialisation */
608 SHELL_LoadRegistry();
610 /* global boot finished, the rest is process-local */
611 SERVER_START_REQ( boot_done )
613 req->debug_level = TRACE_ON(server);
614 wine_server_call( req );
622 /***********************************************************************
625 * Startup routine of a new process. Runs on the new process stack.
627 static void start_process( void *arg )
631 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
633 __EXCEPT(UnhandledExceptionFilter)
635 TerminateThread( GetCurrentThread(), GetExceptionCode() );
641 /***********************************************************************
642 * __wine_process_init
644 * Wine initialisation: load and start the main exe file.
646 void __wine_process_init( int argc, char *argv[] )
648 WCHAR *main_exe_name, *p;
650 DWORD stack_size = 0;
653 /* Initialize everything */
654 if (!process_init( argv )) exit(1);
656 argv++; /* remove argv[0] (wine itself) */
658 if (!(main_exe_name = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer))
660 WCHAR buffer[MAX_PATH];
661 WCHAR exe_nameW[MAX_PATH];
663 if (!argv[0]) OPTIONS_Usage();
665 /* FIXME: locale info not loaded yet */
666 MultiByteToWideChar( CP_UNIXCP, 0, argv[0], -1, exe_nameW, MAX_PATH );
667 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
669 MESSAGE( "wine: cannot find '%s'\n", argv[0] );
672 if (main_exe_file == INVALID_HANDLE_VALUE)
674 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
677 RtlCreateUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->ImagePathName, buffer );
678 main_exe_name = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
681 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
682 debugstr_w(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
684 MODULE_InitLoadPath();
685 VERSION_Init( main_exe_name );
687 if (!main_exe_file) /* no file handle -> Winelib app */
689 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
690 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
692 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
693 debugstr_w(main_exe_name), error );
697 switch( MODULE_GetBinaryType( main_exe_file ))
700 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
701 if ((current_process.module = load_pe_exe( main_exe_name, main_exe_file ))) goto found;
702 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
705 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
708 /* check for .com extension */
709 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
711 MESSAGE( "wine: cannot determine executable type for %s\n",
712 debugstr_w(main_exe_name) );
718 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
719 CloseHandle( main_exe_file );
722 argv[0] = "winevdm.exe";
723 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
725 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
726 debugstr_w(main_exe_name), error );
729 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
731 case BINARY_UNIX_EXE:
732 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
734 case BINARY_UNIX_LIB:
736 DOS_FULL_NAME full_name;
738 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
739 CloseHandle( main_exe_file );
741 if (DOSFS_GetFullName( main_exe_name, TRUE, &full_name ) &&
742 wine_dlopen( full_name.long_name, RTLD_NOW, error, sizeof(error) ))
744 static const WCHAR soW[] = {'s','o',0};
745 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
748 /* update the unicode string */
749 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->ImagePathName,
754 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
760 /* build command line */
761 if (!build_command_line( argv )) goto error;
763 /* create 32-bit module for main exe */
764 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module, CreateFileW )))
766 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
768 /* allocate main thread stack */
769 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
771 /* switch to the new stack */
772 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
775 ExitProcess( GetLastError() );
779 /***********************************************************************
782 * Build an argv array from a command-line.
783 * 'reserved' is the number of args to reserve before the first one.
785 static char **build_argv( const WCHAR *cmdlineW, int reserved )
789 char *arg,*s,*d,*cmdline;
790 int in_quotes,bcount,len;
792 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
793 if (!(cmdline = malloc(len))) return NULL;
794 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
801 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
804 /* skip the remaining spaces */
805 while (*s==' ' || *s=='\t') {
812 } else if (*s=='\\') {
813 /* '\', count them */
815 } else if ((*s=='"') && ((bcount & 1)==0)) {
817 in_quotes=!in_quotes;
820 /* a regular character */
825 argv=malloc(argc*sizeof(*argv));
834 if ((*s==' ' || *s=='\t') && !in_quotes) {
835 /* Close the argument and copy it */
839 /* skip the remaining spaces */
842 } while (*s==' ' || *s=='\t');
844 /* Start with a new argument */
847 } else if (*s=='\\') {
851 } else if (*s=='"') {
853 if ((bcount & 1)==0) {
854 /* Preceeded by an even number of '\', this is half that
855 * number of '\', plus a '"' which we discard.
859 in_quotes=!in_quotes;
861 /* Preceeded by an odd number of '\', this is half that
862 * number of '\' followed by a '"'
870 /* a regular character */
885 /***********************************************************************
888 * Build the environment of a new child process.
890 static char **build_envp( const WCHAR *envW, const WCHAR *extra_envW )
894 char *env, *extra_env = NULL;
895 int count = 0, length;
899 for (p = extra_envW; *p; count++) p += strlenW(p) + 1;
901 length = WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
902 NULL, 0, NULL, NULL );
903 if ((extra_env = malloc( length )))
904 WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
905 extra_env, length, NULL, NULL );
907 for (p = envW; *p; count++) p += strlenW(p) + 1;
909 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, NULL, 0, NULL, NULL );
910 if (!(env = malloc( length ))) return NULL;
911 WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, env, length, NULL, NULL );
915 if ((envp = malloc( count * sizeof(*envp) )))
917 extern char **environ;
918 char **envptr = envp;
919 char **unixptr = environ;
922 /* first the extra strings */
923 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = p;
924 /* then put PATH, HOME and WINEPREFIX from the unix env */
925 for (unixptr = environ; unixptr && *unixptr; unixptr++)
926 if (!memcmp( *unixptr, "PATH=", 5 ) ||
927 !memcmp( *unixptr, "HOME=", 5 ) ||
928 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
929 /* now put the Windows environment strings */
930 for (p = env; *p; p += strlen(p) + 1)
932 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
934 char *winepath = malloc( strlen(p) + 5 );
935 strcpy( winepath, "WINE" );
936 strcpy( winepath + 4, p );
937 *envptr++ = winepath;
939 else if (memcmp( p, "HOME=", 5 ) &&
940 memcmp( p, "WINEPATH=", 9 ) &&
941 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
949 /***********************************************************************
952 * Locate the Wine binary to exec for a new Win32 process.
954 static void exec_wine_binary( char **argv, char **envp )
956 const char *path, *pos, *ptr;
958 /* first, try for a WINELOADER environment variable */
959 argv[0] = getenv("WINELOADER");
961 execve( argv[0], argv, envp );
963 /* next, try bin directory */
964 argv[0] = BINDIR "/wine";
965 execve( argv[0], argv, envp );
967 /* now try the path of argv0 of the current binary */
968 if ((path = wine_get_argv0_path()))
970 if (!(argv[0] = malloc( strlen(path) + sizeof("wine") ))) return;
971 strcpy( argv[0], path );
972 strcat( argv[0], "wine" );
973 execve( argv[0], argv, envp );
977 /* now search in the Unix path */
978 if ((path = getenv( "PATH" )))
980 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
984 while (*pos == ':') pos++;
986 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
987 memcpy( argv[0], pos, ptr - pos );
988 strcpy( argv[0] + (ptr - pos), "/wine" );
989 execve( argv[0], argv, envp );
997 /***********************************************************************
1000 * Fork and exec a new Unix binary, checking for errors.
1002 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1003 const WCHAR *env, const char *newdir )
1008 if (!env) env = GetEnvironmentStringsW();
1015 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1016 if (!(pid = fork())) /* child */
1018 char **argv = build_argv( cmdline, 0 );
1019 char **envp = build_envp( env, NULL );
1022 /* Reset signals that we previously set to SIG_IGN */
1023 signal( SIGPIPE, SIG_DFL );
1024 signal( SIGCHLD, SIG_DFL );
1026 if (newdir) chdir(newdir);
1028 if (argv && envp) execve( filename, argv, envp );
1030 write( fd[1], &err, sizeof(err) );
1034 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1039 if (pid == -1) FILE_SetDosError();
1045 /***********************************************************************
1046 * create_user_params
1048 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1049 const STARTUPINFOW *startup )
1051 RTL_USER_PROCESS_PARAMETERS *params;
1052 UNICODE_STRING image_str, cmdline_str, desktop, title;
1054 WCHAR buffer[MAX_PATH];
1056 if (GetLongPathNameW( filename, buffer, MAX_PATH ))
1057 RtlInitUnicodeString( &image_str, buffer );
1059 RtlInitUnicodeString( &image_str, filename );
1061 RtlInitUnicodeString( &cmdline_str, cmdline );
1062 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1063 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1065 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL, NULL, &cmdline_str, NULL,
1066 startup->lpTitle ? &title : NULL,
1067 startup->lpDesktop ? &desktop : NULL,
1069 if (status != STATUS_SUCCESS)
1071 SetLastError( RtlNtStatusToDosError(status) );
1075 params->Environment = NULL; /* we pass it through the Unix environment */
1076 params->hStdInput = startup->hStdInput;
1077 params->hStdOutput = startup->hStdOutput;
1078 params->hStdError = startup->hStdError;
1079 params->dwX = startup->dwX;
1080 params->dwY = startup->dwY;
1081 params->dwXSize = startup->dwXSize;
1082 params->dwYSize = startup->dwYSize;
1083 params->dwXCountChars = startup->dwXCountChars;
1084 params->dwYCountChars = startup->dwYCountChars;
1085 params->dwFillAttribute = startup->dwFillAttribute;
1086 params->dwFlags = startup->dwFlags;
1087 params->wShowWindow = startup->wShowWindow;
1092 /***********************************************************************
1095 * Create a new process. If hFile is a valid handle we have an exe
1096 * file, otherwise it is a Winelib app.
1098 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1099 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1100 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1101 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1103 BOOL ret, success = FALSE;
1104 HANDLE process_info;
1105 RTL_USER_PROCESS_PARAMETERS *params;
1106 WCHAR *extra_env = NULL;
1115 env = GetEnvironmentStringsW();
1116 extra_env = DRIVE_BuildEnv();
1119 if (!(params = create_user_params( filename, cmd_line, startup )))
1121 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1125 /* create the synchronization pipes */
1127 if (pipe( startfd ) == -1)
1130 RtlDestroyProcessParameters( params );
1131 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1134 if (pipe( execfd ) == -1)
1137 close( startfd[0] );
1138 close( startfd[1] );
1139 RtlDestroyProcessParameters( params );
1140 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1143 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1145 /* create the child process */
1147 if (!(pid = fork())) /* child */
1149 char **argv = build_argv( cmd_line, 1 );
1150 char **envp = build_envp( env, extra_env );
1152 close( startfd[1] );
1155 /* wait for parent to tell us to start */
1156 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1158 close( startfd[0] );
1159 /* Reset signals that we previously set to SIG_IGN */
1160 signal( SIGPIPE, SIG_DFL );
1161 signal( SIGCHLD, SIG_DFL );
1163 if (unixdir) chdir(unixdir);
1165 if (argv && envp) exec_wine_binary( argv, envp );
1168 write( execfd[1], &err, sizeof(err) );
1172 /* this is the parent */
1174 close( startfd[0] );
1176 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1179 close( startfd[1] );
1182 RtlDestroyProcessParameters( params );
1186 /* create the process on the server side */
1188 SERVER_START_REQ( new_process )
1190 req->inherit_all = inherit;
1191 req->create_flags = flags;
1192 req->unix_pid = pid;
1193 req->exe_file = hFile;
1194 if (startup->dwFlags & STARTF_USESTDHANDLES)
1196 req->hstdin = startup->hStdInput;
1197 req->hstdout = startup->hStdOutput;
1198 req->hstderr = startup->hStdError;
1202 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1203 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1204 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1207 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1209 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1210 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1211 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1212 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1216 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1217 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1218 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1221 wine_server_add_data( req, params, params->Size );
1222 ret = !wine_server_call_err( req );
1223 process_info = reply->info;
1227 RtlDestroyProcessParameters( params );
1230 close( startfd[1] );
1235 /* tell child to start and wait for it to exec */
1237 write( startfd[1], &dummy, 1 );
1238 close( startfd[1] );
1240 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1245 CloseHandle( process_info );
1249 /* wait for the new process info to be ready */
1251 WaitForSingleObject( process_info, INFINITE );
1252 SERVER_START_REQ( get_new_process_info )
1254 req->info = process_info;
1255 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1256 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1257 if ((ret = !wine_server_call_err( req )))
1259 info->dwProcessId = (DWORD)reply->pid;
1260 info->dwThreadId = (DWORD)reply->tid;
1261 info->hProcess = reply->phandle;
1262 info->hThread = reply->thandle;
1263 success = reply->success;
1268 if (ret && !success) /* new process failed to start */
1271 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1272 CloseHandle( info->hThread );
1273 CloseHandle( info->hProcess );
1276 CloseHandle( process_info );
1281 /***********************************************************************
1282 * create_vdm_process
1284 * Create a new VDM process for a 16-bit or DOS application.
1286 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1287 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1288 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1289 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1291 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1294 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1295 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1299 SetLastError( ERROR_OUTOFMEMORY );
1302 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1303 ret = create_process( 0, winevdmW, new_cmd_line, env, psa, tsa, inherit,
1304 flags, startup, info, unixdir );
1305 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1310 /***********************************************************************
1311 * create_cmd_process
1313 * Create a new cmd shell process for a .BAT file.
1315 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env,
1316 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1317 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1318 LPPROCESS_INFORMATION info, LPCWSTR cur_dir )
1321 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1322 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1323 WCHAR comspec[MAX_PATH];
1327 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1329 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1330 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1333 strcpyW( newcmdline, comspec );
1334 strcatW( newcmdline, slashcW );
1335 strcatW( newcmdline, cmd_line );
1336 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1337 flags, env, cur_dir, startup, info );
1338 HeapFree( GetProcessHeap(), 0, newcmdline );
1343 /*************************************************************************
1346 * Helper for CreateProcess: retrieve the file name to load from the
1347 * app name and command line. Store the file name in buffer, and
1348 * return a possibly modified command line.
1349 * Also returns a handle to the opened file if it's a Windows binary.
1351 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1352 int buflen, HANDLE *handle )
1354 static const WCHAR quotesW[] = {'"','%','s','"',0};
1356 WCHAR *name, *pos, *ret = NULL;
1359 /* if we have an app name, everything is easy */
1363 /* use the unmodified app name as file name */
1364 lstrcpynW( buffer, appname, buflen );
1365 *handle = open_exe_file( buffer );
1366 if (!(ret = cmdline) || !cmdline[0])
1368 /* no command-line, create one */
1369 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) + sizeof(WCHAR) )))
1370 sprintfW( ret, quotesW, appname );
1377 SetLastError( ERROR_INVALID_PARAMETER );
1381 /* first check for a quoted file name */
1383 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1385 int len = p - cmdline - 1;
1386 /* extract the quoted portion as file name */
1387 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1388 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1391 if (find_exe_file( name, buffer, buflen, handle ))
1392 ret = cmdline; /* no change necessary */
1396 /* now try the command-line word by word */
1398 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1405 do *pos++ = *p++; while (*p && *p != ' ');
1407 if (find_exe_file( name, buffer, buflen, handle ))
1414 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1416 /* now build a new command-line with quotes */
1418 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1420 sprintfW( ret, quotesW, name );
1424 HeapFree( GetProcessHeap(), 0, name );
1429 /**********************************************************************
1430 * CreateProcessA (KERNEL32.@)
1432 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1433 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1434 DWORD flags, LPVOID env, LPCSTR cur_dir,
1435 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1438 UNICODE_STRING app_nameW, cmd_lineW, cur_dirW, desktopW, titleW;
1441 if (app_name) RtlCreateUnicodeStringFromAsciiz( &app_nameW, app_name );
1442 else app_nameW.Buffer = NULL;
1443 if (cmd_line) RtlCreateUnicodeStringFromAsciiz( &cmd_lineW, cmd_line );
1444 else cmd_lineW.Buffer = NULL;
1445 if (cur_dir) RtlCreateUnicodeStringFromAsciiz( &cur_dirW, cur_dir );
1446 else cur_dirW.Buffer = NULL;
1447 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1448 else desktopW.Buffer = NULL;
1449 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1450 else titleW.Buffer = NULL;
1452 memcpy( &infoW, startup_info, sizeof(infoW) );
1453 infoW.lpDesktop = desktopW.Buffer;
1454 infoW.lpTitle = titleW.Buffer;
1456 if (startup_info->lpReserved)
1457 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1458 debugstr_a(startup_info->lpReserved));
1460 ret = CreateProcessW( app_nameW.Buffer, cmd_lineW.Buffer, process_attr, thread_attr,
1461 inherit, flags, env, cur_dirW.Buffer, &infoW, info );
1463 RtlFreeUnicodeString( &app_nameW );
1464 RtlFreeUnicodeString( &cmd_lineW );
1465 RtlFreeUnicodeString( &cur_dirW );
1466 RtlFreeUnicodeString( &desktopW );
1467 RtlFreeUnicodeString( &titleW );
1472 /**********************************************************************
1473 * CreateProcessW (KERNEL32.@)
1475 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1476 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1477 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1478 LPPROCESS_INFORMATION info )
1482 const char *unixdir = NULL;
1483 DOS_FULL_NAME full_dir;
1484 WCHAR name[MAX_PATH];
1485 WCHAR *tidy_cmdline, *p, *envW = env;
1487 /* Process the AppName and/or CmdLine to get module name and path */
1489 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1491 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1493 if (hFile == INVALID_HANDLE_VALUE) goto done;
1495 /* Warn if unsupported features are used */
1497 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1498 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1499 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1500 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1501 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1505 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir )) unixdir = full_dir.long_name;
1509 WCHAR buf[MAX_PATH];
1510 if (GetCurrentDirectoryW(MAX_PATH, buf))
1512 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1516 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1521 while (*p) p += strlen(p) + 1;
1522 p++; /* final null */
1523 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1524 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1525 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1526 flags |= CREATE_UNICODE_ENVIRONMENT;
1529 info->hThread = info->hProcess = 0;
1530 info->dwProcessId = info->dwThreadId = 0;
1532 /* Determine executable type */
1534 if (!hFile) /* builtin exe */
1536 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1537 retv = create_process( 0, name, tidy_cmdline, envW, process_attr, thread_attr,
1538 inherit, flags, startup_info, info, unixdir );
1542 switch( MODULE_GetBinaryType( hFile ))
1545 TRACE( "starting %s as Win32 binary\n", debugstr_w(name) );
1546 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1547 inherit, flags, startup_info, info, unixdir );
1551 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1552 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1553 inherit, flags, startup_info, info, unixdir );
1556 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1557 SetLastError( ERROR_BAD_EXE_FORMAT );
1560 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1561 SetLastError( ERROR_BAD_EXE_FORMAT );
1563 case BINARY_UNIX_LIB:
1564 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1565 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1566 inherit, flags, startup_info, info, unixdir );
1568 case BINARY_UNKNOWN:
1569 /* check for .com or .bat extension */
1570 if ((p = strrchrW( name, '.' )))
1572 if (!strcmpiW( p, comW ))
1574 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1575 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1576 inherit, flags, startup_info, info, unixdir );
1579 if (!strcmpiW( p, batW ))
1581 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1582 retv = create_cmd_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1583 inherit, flags, startup_info, info, cur_dir );
1588 case BINARY_UNIX_EXE:
1590 /* unknown file, try as unix executable */
1591 DOS_FULL_NAME full_name;
1593 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1595 if (DOSFS_GetFullName( name, TRUE, &full_name ))
1596 retv = (fork_and_exec( full_name.long_name, tidy_cmdline, envW, unixdir ) != -1);
1600 CloseHandle( hFile );
1603 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1604 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1609 /***********************************************************************
1612 * Wrapper to call WaitForInputIdle USER function
1614 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1616 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1618 HMODULE mod = GetModuleHandleA( "user32.dll" );
1621 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1622 if (ptr) return ptr( process, timeout );
1628 /***********************************************************************
1629 * WinExec (KERNEL32.@)
1631 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1633 PROCESS_INFORMATION info;
1634 STARTUPINFOA startup;
1638 memset( &startup, 0, sizeof(startup) );
1639 startup.cb = sizeof(startup);
1640 startup.dwFlags = STARTF_USESHOWWINDOW;
1641 startup.wShowWindow = nCmdShow;
1643 /* cmdline needs to be writeable for CreateProcess */
1644 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1645 strcpy( cmdline, lpCmdLine );
1647 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1648 0, NULL, NULL, &startup, &info ))
1650 /* Give 30 seconds to the app to come up */
1651 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF)
1652 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1654 /* Close off the handles */
1655 CloseHandle( info.hThread );
1656 CloseHandle( info.hProcess );
1658 else if ((ret = GetLastError()) >= 32)
1660 FIXME("Strange error set by CreateProcess: %d\n", ret );
1663 HeapFree( GetProcessHeap(), 0, cmdline );
1668 /**********************************************************************
1669 * LoadModule (KERNEL32.@)
1671 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1673 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
1674 PROCESS_INFORMATION info;
1675 STARTUPINFOA startup;
1676 HINSTANCE hInstance;
1678 char filename[MAX_PATH];
1681 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1683 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1684 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1685 return (HINSTANCE)GetLastError();
1687 len = (BYTE)params->lpCmdLine[0];
1688 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1689 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1691 strcpy( cmdline, filename );
1692 p = cmdline + strlen(cmdline);
1694 memcpy( p, params->lpCmdLine + 1, len );
1697 memset( &startup, 0, sizeof(startup) );
1698 startup.cb = sizeof(startup);
1699 if (params->lpCmdShow)
1701 startup.dwFlags = STARTF_USESHOWWINDOW;
1702 startup.wShowWindow = params->lpCmdShow[1];
1705 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1706 params->lpEnvAddress, NULL, &startup, &info ))
1708 /* Give 30 seconds to the app to come up */
1709 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF )
1710 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1711 hInstance = (HINSTANCE)33;
1712 /* Close off the handles */
1713 CloseHandle( info.hThread );
1714 CloseHandle( info.hProcess );
1716 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1718 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1719 hInstance = (HINSTANCE)11;
1722 HeapFree( GetProcessHeap(), 0, cmdline );
1727 /******************************************************************************
1728 * TerminateProcess (KERNEL32.@)
1730 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1732 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1733 if (status) SetLastError( RtlNtStatusToDosError(status) );
1738 /***********************************************************************
1739 * GetExitCodeProcess [KERNEL32.@]
1741 * Gets termination status of specified process
1747 BOOL WINAPI GetExitCodeProcess(
1748 HANDLE hProcess, /* [in] handle to the process */
1749 LPDWORD lpExitCode) /* [out] address to receive termination status */
1752 SERVER_START_REQ( get_process_info )
1754 req->handle = hProcess;
1755 ret = !wine_server_call_err( req );
1756 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1763 /***********************************************************************
1764 * SetErrorMode (KERNEL32.@)
1766 UINT WINAPI SetErrorMode( UINT mode )
1768 UINT old = current_process.error_mode;
1769 current_process.error_mode = mode;
1774 /**********************************************************************
1775 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1777 * Allocates a thread local storage index
1780 * Success: TLS Index
1781 * Failure: 0xFFFFFFFF
1783 DWORD WINAPI TlsAlloc( void )
1785 DWORD i, mask, ret = 0;
1786 DWORD *bits = current_process.tls_bits;
1787 RtlAcquirePebLock();
1788 if (*bits == 0xffffffff)
1792 if (*bits == 0xffffffff)
1794 RtlReleasePebLock();
1795 SetLastError( ERROR_NO_MORE_ITEMS );
1799 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1801 RtlReleasePebLock();
1802 NtCurrentTeb()->TlsSlots[ret+i] = 0; /* clear the value */
1807 /**********************************************************************
1808 * TlsFree [KERNEL32.@] Releases a TLS index.
1810 * Releases a thread local storage index, making it available for reuse
1816 BOOL WINAPI TlsFree(
1817 DWORD index) /* [in] TLS Index to free */
1819 DWORD mask = (1 << (index & 31));
1820 DWORD *bits = current_process.tls_bits;
1823 SetLastError( ERROR_INVALID_PARAMETER );
1826 if (index >= 32) bits++;
1827 RtlAcquirePebLock();
1828 if (!(*bits & mask)) /* already free? */
1830 RtlReleasePebLock();
1831 SetLastError( ERROR_INVALID_PARAMETER );
1835 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1836 RtlReleasePebLock();
1841 /**********************************************************************
1842 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1845 * Success: Value stored in calling thread's TLS slot for index
1846 * Failure: 0 and GetLastError returns NO_ERROR
1848 LPVOID WINAPI TlsGetValue(
1849 DWORD index) /* [in] TLS index to retrieve value for */
1853 SetLastError( ERROR_INVALID_PARAMETER );
1856 SetLastError( ERROR_SUCCESS );
1857 return NtCurrentTeb()->TlsSlots[index];
1861 /**********************************************************************
1862 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1868 BOOL WINAPI TlsSetValue(
1869 DWORD index, /* [in] TLS index to set value for */
1870 LPVOID value) /* [in] Value to be stored */
1874 SetLastError( ERROR_INVALID_PARAMETER );
1877 NtCurrentTeb()->TlsSlots[index] = value;
1882 /***********************************************************************
1883 * GetProcessFlags (KERNEL32.@)
1885 DWORD WINAPI GetProcessFlags( DWORD processid )
1887 IMAGE_NT_HEADERS *nt;
1890 if (processid && processid != GetCurrentProcessId()) return 0;
1892 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1894 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
1895 flags |= PDB32_CONSOLE_PROC;
1897 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
1898 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
1903 /***********************************************************************
1904 * GetProcessDword (KERNEL.485)
1905 * GetProcessDword (KERNEL32.18)
1906 * 'Of course you cannot directly access Windows internal structures'
1908 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1913 TRACE("(%ld, %d)\n", dwProcessID, offset );
1915 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1917 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1923 case GPD_APP_COMPAT_FLAGS:
1924 return GetAppCompatFlags16(0);
1925 case GPD_LOAD_DONE_EVENT:
1927 case GPD_HINSTANCE16:
1928 return GetTaskDS16();
1929 case GPD_WINDOWS_VERSION:
1930 return GetExeVersion16();
1932 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1934 return (DWORD)NtCurrentTeb()->Peb;
1935 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1936 GetStartupInfoW(&siw);
1937 return (DWORD)siw.hStdOutput;
1938 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1939 GetStartupInfoW(&siw);
1940 return (DWORD)siw.hStdInput;
1941 case GPD_STARTF_SHOWWINDOW:
1942 GetStartupInfoW(&siw);
1943 return siw.wShowWindow;
1944 case GPD_STARTF_SIZE:
1945 GetStartupInfoW(&siw);
1947 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1949 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1950 return MAKELONG( x, y );
1951 case GPD_STARTF_POSITION:
1952 GetStartupInfoW(&siw);
1954 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1956 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1957 return MAKELONG( x, y );
1958 case GPD_STARTF_FLAGS:
1959 GetStartupInfoW(&siw);
1964 return GetProcessFlags(0);
1966 return process_dword;
1968 ERR("Unknown offset %d\n", offset );
1973 /***********************************************************************
1974 * SetProcessDword (KERNEL.484)
1975 * 'Of course you cannot directly access Windows internal structures'
1977 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1979 TRACE("(%ld, %d)\n", dwProcessID, offset );
1981 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1983 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1989 case GPD_APP_COMPAT_FLAGS:
1990 case GPD_LOAD_DONE_EVENT:
1991 case GPD_HINSTANCE16:
1992 case GPD_WINDOWS_VERSION:
1995 case GPD_STARTF_SHELLDATA:
1996 case GPD_STARTF_HOTKEY:
1997 case GPD_STARTF_SHOWWINDOW:
1998 case GPD_STARTF_SIZE:
1999 case GPD_STARTF_POSITION:
2000 case GPD_STARTF_FLAGS:
2003 ERR("Not allowed to modify offset %d\n", offset );
2006 process_dword = value;
2009 ERR("Unknown offset %d\n", offset );
2015 /***********************************************************************
2016 * ExitProcess (KERNEL.466)
2018 void WINAPI ExitProcess16( WORD status )
2021 ReleaseThunkLock( &count );
2022 ExitProcess( status );
2026 /*********************************************************************
2027 * OpenProcess (KERNEL32.@)
2029 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2032 SERVER_START_REQ( open_process )
2035 req->access = access;
2036 req->inherit = inherit;
2037 if (!wine_server_call_err( req )) ret = reply->handle;
2044 /*********************************************************************
2045 * MapProcessHandle (KERNEL.483)
2047 DWORD WINAPI MapProcessHandle( HANDLE handle )
2050 SERVER_START_REQ( get_process_info )
2052 req->handle = handle;
2053 if (!wine_server_call_err( req )) ret = reply->pid;
2060 /***********************************************************************
2061 * SetPriorityClass (KERNEL32.@)
2063 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2066 SERVER_START_REQ( set_process_info )
2068 req->handle = hprocess;
2069 req->priority = priorityclass;
2070 req->mask = SET_PROCESS_INFO_PRIORITY;
2071 ret = !wine_server_call_err( req );
2078 /***********************************************************************
2079 * GetPriorityClass (KERNEL32.@)
2081 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2084 SERVER_START_REQ( get_process_info )
2086 req->handle = hprocess;
2087 if (!wine_server_call_err( req )) ret = reply->priority;
2094 /***********************************************************************
2095 * SetProcessAffinityMask (KERNEL32.@)
2097 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2100 SERVER_START_REQ( set_process_info )
2102 req->handle = hProcess;
2103 req->affinity = affmask;
2104 req->mask = SET_PROCESS_INFO_AFFINITY;
2105 ret = !wine_server_call_err( req );
2112 /**********************************************************************
2113 * GetProcessAffinityMask (KERNEL32.@)
2115 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2116 LPDWORD lpProcessAffinityMask,
2117 LPDWORD lpSystemAffinityMask )
2120 SERVER_START_REQ( get_process_info )
2122 req->handle = hProcess;
2123 if (!wine_server_call_err( req ))
2125 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2126 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2135 /***********************************************************************
2136 * GetProcessVersion (KERNEL32.@)
2138 DWORD WINAPI GetProcessVersion( DWORD processid )
2140 IMAGE_NT_HEADERS *nt;
2142 if (processid && processid != GetCurrentProcessId())
2144 FIXME("should use ReadProcessMemory\n");
2147 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2148 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2149 nt->OptionalHeader.MinorSubsystemVersion);
2154 /***********************************************************************
2155 * SetProcessWorkingSetSize [KERNEL32.@]
2156 * Sets the min/max working set sizes for a specified process.
2159 * hProcess [I] Handle to the process of interest
2160 * minset [I] Specifies minimum working set size
2161 * maxset [I] Specifies maximum working set size
2165 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2168 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2169 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2170 /* Trim the working set to zero */
2171 /* Swap the process out of physical RAM */
2176 /***********************************************************************
2177 * GetProcessWorkingSetSize (KERNEL32.@)
2179 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2182 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2183 /* 32 MB working set size */
2184 if (minset) *minset = 32*1024*1024;
2185 if (maxset) *maxset = 32*1024*1024;
2190 /***********************************************************************
2191 * SetProcessShutdownParameters (KERNEL32.@)
2193 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2195 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2196 shutdown_flags = flags;
2197 shutdown_priority = level;
2202 /***********************************************************************
2203 * GetProcessShutdownParameters (KERNEL32.@)
2206 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2208 *lpdwLevel = shutdown_priority;
2209 *lpdwFlags = shutdown_flags;
2214 /***********************************************************************
2215 * GetProcessPriorityBoost (KERNEL32.@)
2217 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2219 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2221 /* Report that no boost is present.. */
2222 *pDisablePriorityBoost = FALSE;
2227 /***********************************************************************
2228 * SetProcessPriorityBoost (KERNEL32.@)
2230 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2232 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2233 /* Say we can do it. I doubt the program will notice that we don't. */
2238 /***********************************************************************
2239 * ReadProcessMemory (KERNEL32.@)
2241 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2242 SIZE_T *bytes_read )
2244 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2245 if (status) SetLastError( RtlNtStatusToDosError(status) );
2250 /***********************************************************************
2251 * WriteProcessMemory (KERNEL32.@)
2253 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2254 SIZE_T *bytes_written )
2256 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2257 if (status) SetLastError( RtlNtStatusToDosError(status) );
2262 /****************************************************************************
2263 * FlushInstructionCache (KERNEL32.@)
2265 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2267 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2268 FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2273 /******************************************************************
2274 * GetProcessIoCounters (KERNEL32.@)
2276 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2280 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2281 ioc, sizeof(*ioc), NULL);
2282 if (status) SetLastError( RtlNtStatusToDosError(status) );
2286 /***********************************************************************
2287 * ProcessIdToSessionId (KERNEL32.@)
2288 * This function is available on Terminal Server 4SP4 and Windows 2000
2290 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2292 /* According to MSDN, if the calling process is not in a terminal
2293 * services environment, then the sessionid returned is zero.
2300 /***********************************************************************
2301 * RegisterServiceProcess (KERNEL.491)
2302 * RegisterServiceProcess (KERNEL32.@)
2304 * A service process calls this function to ensure that it continues to run
2305 * even after a user logged off.
2307 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2309 /* I don't think that Wine needs to do anything in that function */
2310 return 1; /* success */
2314 /**************************************************************************
2315 * SetFileApisToOEM (KERNEL32.@)
2317 VOID WINAPI SetFileApisToOEM(void)
2319 oem_file_apis = TRUE;
2323 /**************************************************************************
2324 * SetFileApisToANSI (KERNEL32.@)
2326 VOID WINAPI SetFileApisToANSI(void)
2328 oem_file_apis = FALSE;
2332 /******************************************************************************
2333 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
2336 * TRUE: Set of file functions is using ANSI code page
2337 * FALSE: Set of file functions is using OEM code page
2339 BOOL WINAPI AreFileApisANSI(void)
2341 return !oem_file_apis;
2345 /***********************************************************************
2346 * GetCurrentProcess (KERNEL32.@)
2348 #undef GetCurrentProcess
2349 HANDLE WINAPI GetCurrentProcess(void)
2351 return (HANDLE)0xffffffff;