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/debug.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(process);
45 WINE_DECLARE_DEBUG_CHANNEL(server);
46 WINE_DECLARE_DEBUG_CHANNEL(relay);
47 WINE_DECLARE_DEBUG_CHANNEL(snoop);
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 RTL_USER_PROCESS_PARAMETERS process_pmts;
102 static PEB_LDR_DATA process_ldr;
104 static char main_exe_name[MAX_PATH];
105 static char *main_exe_name_ptr = main_exe_name;
106 static HANDLE main_exe_file;
107 static DWORD shutdown_flags = 0;
108 static DWORD shutdown_priority = 0x280;
109 static DWORD process_dword;
110 static BOOL oem_file_apis;
112 extern unsigned int server_startticks;
113 int main_create_flags = 0;
116 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
117 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
118 #define PDB32_DOS_PROC 0x0010 /* Dos process */
119 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
120 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
121 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
123 /* dlls/ntdll/env.c */
124 extern BOOL init_user_process_pmts( size_t, char*, size_t );
125 extern BOOL build_command_line( char **argv );
127 extern WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename ); /* FIXME */
129 extern void RELAY_InitDebugLists(void);
130 extern void SHELL_LoadRegistry(void);
131 extern void VERSION_Init( const char *appname );
133 /***********************************************************************
136 inline static const char *get_basename( const char *name )
140 if ((p = strrchr( name, '/' ))) name = p + 1;
141 if ((p = strrchr( name, '\\' ))) name = p + 1;
146 /***********************************************************************
147 * open_builtin_exe_file
149 * Open an exe file for a builtin exe.
151 static void *open_builtin_exe_file( const char *name, char *error, int error_size,
152 int test_only, int *file_exists )
154 char exename[MAX_PATH], *p;
155 const char *basename = get_basename(name);
157 if (strlen(basename) >= sizeof(exename)) return NULL;
158 strcpy( exename, basename );
159 for (p = exename; *p; p++) *p = FILE_tolower(*p);
160 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
164 /***********************************************************************
167 * Open a specific exe file, taking load order into account.
168 * Returns the file handle or 0 for a builtin exe.
170 static HANDLE open_exe_file( const char *name )
172 enum loadorder_type loadorder[LOADORDER_NTYPES];
173 char buffer[MAX_PATH];
177 TRACE("looking for %s\n", debugstr_a(name) );
179 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
180 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
182 /* file doesn't exist, check for builtin */
183 if (!FILE_contains_path( name )) goto error;
184 if (!MODULE_GetBuiltinPath( name, "", buffer, sizeof(buffer) )) goto error;
188 MODULE_GetLoadOrderA( loadorder, NULL, name, TRUE );
190 for(i = 0; i < LOADORDER_NTYPES; i++)
192 if (loadorder[i] == LOADORDER_INVALID) break;
196 TRACE( "Trying native exe %s\n", debugstr_a(name) );
197 if (handle != INVALID_HANDLE_VALUE) return handle;
200 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
201 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
204 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
211 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
214 SetLastError( ERROR_FILE_NOT_FOUND );
215 return INVALID_HANDLE_VALUE;
219 /***********************************************************************
222 * Open an exe file, and return the full name and file handle.
223 * Returns FALSE if file could not be found.
224 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
225 * If file is a builtin exe, returns TRUE and sets handle to 0.
227 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
229 enum loadorder_type loadorder[LOADORDER_NTYPES];
232 TRACE("looking for %s\n", debugstr_a(name) );
234 if (!SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) &&
235 !MODULE_GetBuiltinPath( name, ".exe", buffer, buflen ))
237 /* no builtin found, try native without extension in case it is a Unix app */
239 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
241 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
242 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
243 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
249 MODULE_GetLoadOrderA( loadorder, NULL, buffer, TRUE );
251 for(i = 0; i < LOADORDER_NTYPES; i++)
253 if (loadorder[i] == LOADORDER_INVALID) break;
257 TRACE( "Trying native exe %s\n", debugstr_a(buffer) );
258 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
259 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
261 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
264 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
265 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
276 SetLastError( ERROR_FILE_NOT_FOUND );
281 /**********************************************************************
284 * Load a PE format EXE file.
286 static HMODULE load_pe_exe( HANDLE file )
288 IMAGE_NT_HEADERS *nt;
291 OBJECT_ATTRIBUTES attr;
295 attr.Length = sizeof(attr);
296 attr.RootDirectory = 0;
297 attr.ObjectName = NULL;
299 attr.SecurityDescriptor = NULL;
300 attr.SecurityQualityOfService = NULL;
303 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
304 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
308 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
309 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
315 nt = RtlImageNtHeader( module );
316 if (nt->OptionalHeader.AddressOfEntryPoint)
318 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
319 MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
320 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
321 nt->OptionalHeader.AddressOfEntryPoint );
326 /***********************************************************************
329 * Main process initialisation code
331 static BOOL process_init( char *argv[] )
334 size_t info_size = 0;
338 setlocale(LC_CTYPE,"");
340 /* store the program name */
343 /* Fill the initial process structure */
344 current_process.threads = 1;
345 current_process.running_threads = 1;
346 current_process.ring0_threads = 1;
347 current_process.group = ¤t_process;
348 current_process.priority = 8; /* Normal */
349 current_process.ProcessParameters = &process_pmts;
350 current_process.LdrData = &process_ldr;
351 InitializeListHead(&process_ldr.InLoadOrderModuleList);
352 InitializeListHead(&process_ldr.InMemoryOrderModuleList);
353 InitializeListHead(&process_ldr.InInitializationOrderModuleList);
355 /* Setup the server connection */
356 wine_server_init_thread();
358 /* Retrieve startup info from the server */
359 SERVER_START_REQ( init_process )
361 req->ldt_copy = &wine_ldt_copy;
362 if ((ret = !wine_server_call_err( req )))
364 main_exe_file = reply->exe_file;
365 main_create_flags = reply->create_flags;
366 info_size = reply->info_size;
367 server_startticks = reply->server_start;
368 process_pmts.hStdInput = reply->hstdin;
369 process_pmts.hStdOutput = reply->hstdout;
370 process_pmts.hStdError = reply->hstderr;
374 if (!ret) return FALSE;
376 /* Create the process heap */
377 current_process.heap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL );
381 /* This is wine specific: we have no parent (we're started from unix)
382 * so, create a simple console with bare handles to unix stdio
383 * input & output streams (aka simple console)
385 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &process_pmts.hStdInput );
386 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &process_pmts.hStdOutput );
387 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &process_pmts.hStdError );
391 /* convert value from server:
392 * + 0 => INVALID_HANDLE_VALUE
393 * + console handle need to be mapped
395 if (!process_pmts.hStdInput)
396 process_pmts.hStdInput = INVALID_HANDLE_VALUE;
397 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdInput)))
398 process_pmts.hStdInput = console_handle_map(process_pmts.hStdInput);
399 if (!process_pmts.hStdOutput)
400 process_pmts.hStdOutput = INVALID_HANDLE_VALUE;
401 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdOutput)))
402 process_pmts.hStdOutput = console_handle_map(process_pmts.hStdOutput);
403 if (!process_pmts.hStdError)
404 process_pmts.hStdError = INVALID_HANDLE_VALUE;
405 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdError)))
406 process_pmts.hStdError = console_handle_map(process_pmts.hStdError);
409 /* Copy the parent environment */
410 if (!init_user_process_pmts( info_size, main_exe_name, sizeof(main_exe_name) ))
413 /* Parse command line arguments */
414 OPTIONS_ParseOptions( !info_size ? argv : NULL );
416 /* <hack: to be changed later on> */
417 process_pmts.CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
418 process_pmts.CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
419 process_pmts.CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, process_pmts.CurrentDirectoryName.MaximumLength);
420 process_pmts.CurrentDirectoryName.Buffer[0] = 'C';
421 process_pmts.CurrentDirectoryName.Buffer[1] = ':';
422 process_pmts.CurrentDirectoryName.Buffer[2] = '\\';
423 process_pmts.CurrentDirectoryName.Buffer[3] = '\0';
424 /* </hack: to be changed later on> */
426 /* initialise DOS drives */
427 if (!DRIVE_Init()) return FALSE;
429 /* initialise DOS directories */
430 if (!DIR_Init()) return FALSE;
432 /* registry initialisation */
433 SHELL_LoadRegistry();
435 /* global boot finished, the rest is process-local */
436 SERVER_START_REQ( boot_done )
438 req->debug_level = TRACE_ON(server);
439 wine_server_call( req );
443 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
449 /***********************************************************************
452 * Startup routine of a new process. Runs on the new process stack.
454 static void start_process( void *arg )
458 LPTHREAD_START_ROUTINE entry;
459 HANDLE main_file = main_exe_file;
460 IMAGE_NT_HEADERS *nt;
462 PEB *peb = NtCurrentTeb()->Peb;
466 UINT drive_type = GetDriveTypeA( main_exe_name );
467 /* don't keep the file handle open on removable media */
468 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
471 /* Retrieve entry point address */
472 nt = RtlImageNtHeader( peb->ImageBaseAddress );
473 entry = (LPTHREAD_START_ROUTINE)((char*)peb->ImageBaseAddress +
474 nt->OptionalHeader.AddressOfEntryPoint);
476 /* Install signal handlers; this cannot be done before, since we cannot
477 * send exceptions to the debugger before the create process event that
478 * is sent by REQ_INIT_PROCESS_DONE.
479 * We do need the handlers in place by the time the request is over, so
480 * we set them up here. If we segfault between here and the server call
481 * something is very wrong... */
482 if (!SIGNAL_Init()) goto error;
484 /* Signal the parent process to continue */
485 SERVER_START_REQ( init_process_done )
487 req->module = peb->ImageBaseAddress;
488 req->module_size = nt->OptionalHeader.SizeOfImage;
490 /* API requires a double indirection */
491 req->name = &main_exe_name_ptr;
492 req->exe_file = main_file;
493 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
494 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
495 wine_server_call( req );
496 peb->BeingDebugged = reply->debugged;
500 /* create the main modref and load dependencies */
501 if (!(wm = MODULE_AllocModRef( peb->ImageBaseAddress, main_exe_name ))) goto error;
502 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
503 if (MODULE_DllProcessAttach( NULL, (LPVOID)1 ) != STATUS_SUCCESS)
505 ERR( "Main exe initialization failed\n" );
510 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n",
511 GetCurrentThreadId(), main_exe_name, entry );
512 if (peb->BeingDebugged) DbgBreakPoint();
513 SetLastError(0); /* clear error code */
514 ExitThread( entry( NtCurrentTeb()->Peb ) );
517 ExitProcess( GetLastError() );
519 __EXCEPT(UnhandledExceptionFilter)
521 TerminateThread( GetCurrentThread(), GetExceptionCode() );
527 /***********************************************************************
528 * __wine_process_init
530 * Wine initialisation: load and start the main exe file.
532 void __wine_process_init( int argc, char *argv[] )
534 char error[1024], *p;
535 DWORD stack_size = 0;
538 /* Initialize everything */
539 if (!process_init( argv )) exit(1);
541 argv++; /* remove argv[0] (wine itself) */
543 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
544 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
546 if (!main_exe_name[0])
548 if (!argv[0]) OPTIONS_Usage();
550 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
552 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
555 if (main_exe_file == INVALID_HANDLE_VALUE)
557 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
562 if (!main_exe_file) /* no file handle -> Winelib app */
564 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
565 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
567 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
570 VERSION_Init( main_exe_name );
572 switch( MODULE_GetBinaryType( main_exe_file ))
575 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
576 if ((current_process.module = load_pe_exe( main_exe_file ))) goto found;
577 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
580 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
583 /* check for .com extension */
584 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
586 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
592 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
593 CloseHandle( main_exe_file );
596 argv[0] = "winevdm.exe";
597 if (open_builtin_exe_file( "winevdm.exe", error, sizeof(error), 0, &file_exists ))
599 MESSAGE( "%s: trying to run '%s', cannot open builtin library for 'winevdm.exe': %s\n",
600 argv0, main_exe_name, error );
603 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
605 case BINARY_UNIX_EXE:
606 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
608 case BINARY_UNIX_LIB:
610 DOS_FULL_NAME full_name;
611 const char *name = main_exe_name;
612 UNICODE_STRING nameW;
614 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
615 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
616 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
617 RtlFreeUnicodeString(&nameW);
618 CloseHandle( main_exe_file );
620 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
622 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
625 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
631 /* build command line */
632 if (!build_command_line( argv )) goto error;
634 /* create 32-bit module for main exe */
635 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
636 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
638 /* allocate main thread stack */
639 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
641 /* switch to the new stack */
642 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
645 ExitProcess( GetLastError() );
649 /***********************************************************************
652 * Build an argv array from a command-line.
653 * The command-line is modified to insert nulls.
654 * 'reserved' is the number of args to reserve before the first one.
656 static char **build_argv( char *cmdline, int reserved )
661 int in_quotes,bcount;
668 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
671 /* skip the remaining spaces */
672 while (*s==' ' || *s=='\t') {
679 } else if (*s=='\\') {
680 /* '\', count them */
682 } else if ((*s=='"') && ((bcount & 1)==0)) {
684 in_quotes=!in_quotes;
687 /* a regular character */
692 argv=malloc(argc*sizeof(*argv));
701 if ((*s==' ' || *s=='\t') && !in_quotes) {
702 /* Close the argument and copy it */
706 /* skip the remaining spaces */
709 } while (*s==' ' || *s=='\t');
711 /* Start with a new argument */
714 } else if (*s=='\\') {
718 } else if (*s=='"') {
720 if ((bcount & 1)==0) {
721 /* Preceeded by an even number of '\', this is half that
722 * number of '\', plus a '"' which we discard.
726 in_quotes=!in_quotes;
728 /* Preceeded by an odd number of '\', this is half that
729 * number of '\' followed by a '"'
737 /* a regular character */
752 /***********************************************************************
755 * Build the environment of a new child process.
757 static char **build_envp( const char *env, const char *extra_env )
763 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
764 for (p = env; *p; count++) p += strlen(p) + 1;
767 if ((envp = malloc( count * sizeof(*envp) )))
769 extern char **environ;
770 char **envptr = envp;
771 char **unixptr = environ;
772 /* first the extra strings */
773 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
774 /* then put PATH, HOME and WINEPREFIX from the unix env */
775 for (unixptr = environ; unixptr && *unixptr; unixptr++)
776 if (!memcmp( *unixptr, "PATH=", 5 ) ||
777 !memcmp( *unixptr, "HOME=", 5 ) ||
778 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
779 /* now put the Windows environment strings */
780 for (p = env; *p; p += strlen(p) + 1)
782 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
784 char *winepath = malloc( strlen(p) + 5 );
785 strcpy( winepath, "WINE" );
786 strcpy( winepath + 4, p );
787 *envptr++ = winepath;
789 else if (memcmp( p, "HOME=", 5 ) &&
790 memcmp( p, "WINEPATH=", 9 ) &&
791 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
799 /***********************************************************************
802 * Locate the Wine binary to exec for a new Win32 process.
804 static void exec_wine_binary( char **argv, char **envp )
806 const char *path, *pos, *ptr;
808 /* first, try for a WINELOADER environment variable */
809 argv[0] = getenv("WINELOADER");
811 execve( argv[0], argv, envp );
813 /* next, try bin directory */
814 argv[0] = BINDIR "/wine";
815 execve( argv[0], argv, envp );
817 /* now try the path of argv0 of the current binary */
818 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
819 if ((ptr = strrchr( full_argv0, '/' )))
821 memcpy( argv[0], full_argv0, ptr - full_argv0 );
822 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
823 execve( argv[0], argv, envp );
827 /* now search in the Unix path */
828 if ((path = getenv( "PATH" )))
830 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
834 while (*pos == ':') pos++;
836 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
837 memcpy( argv[0], pos, ptr - pos );
838 strcpy( argv[0] + (ptr - pos), "/wine" );
839 execve( argv[0], argv, envp );
847 /***********************************************************************
850 * Fork and exec a new Unix binary, checking for errors.
852 static int fork_and_exec( const char *filename, char *cmdline,
853 const char *env, const char *newdir )
858 if (!env) env = GetEnvironmentStringsA();
865 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
866 if (!(pid = fork())) /* child */
868 char **argv = build_argv( cmdline, 0 );
869 char **envp = build_envp( env, NULL );
872 /* Reset signals that we previously set to SIG_IGN */
873 signal( SIGPIPE, SIG_DFL );
874 signal( SIGCHLD, SIG_DFL );
876 if (newdir) chdir(newdir);
878 if (argv && envp) execve( filename, argv, envp );
880 write( fd[1], &err, sizeof(err) );
884 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
889 if (pid == -1) FILE_SetDosError();
895 /***********************************************************************
898 * Create a new process. If hFile is a valid handle we have an exe
899 * file, otherwise it is a Winelib app.
901 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
902 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
903 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
904 LPPROCESS_INFORMATION info, LPCSTR unixdir )
906 BOOL ret, success = FALSE;
908 startup_info_t startup_info;
909 char *extra_env = NULL;
918 env = GetEnvironmentStringsA();
919 extra_env = DRIVE_BuildEnv();
922 /* create the synchronization pipes */
924 if (pipe( startfd ) == -1)
929 if (pipe( execfd ) == -1)
936 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
938 /* create the child process */
940 if (!(pid = fork())) /* child */
942 char **argv = build_argv( cmd_line, 1 );
943 char **envp = build_envp( env, extra_env );
948 /* wait for parent to tell us to start */
949 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
952 /* Reset signals that we previously set to SIG_IGN */
953 signal( SIGPIPE, SIG_DFL );
954 signal( SIGCHLD, SIG_DFL );
956 if (unixdir) chdir(unixdir);
958 if (argv && envp) exec_wine_binary( argv, envp );
961 write( execfd[1], &err, sizeof(err) );
965 /* this is the parent */
969 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
978 /* fill the startup info structure */
980 startup_info.size = sizeof(startup_info);
981 /* startup_info.filename_len is set below */
982 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
983 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
984 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
985 startup_info.x = startup->dwX;
986 startup_info.y = startup->dwY;
987 startup_info.cx = startup->dwXSize;
988 startup_info.cy = startup->dwYSize;
989 startup_info.x_chars = startup->dwXCountChars;
990 startup_info.y_chars = startup->dwYCountChars;
991 startup_info.attribute = startup->dwFillAttribute;
992 startup_info.cmd_show = startup->wShowWindow;
993 startup_info.flags = startup->dwFlags;
995 /* create the process on the server side */
997 SERVER_START_REQ( new_process )
1002 req->inherit_all = inherit;
1003 req->create_flags = flags;
1004 req->unix_pid = pid;
1005 req->exe_file = hFile;
1006 if (startup->dwFlags & STARTF_USESTDHANDLES)
1008 req->hstdin = startup->hStdInput;
1009 req->hstdout = startup->hStdOutput;
1010 req->hstderr = startup->hStdError;
1014 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1015 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1016 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1019 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1021 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1022 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1023 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1024 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1028 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1029 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1030 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1033 if (GetLongPathNameA( filename, buf, MAX_PATH ))
1038 startup_info.filename_len = strlen(nameptr);
1039 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
1040 wine_server_add_data( req, nameptr, startup_info.filename_len );
1041 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
1042 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
1043 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
1045 ret = !wine_server_call_err( req );
1046 process_info = reply->info;
1052 close( startfd[1] );
1057 /* tell child to start and wait for it to exec */
1059 write( startfd[1], &dummy, 1 );
1060 close( startfd[1] );
1062 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1067 CloseHandle( process_info );
1071 /* wait for the new process info to be ready */
1073 WaitForSingleObject( process_info, INFINITE );
1074 SERVER_START_REQ( get_new_process_info )
1076 req->info = process_info;
1077 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1078 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1079 if ((ret = !wine_server_call_err( req )))
1081 info->dwProcessId = (DWORD)reply->pid;
1082 info->dwThreadId = (DWORD)reply->tid;
1083 info->hProcess = reply->phandle;
1084 info->hThread = reply->thandle;
1085 success = reply->success;
1090 if (ret && !success) /* new process failed to start */
1093 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1094 CloseHandle( info->hThread );
1095 CloseHandle( info->hProcess );
1098 CloseHandle( process_info );
1103 /***********************************************************************
1104 * create_vdm_process
1106 * Create a new VDM process for a 16-bit or DOS application.
1108 static BOOL create_vdm_process( LPCSTR filename, LPSTR cmd_line, LPCSTR env,
1109 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1110 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
1111 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1114 LPSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + strlen(cmd_line) + 30 );
1118 SetLastError( ERROR_OUTOFMEMORY );
1121 sprintf( new_cmd_line, "winevdm.exe --app-name \"%s\" %s", filename, cmd_line );
1122 ret = create_process( 0, "winevdm.exe", new_cmd_line, env, psa, tsa, inherit,
1123 flags, startup, info, unixdir );
1124 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1129 /*************************************************************************
1132 * Helper for CreateProcess: retrieve the file name to load from the
1133 * app name and command line. Store the file name in buffer, and
1134 * return a possibly modified command line.
1135 * Also returns a handle to the opened file if it's a Windows binary.
1137 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1138 int buflen, HANDLE *handle )
1140 char *name, *pos, *ret = NULL;
1143 /* if we have an app name, everything is easy */
1147 /* use the unmodified app name as file name */
1148 lstrcpynA( buffer, appname, buflen );
1149 *handle = open_exe_file( buffer );
1150 if (!(ret = cmdline) || !cmdline[0])
1152 /* no command-line, create one */
1153 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1154 sprintf( ret, "\"%s\"", appname );
1161 SetLastError( ERROR_INVALID_PARAMETER );
1165 /* first check for a quoted file name */
1167 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1169 int len = p - cmdline - 1;
1170 /* extract the quoted portion as file name */
1171 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1172 memcpy( name, cmdline + 1, len );
1175 if (find_exe_file( name, buffer, buflen, handle ))
1176 ret = cmdline; /* no change necessary */
1180 /* now try the command-line word by word */
1182 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1188 do *pos++ = *p++; while (*p && *p != ' ');
1190 if (find_exe_file( name, buffer, buflen, handle ))
1197 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1199 /* now build a new command-line with quotes */
1201 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1202 sprintf( ret, "\"%s\"%s", name, p );
1205 HeapFree( GetProcessHeap(), 0, name );
1210 /**********************************************************************
1211 * CreateProcessA (KERNEL32.@)
1213 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1214 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1215 DWORD flags, LPVOID env, LPCSTR cur_dir,
1216 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1220 const char *unixdir = NULL;
1221 DOS_FULL_NAME full_dir;
1222 char name[MAX_PATH];
1226 /* Process the AppName and/or CmdLine to get module name and path */
1228 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1230 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1232 if (hFile == INVALID_HANDLE_VALUE) goto done;
1234 /* Warn if unsupported features are used */
1236 if (flags & NORMAL_PRIORITY_CLASS)
1237 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1238 if (flags & IDLE_PRIORITY_CLASS)
1239 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1240 if (flags & HIGH_PRIORITY_CLASS)
1241 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1242 if (flags & REALTIME_PRIORITY_CLASS)
1243 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1244 if (flags & CREATE_NEW_PROCESS_GROUP)
1245 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1246 if (flags & CREATE_UNICODE_ENVIRONMENT)
1247 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1248 if (flags & CREATE_SEPARATE_WOW_VDM)
1249 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1250 if (flags & CREATE_SHARED_WOW_VDM)
1251 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1252 if (flags & CREATE_DEFAULT_ERROR_MODE)
1253 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1254 if (flags & CREATE_NO_WINDOW)
1255 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1256 if (flags & PROFILE_USER)
1257 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1258 if (flags & PROFILE_KERNEL)
1259 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1260 if (flags & PROFILE_SERVER)
1261 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1262 if (startup_info->lpDesktop)
1263 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1264 name, debugstr_a(startup_info->lpDesktop));
1265 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1266 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1267 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1268 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1269 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1270 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1271 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1272 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1276 UNICODE_STRING cur_dirW;
1277 RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1278 if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1279 unixdir = full_dir.long_name;
1280 RtlFreeUnicodeString(&cur_dirW);
1284 WCHAR buf[MAX_PATH];
1285 if (GetCurrentDirectoryW(MAX_PATH, buf))
1287 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1291 info->hThread = info->hProcess = 0;
1292 info->dwProcessId = info->dwThreadId = 0;
1294 /* Determine executable type */
1296 if (!hFile) /* builtin exe */
1298 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1299 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1300 inherit, flags, startup_info, info, unixdir );
1304 switch( MODULE_GetBinaryType( hFile ))
1307 TRACE( "starting %s as Win32 binary\n", debugstr_a(name) );
1308 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1309 inherit, flags, startup_info, info, unixdir );
1313 TRACE( "starting %s as Win16/DOS binary\n", debugstr_a(name) );
1314 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1315 inherit, flags, startup_info, info, unixdir );
1318 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1319 SetLastError( ERROR_BAD_EXE_FORMAT );
1322 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1323 SetLastError( ERROR_BAD_EXE_FORMAT );
1325 case BINARY_UNIX_LIB:
1326 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1327 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1328 inherit, flags, startup_info, info, unixdir );
1330 case BINARY_UNKNOWN:
1331 /* check for .com or .bat extension */
1332 if ((p = strrchr( name, '.' )))
1334 if (!FILE_strcasecmp( p, ".com" ))
1336 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1337 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1338 inherit, flags, startup_info, info, unixdir );
1341 if (!FILE_strcasecmp( p, ".bat" ))
1343 char comspec[MAX_PATH];
1344 if (GetEnvironmentVariableA("COMSPEC", comspec, sizeof(comspec)))
1347 if ((newcmdline = HeapAlloc( GetProcessHeap(), 0,
1348 strlen(comspec) + 4 + strlen(tidy_cmdline) + 1)))
1350 sprintf( newcmdline, "%s /c %s", comspec, tidy_cmdline);
1351 TRACE( "starting %s as batch binary: %s\n",
1352 debugstr_a(name), debugstr_a(newcmdline) );
1353 retv = CreateProcessA( comspec, newcmdline, process_attr, thread_attr,
1354 inherit, flags, env, cur_dir, startup_info, info );
1355 HeapFree( GetProcessHeap(), 0, newcmdline );
1362 case BINARY_UNIX_EXE:
1364 /* unknown file, try as unix executable */
1365 UNICODE_STRING nameW;
1366 DOS_FULL_NAME full_name;
1367 const char *unixfilename = name;
1369 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1371 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1372 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1373 RtlFreeUnicodeString(&nameW);
1374 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1378 CloseHandle( hFile );
1381 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1386 /**********************************************************************
1387 * CreateProcessW (KERNEL32.@)
1389 * lpReserved is not converted
1391 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1392 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1393 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1394 LPPROCESS_INFORMATION info )
1397 STARTUPINFOA StartupInfoA;
1399 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1400 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1401 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1403 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1404 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1405 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1407 TRACE("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1409 if (startup_info->lpReserved)
1410 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1411 debugstr_w(startup_info->lpReserved));
1413 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1414 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1416 HeapFree( GetProcessHeap(), 0, cur_dirA );
1417 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1418 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1419 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1425 /***********************************************************************
1428 * Wrapper to call WaitForInputIdle USER function
1430 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1432 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1434 HMODULE mod = GetModuleHandleA( "user32.dll" );
1437 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1438 if (ptr) return ptr( process, timeout );
1444 /***********************************************************************
1445 * WinExec (KERNEL32.@)
1447 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1449 PROCESS_INFORMATION info;
1450 STARTUPINFOA startup;
1454 memset( &startup, 0, sizeof(startup) );
1455 startup.cb = sizeof(startup);
1456 startup.dwFlags = STARTF_USESHOWWINDOW;
1457 startup.wShowWindow = nCmdShow;
1459 /* cmdline needs to be writeable for CreateProcess */
1460 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1461 strcpy( cmdline, lpCmdLine );
1463 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1464 0, NULL, NULL, &startup, &info ))
1466 /* Give 30 seconds to the app to come up */
1467 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF)
1468 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1470 /* Close off the handles */
1471 CloseHandle( info.hThread );
1472 CloseHandle( info.hProcess );
1474 else if ((ret = GetLastError()) >= 32)
1476 FIXME("Strange error set by CreateProcess: %d\n", ret );
1479 HeapFree( GetProcessHeap(), 0, cmdline );
1484 /**********************************************************************
1485 * LoadModule (KERNEL32.@)
1487 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1489 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
1490 PROCESS_INFORMATION info;
1491 STARTUPINFOA startup;
1492 HINSTANCE hInstance;
1494 char filename[MAX_PATH];
1497 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1499 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1500 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1501 return (HINSTANCE)GetLastError();
1503 len = (BYTE)params->lpCmdLine[0];
1504 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1505 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1507 strcpy( cmdline, filename );
1508 p = cmdline + strlen(cmdline);
1510 memcpy( p, params->lpCmdLine + 1, len );
1513 memset( &startup, 0, sizeof(startup) );
1514 startup.cb = sizeof(startup);
1515 if (params->lpCmdShow)
1517 startup.dwFlags = STARTF_USESHOWWINDOW;
1518 startup.wShowWindow = params->lpCmdShow[1];
1521 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1522 params->lpEnvAddress, NULL, &startup, &info ))
1524 /* Give 30 seconds to the app to come up */
1525 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF )
1526 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1527 hInstance = (HINSTANCE)33;
1528 /* Close off the handles */
1529 CloseHandle( info.hThread );
1530 CloseHandle( info.hProcess );
1532 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1534 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1535 hInstance = (HINSTANCE)11;
1538 HeapFree( GetProcessHeap(), 0, cmdline );
1543 /******************************************************************************
1544 * TerminateProcess (KERNEL32.@)
1546 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1548 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1549 if (status) SetLastError( RtlNtStatusToDosError(status) );
1554 /***********************************************************************
1555 * GetExitCodeProcess [KERNEL32.@]
1557 * Gets termination status of specified process
1563 BOOL WINAPI GetExitCodeProcess(
1564 HANDLE hProcess, /* [in] handle to the process */
1565 LPDWORD lpExitCode) /* [out] address to receive termination status */
1568 SERVER_START_REQ( get_process_info )
1570 req->handle = hProcess;
1571 ret = !wine_server_call_err( req );
1572 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1579 /***********************************************************************
1580 * SetErrorMode (KERNEL32.@)
1582 UINT WINAPI SetErrorMode( UINT mode )
1584 UINT old = current_process.error_mode;
1585 current_process.error_mode = mode;
1590 /**********************************************************************
1591 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1593 * Allocates a thread local storage index
1596 * Success: TLS Index
1597 * Failure: 0xFFFFFFFF
1599 DWORD WINAPI TlsAlloc( void )
1601 DWORD i, mask, ret = 0;
1602 DWORD *bits = current_process.tls_bits;
1603 RtlAcquirePebLock();
1604 if (*bits == 0xffffffff)
1608 if (*bits == 0xffffffff)
1610 RtlReleasePebLock();
1611 SetLastError( ERROR_NO_MORE_ITEMS );
1615 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1617 RtlReleasePebLock();
1618 NtCurrentTeb()->TlsSlots[ret+i] = 0; /* clear the value */
1623 /**********************************************************************
1624 * TlsFree [KERNEL32.@] Releases a TLS index.
1626 * Releases a thread local storage index, making it available for reuse
1632 BOOL WINAPI TlsFree(
1633 DWORD index) /* [in] TLS Index to free */
1635 DWORD mask = (1 << (index & 31));
1636 DWORD *bits = current_process.tls_bits;
1639 SetLastError( ERROR_INVALID_PARAMETER );
1642 if (index >= 32) bits++;
1643 RtlAcquirePebLock();
1644 if (!(*bits & mask)) /* already free? */
1646 RtlReleasePebLock();
1647 SetLastError( ERROR_INVALID_PARAMETER );
1651 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1652 RtlReleasePebLock();
1657 /**********************************************************************
1658 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1661 * Success: Value stored in calling thread's TLS slot for index
1662 * Failure: 0 and GetLastError returns NO_ERROR
1664 LPVOID WINAPI TlsGetValue(
1665 DWORD index) /* [in] TLS index to retrieve value for */
1669 SetLastError( ERROR_INVALID_PARAMETER );
1672 SetLastError( ERROR_SUCCESS );
1673 return NtCurrentTeb()->TlsSlots[index];
1677 /**********************************************************************
1678 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1684 BOOL WINAPI TlsSetValue(
1685 DWORD index, /* [in] TLS index to set value for */
1686 LPVOID value) /* [in] Value to be stored */
1690 SetLastError( ERROR_INVALID_PARAMETER );
1693 NtCurrentTeb()->TlsSlots[index] = value;
1698 /***********************************************************************
1699 * GetProcessFlags (KERNEL32.@)
1701 DWORD WINAPI GetProcessFlags( DWORD processid )
1703 IMAGE_NT_HEADERS *nt;
1706 if (processid && processid != GetCurrentProcessId()) return 0;
1708 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1710 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
1711 flags |= PDB32_CONSOLE_PROC;
1713 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
1714 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
1719 /***********************************************************************
1720 * GetProcessDword (KERNEL.485)
1721 * GetProcessDword (KERNEL32.18)
1722 * 'Of course you cannot directly access Windows internal structures'
1724 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1729 TRACE("(%ld, %d)\n", dwProcessID, offset );
1731 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1733 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1739 case GPD_APP_COMPAT_FLAGS:
1740 return GetAppCompatFlags16(0);
1741 case GPD_LOAD_DONE_EVENT:
1743 case GPD_HINSTANCE16:
1744 return GetTaskDS16();
1745 case GPD_WINDOWS_VERSION:
1746 return GetExeVersion16();
1748 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1750 return (DWORD)NtCurrentTeb()->Peb;
1751 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1752 GetStartupInfoW(&siw);
1753 return (DWORD)siw.hStdOutput;
1754 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1755 GetStartupInfoW(&siw);
1756 return (DWORD)siw.hStdInput;
1757 case GPD_STARTF_SHOWWINDOW:
1758 GetStartupInfoW(&siw);
1759 return siw.wShowWindow;
1760 case GPD_STARTF_SIZE:
1761 GetStartupInfoW(&siw);
1763 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1765 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1766 return MAKELONG( x, y );
1767 case GPD_STARTF_POSITION:
1768 GetStartupInfoW(&siw);
1770 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1772 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1773 return MAKELONG( x, y );
1774 case GPD_STARTF_FLAGS:
1775 GetStartupInfoW(&siw);
1780 return GetProcessFlags(0);
1782 return process_dword;
1784 ERR("Unknown offset %d\n", offset );
1789 /***********************************************************************
1790 * SetProcessDword (KERNEL.484)
1791 * 'Of course you cannot directly access Windows internal structures'
1793 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1795 TRACE("(%ld, %d)\n", dwProcessID, offset );
1797 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1799 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1805 case GPD_APP_COMPAT_FLAGS:
1806 case GPD_LOAD_DONE_EVENT:
1807 case GPD_HINSTANCE16:
1808 case GPD_WINDOWS_VERSION:
1811 case GPD_STARTF_SHELLDATA:
1812 case GPD_STARTF_HOTKEY:
1813 case GPD_STARTF_SHOWWINDOW:
1814 case GPD_STARTF_SIZE:
1815 case GPD_STARTF_POSITION:
1816 case GPD_STARTF_FLAGS:
1819 ERR("Not allowed to modify offset %d\n", offset );
1822 process_dword = value;
1825 ERR("Unknown offset %d\n", offset );
1831 /***********************************************************************
1832 * ExitProcess (KERNEL.466)
1834 void WINAPI ExitProcess16( WORD status )
1837 ReleaseThunkLock( &count );
1838 ExitProcess( status );
1842 /*********************************************************************
1843 * OpenProcess (KERNEL32.@)
1845 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1848 SERVER_START_REQ( open_process )
1851 req->access = access;
1852 req->inherit = inherit;
1853 if (!wine_server_call_err( req )) ret = reply->handle;
1860 /*********************************************************************
1861 * MapProcessHandle (KERNEL.483)
1863 DWORD WINAPI MapProcessHandle( HANDLE handle )
1866 SERVER_START_REQ( get_process_info )
1868 req->handle = handle;
1869 if (!wine_server_call_err( req )) ret = reply->pid;
1876 /***********************************************************************
1877 * SetPriorityClass (KERNEL32.@)
1879 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1882 SERVER_START_REQ( set_process_info )
1884 req->handle = hprocess;
1885 req->priority = priorityclass;
1886 req->mask = SET_PROCESS_INFO_PRIORITY;
1887 ret = !wine_server_call_err( req );
1894 /***********************************************************************
1895 * GetPriorityClass (KERNEL32.@)
1897 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1900 SERVER_START_REQ( get_process_info )
1902 req->handle = hprocess;
1903 if (!wine_server_call_err( req )) ret = reply->priority;
1910 /***********************************************************************
1911 * SetProcessAffinityMask (KERNEL32.@)
1913 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1916 SERVER_START_REQ( set_process_info )
1918 req->handle = hProcess;
1919 req->affinity = affmask;
1920 req->mask = SET_PROCESS_INFO_AFFINITY;
1921 ret = !wine_server_call_err( req );
1928 /**********************************************************************
1929 * GetProcessAffinityMask (KERNEL32.@)
1931 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1932 LPDWORD lpProcessAffinityMask,
1933 LPDWORD lpSystemAffinityMask )
1936 SERVER_START_REQ( get_process_info )
1938 req->handle = hProcess;
1939 if (!wine_server_call_err( req ))
1941 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1942 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1951 /***********************************************************************
1952 * GetProcessVersion (KERNEL32.@)
1954 DWORD WINAPI GetProcessVersion( DWORD processid )
1956 IMAGE_NT_HEADERS *nt;
1958 if (processid && processid != GetCurrentProcessId())
1960 FIXME("should use ReadProcessMemory\n");
1963 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1964 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1965 nt->OptionalHeader.MinorSubsystemVersion);
1970 /***********************************************************************
1971 * SetProcessWorkingSetSize [KERNEL32.@]
1972 * Sets the min/max working set sizes for a specified process.
1975 * hProcess [I] Handle to the process of interest
1976 * minset [I] Specifies minimum working set size
1977 * maxset [I] Specifies maximum working set size
1981 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
1984 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1985 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
1986 /* Trim the working set to zero */
1987 /* Swap the process out of physical RAM */
1992 /***********************************************************************
1993 * GetProcessWorkingSetSize (KERNEL32.@)
1995 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
1998 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
1999 /* 32 MB working set size */
2000 if (minset) *minset = 32*1024*1024;
2001 if (maxset) *maxset = 32*1024*1024;
2006 /***********************************************************************
2007 * SetProcessShutdownParameters (KERNEL32.@)
2009 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2011 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2012 shutdown_flags = flags;
2013 shutdown_priority = level;
2018 /***********************************************************************
2019 * GetProcessShutdownParameters (KERNEL32.@)
2022 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2024 *lpdwLevel = shutdown_priority;
2025 *lpdwFlags = shutdown_flags;
2030 /***********************************************************************
2031 * GetProcessPriorityBoost (KERNEL32.@)
2033 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2035 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2037 /* Report that no boost is present.. */
2038 *pDisablePriorityBoost = FALSE;
2043 /***********************************************************************
2044 * SetProcessPriorityBoost (KERNEL32.@)
2046 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2048 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2049 /* Say we can do it. I doubt the program will notice that we don't. */
2054 /***********************************************************************
2055 * ReadProcessMemory (KERNEL32.@)
2057 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2058 SIZE_T *bytes_read )
2060 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2061 if (status) SetLastError( RtlNtStatusToDosError(status) );
2066 /***********************************************************************
2067 * WriteProcessMemory (KERNEL32.@)
2069 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2070 SIZE_T *bytes_written )
2072 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2073 if (status) SetLastError( RtlNtStatusToDosError(status) );
2078 /****************************************************************************
2079 * FlushInstructionCache (KERNEL32.@)
2081 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2083 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2084 FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2089 /******************************************************************
2090 * GetProcessIoCounters (KERNEL32.@)
2092 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2096 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2097 ioc, sizeof(*ioc), NULL);
2098 if (status) SetLastError( RtlNtStatusToDosError(status) );
2102 /***********************************************************************
2103 * ProcessIdToSessionId (KERNEL32.@)
2104 * This function is available on Terminal Server 4SP4 and Windows 2000
2106 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2108 /* According to MSDN, if the calling process is not in a terminal
2109 * services environment, then the sessionid returned is zero.
2116 /***********************************************************************
2117 * RegisterServiceProcess (KERNEL.491)
2118 * RegisterServiceProcess (KERNEL32.@)
2120 * A service process calls this function to ensure that it continues to run
2121 * even after a user logged off.
2123 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2125 /* I don't think that Wine needs to do anything in that function */
2126 return 1; /* success */
2130 /**************************************************************************
2131 * SetFileApisToOEM (KERNEL32.@)
2133 VOID WINAPI SetFileApisToOEM(void)
2135 oem_file_apis = TRUE;
2139 /**************************************************************************
2140 * SetFileApisToANSI (KERNEL32.@)
2142 VOID WINAPI SetFileApisToANSI(void)
2144 oem_file_apis = FALSE;
2148 /******************************************************************************
2149 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
2152 * TRUE: Set of file functions is using ANSI code page
2153 * FALSE: Set of file functions is using OEM code page
2155 BOOL WINAPI AreFileApisANSI(void)
2157 return !oem_file_apis;
2161 /***********************************************************************
2162 * GetCurrentProcess (KERNEL32.@)
2164 #undef GetCurrentProcess
2165 HANDLE WINAPI GetCurrentProcess(void)
2167 return (HANDLE)0xffffffff;