Change calls to CLSIDFromString to SHCLSIDFromStringW except in
[wine/multimedia.git] / scheduler / process.c
blobd208cfb2805864a9de48e258137034d3e6bf7840
1 /*
2 * Win32 processes
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35 #include "wine/winbase16.h"
36 #include "wine/winuser16.h"
37 #include "wine/exception.h"
38 #include "wine/library.h"
39 #include "drive.h"
40 #include "module.h"
41 #include "file.h"
42 #include "heap.h"
43 #include "thread.h"
44 #include "winerror.h"
45 #include "wincon.h"
46 #include "wine/server.h"
47 #include "options.h"
48 #include "wine/debug.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(process);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
52 WINE_DECLARE_DEBUG_CHANNEL(snoop);
53 WINE_DECLARE_DEBUG_CHANNEL(win32);
55 struct _ENVDB;
57 /* Win32 process database */
58 typedef struct _PDB
60 LONG header[2]; /* 00 Kernel object header */
61 HMODULE module; /* 08 Main exe module (NT) */
62 void *event; /* 0c Pointer to an event object (unused) */
63 DWORD exit_code; /* 10 Process exit code */
64 DWORD unknown2; /* 14 Unknown */
65 HANDLE heap; /* 18 Default process heap */
66 HANDLE mem_context; /* 1c Process memory context */
67 DWORD flags; /* 20 Flags */
68 void *pdb16; /* 24 DOS PSP */
69 WORD PSP_sel; /* 28 Selector to DOS PSP */
70 WORD imte; /* 2a IMTE for the process module */
71 WORD threads; /* 2c Number of threads */
72 WORD running_threads; /* 2e Number of running threads */
73 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
74 WORD ring0_threads; /* 32 Number of ring 0 threads */
75 HANDLE system_heap; /* 34 System heap to allocate handles */
76 HTASK task; /* 38 Win16 task */
77 void *mem_map_files; /* 3c Pointer to mem-mapped files */
78 struct _ENVDB *env_db; /* 40 Environment database */
79 void *handle_table; /* 44 Handle table */
80 struct _PDB *parent; /* 48 Parent process */
81 void *modref_list; /* 4c MODREF list */
82 void *thread_list; /* 50 List of threads */
83 void *debuggee_CB; /* 54 Debuggee context block */
84 void *local_heap_free; /* 58 Head of local heap free list */
85 DWORD unknown4; /* 5c Unknown */
86 CRITICAL_SECTION crit_section; /* 60 Critical section */
87 DWORD unknown5[3]; /* 78 Unknown */
88 void *console; /* 84 Console */
89 DWORD tls_bits[2]; /* 88 TLS in-use bits */
90 DWORD process_dword; /* 90 Unknown */
91 struct _PDB *group; /* 94 Process group */
92 void *exe_modref; /* 98 MODREF for the process EXE */
93 void *top_filter; /* 9c Top exception filter */
94 DWORD priority; /* a0 Priority level */
95 HANDLE heap_list; /* a4 Head of process heap list */
96 void *heap_handles; /* a8 Head of heap handles list */
97 DWORD unknown6; /* ac Unknown */
98 void *console_provider; /* b0 Console provider (??) */
99 WORD env_selector; /* b4 Selector to process environment */
100 WORD error_mode; /* b6 Error mode */
101 HANDLE load_done_evt; /* b8 Event for process loading done */
102 void *UTState; /* bc Head of Univeral Thunk list */
103 DWORD unknown8; /* c0 Unknown (NT) */
104 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
105 } PDB;
107 PDB current_process;
109 /* Process flags */
110 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
111 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
112 #define PDB32_DOS_PROC 0x0010 /* Dos process */
113 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
114 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
115 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
117 static char main_exe_name[MAX_PATH];
118 static char *main_exe_name_ptr = main_exe_name;
119 static HANDLE main_exe_file;
120 static unsigned int server_startticks;
122 int main_create_flags = 0;
124 /* memory/environ.c */
125 extern struct _ENVDB *ENV_InitStartupInfo( size_t info_size, char *main_exe_name,
126 size_t main_exe_size );
127 extern BOOL ENV_BuildCommandLine( char **argv );
128 extern STARTUPINFOA current_startupinfo;
130 /* scheduler/pthread.c */
131 extern void PTHREAD_init_done(void);
133 extern void RELAY_InitDebugLists(void);
134 extern BOOL MAIN_MainInit(void);
136 typedef WORD (WINAPI *pUserSignalProc)( UINT, DWORD, DWORD, HMODULE16 );
138 /***********************************************************************
139 * PROCESS_CallUserSignalProc
141 * FIXME: Some of the signals aren't sent correctly!
143 * The exact meaning of the USER signals is undocumented, but this
144 * should cover the basic idea:
146 * USIG_DLL_UNLOAD_WIN16
147 * This is sent when a 16-bit module is unloaded.
149 * USIG_DLL_UNLOAD_WIN32
150 * This is sent when a 32-bit module is unloaded.
152 * USIG_DLL_UNLOAD_ORPHANS
153 * This is sent after the last Win3.1 module is unloaded,
154 * to allow removal of orphaned menus.
156 * USIG_FAULT_DIALOG_PUSH
157 * USIG_FAULT_DIALOG_POP
158 * These are called to allow USER to prepare for displaying a
159 * fault dialog, even though the fault might have happened while
160 * inside a USER critical section.
162 * USIG_THREAD_INIT
163 * This is called from the context of a new thread, as soon as it
164 * has started to run.
166 * USIG_THREAD_EXIT
167 * This is called, still in its context, just before a thread is
168 * about to terminate.
170 * USIG_PROCESS_CREATE
171 * This is called, in the parent process context, after a new process
172 * has been created.
174 * USIG_PROCESS_INIT
175 * This is called in the new process context, just after the main thread
176 * has started execution (after the main thread's USIG_THREAD_INIT has
177 * been sent).
179 * USIG_PROCESS_LOADED
180 * This is called after the executable file has been loaded into the
181 * new process context.
183 * USIG_PROCESS_RUNNING
184 * This is called immediately before the main entry point is called.
186 * USIG_PROCESS_EXIT
187 * This is called in the context of a process that is about to
188 * terminate (but before the last thread's USIG_THREAD_EXIT has
189 * been sent).
191 * USIG_PROCESS_DESTROY
192 * This is called after a process has terminated.
195 * The meaning of the dwFlags bits is as follows:
197 * USIG_FLAGS_WIN32
198 * Current process is 32-bit.
200 * USIG_FLAGS_GUI
201 * Current process is a (Win32) GUI process.
203 * USIG_FLAGS_FEEDBACK
204 * Current process needs 'feedback' (determined from the STARTUPINFO
205 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
207 * USIG_FLAGS_FAULT
208 * The signal is being sent due to a fault.
210 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
212 DWORD dwFlags = 0;
213 HMODULE user;
214 pUserSignalProc proc;
216 if (!(user = GetModuleHandleA( "user32.dll" ))) return;
217 if (!(proc = (pUserSignalProc)GetProcAddress( user, "UserSignalProc" ))) return;
219 /* Determine dwFlags */
221 if ( !(current_process.flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
222 if ( !(current_process.flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
224 if ( dwFlags & USIG_FLAGS_GUI )
226 /* Feedback defaults to ON */
227 if ( !(current_startupinfo.dwFlags & STARTF_FORCEOFFFEEDBACK) )
228 dwFlags |= USIG_FLAGS_FEEDBACK;
230 else
232 /* Feedback defaults to OFF */
233 if (current_startupinfo.dwFlags & STARTF_FORCEONFEEDBACK)
234 dwFlags |= USIG_FLAGS_FEEDBACK;
237 /* Call USER signal proc */
239 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
240 proc( uCode, GetCurrentThreadId(), dwFlags, hModule );
241 else
242 proc( uCode, GetCurrentProcessId(), dwFlags, hModule );
246 /***********************************************************************
247 * get_basename
249 inline static const char *get_basename( const char *name )
251 char *p;
253 if ((p = strrchr( name, '/' ))) name = p + 1;
254 if ((p = strrchr( name, '\\' ))) name = p + 1;
255 return name;
259 /***********************************************************************
260 * open_builtin_exe_file
262 * Open an exe file for a builtin exe.
264 static void *open_builtin_exe_file( const char *name, char *error, int error_size, int test_only )
266 char exename[MAX_PATH], *p;
267 const char *basename = get_basename(name);
269 if (strlen(basename) >= sizeof(exename)) return NULL;
270 strcpy( exename, basename );
271 for (p = exename; *p; p++) *p = FILE_tolower(*p);
272 return wine_dll_load_main_exe( exename, error, error_size, test_only );
276 /***********************************************************************
277 * open_exe_file
279 * Open a specific exe file, taking load order into account.
280 * Returns the file handle or 0 for a builtin exe.
282 static HANDLE open_exe_file( const char *name )
284 enum loadorder_type loadorder[LOADORDER_NTYPES];
285 char buffer[MAX_PATH];
286 HANDLE handle;
287 int i;
289 TRACE("looking for %s\n", debugstr_a(name) );
291 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
292 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
294 /* file doesn't exist, check for builtin */
295 if (!FILE_contains_path( name )) goto error;
296 if (!MODULE_GetBuiltinPath( name, "", buffer, sizeof(buffer) )) goto error;
297 name = buffer;
300 MODULE_GetLoadOrder( loadorder, name, TRUE );
302 for(i = 0; i < LOADORDER_NTYPES; i++)
304 if (loadorder[i] == LOADORDER_INVALID) break;
305 switch(loadorder[i])
307 case LOADORDER_DLL:
308 TRACE( "Trying native exe %s\n", debugstr_a(name) );
309 if (handle != INVALID_HANDLE_VALUE) return handle;
310 break;
311 case LOADORDER_BI:
312 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
313 if (open_builtin_exe_file( name, NULL, 0, 1 ))
315 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
316 return 0;
318 default:
319 break;
322 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
324 error:
325 SetLastError( ERROR_FILE_NOT_FOUND );
326 return INVALID_HANDLE_VALUE;
330 /***********************************************************************
331 * find_exe_file
333 * Open an exe file, and return the full name and file handle.
334 * Returns FALSE if file could not be found.
335 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
336 * If file is a builtin exe, returns TRUE and sets handle to 0.
338 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
340 enum loadorder_type loadorder[LOADORDER_NTYPES];
341 int i;
343 TRACE("looking for %s\n", debugstr_a(name) );
345 if (!SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) &&
346 !MODULE_GetBuiltinPath( name, ".exe", buffer, buflen ))
348 /* no builtin found, try native without extension in case it is a Unix app */
350 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
352 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
353 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
354 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
355 return TRUE;
357 return FALSE;
360 MODULE_GetLoadOrder( loadorder, buffer, TRUE );
362 for(i = 0; i < LOADORDER_NTYPES; i++)
364 if (loadorder[i] == LOADORDER_INVALID) break;
365 switch(loadorder[i])
367 case LOADORDER_DLL:
368 TRACE( "Trying native exe %s\n", debugstr_a(buffer) );
369 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
370 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
371 return TRUE;
372 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
373 break;
374 case LOADORDER_BI:
375 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
376 if (open_builtin_exe_file( buffer, NULL, 0, 1 ))
378 *handle = 0;
379 return TRUE;
381 break;
382 default:
383 break;
386 SetLastError( ERROR_FILE_NOT_FOUND );
387 return FALSE;
391 /***********************************************************************
392 * process_init
394 * Main process initialisation code
396 static BOOL process_init( char *argv[] )
398 BOOL ret;
399 size_t info_size = 0;
401 /* store the program name */
402 argv0 = argv[0];
404 /* Fill the initial process structure */
405 current_process.exit_code = STILL_ACTIVE;
406 current_process.threads = 1;
407 current_process.running_threads = 1;
408 current_process.ring0_threads = 1;
409 current_process.group = &current_process;
410 current_process.priority = 8; /* Normal */
412 /* Setup the server connection */
413 CLIENT_InitServer();
415 /* Retrieve startup info from the server */
416 SERVER_START_REQ( init_process )
418 req->ldt_copy = &wine_ldt_copy;
419 req->ppid = getppid();
420 if ((ret = !wine_server_call_err( req )))
422 main_exe_file = reply->exe_file;
423 main_create_flags = reply->create_flags;
424 info_size = reply->info_size;
425 server_startticks = reply->server_start;
426 current_startupinfo.hStdInput = reply->hstdin;
427 current_startupinfo.hStdOutput = reply->hstdout;
428 current_startupinfo.hStdError = reply->hstderr;
431 SERVER_END_REQ;
432 if (!ret) return FALSE;
434 /* Create the process heap */
435 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
437 if (main_create_flags == 0 &&
438 current_startupinfo.hStdInput == 0 &&
439 current_startupinfo.hStdOutput == 0 &&
440 current_startupinfo.hStdError == 0)
442 /* no parent, and no new console requested, create a simple console with bare handles to
443 * unix stdio input & output streams (aka simple console)
445 HANDLE handle;
446 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &handle );
447 SetStdHandle( STD_INPUT_HANDLE, handle );
448 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
449 SetStdHandle( STD_OUTPUT_HANDLE, handle );
450 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
451 SetStdHandle( STD_ERROR_HANDLE, handle );
453 else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
455 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
456 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
457 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
460 /* Now we can use the pthreads routines */
461 PTHREAD_init_done();
463 /* Copy the parent environment */
464 if (!(current_process.env_db = ENV_InitStartupInfo( info_size, main_exe_name,
465 sizeof(main_exe_name) )))
466 return FALSE;
468 /* Parse command line arguments */
469 OPTIONS_ParseOptions( !info_size ? argv : NULL );
471 ret = MAIN_MainInit();
472 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
474 return ret;
478 /***********************************************************************
479 * start_process
481 * Startup routine of a new process. Runs on the new process stack.
483 static void start_process(void)
485 int debugged, console_app;
486 LPTHREAD_START_ROUTINE entry;
487 WINE_MODREF *wm;
488 HANDLE main_file = main_exe_file;
489 IMAGE_NT_HEADERS *nt;
491 /* use original argv[0] as name for the main module */
492 if (!main_exe_name[0])
494 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
495 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
498 if (main_file)
500 UINT drive_type = GetDriveTypeA( main_exe_name );
501 /* don't keep the file handle open on removable media */
502 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
505 /* Retrieve entry point address */
506 nt = RtlImageNtHeader( current_process.module );
507 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
508 nt->OptionalHeader.AddressOfEntryPoint);
509 console_app = (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
510 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
512 /* Signal the parent process to continue */
513 SERVER_START_REQ( init_process_done )
515 req->module = (void *)current_process.module;
516 req->module_size = nt->OptionalHeader.SizeOfImage;
517 req->entry = entry;
518 /* API requires a double indirection */
519 req->name = &main_exe_name_ptr;
520 req->exe_file = main_file;
521 req->gui = !console_app;
522 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
523 wine_server_call( req );
524 debugged = reply->debugged;
526 SERVER_END_REQ;
528 /* Install signal handlers; this cannot be done before, since we cannot
529 * send exceptions to the debugger before the create process event that
530 * is sent by REQ_INIT_PROCESS_DONE */
531 if (!SIGNAL_Init()) goto error;
533 /* create the main modref and load dependencies */
534 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
535 goto error;
536 wm->refCount++;
538 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
540 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
542 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
543 * context of the parent process. Actually, the USER signal proc
544 * doesn't really care about that, but it *does* require that the
545 * startup parameters are correctly set up, so that GetProcessDword
546 * works. Furthermore, before calling the USER signal proc the
547 * 16-bit stack must be set up, which it is only after TASK_Create
548 * in the case of a 16-bit process. Thus, we send the signal here.
550 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
551 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
552 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
553 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
554 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
555 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
557 if (TRACE_ON(relay))
558 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
559 GetCurrentThreadId(), main_exe_name, entry );
560 if (debugged) DbgBreakPoint();
561 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
562 * Dunno about other OSs */
563 SetLastError(0); /* clear error code */
564 ExitThread( entry(NULL) );
566 error:
567 ExitProcess( GetLastError() );
571 /***********************************************************************
572 * PROCESS_InitWine
574 * Wine initialisation: load and start the main exe file.
576 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
578 char error[100], *p;
579 DWORD stack_size = 0;
581 /* Initialize everything */
582 if (!process_init( argv )) exit(1);
584 argv++; /* remove argv[0] (wine itself) */
586 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
587 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
589 if (!main_exe_name[0])
591 if (!argv[0]) OPTIONS_Usage();
593 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
595 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
596 ExitProcess(1);
598 if (main_exe_file == INVALID_HANDLE_VALUE)
600 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
601 ExitProcess(1);
605 if (!main_exe_file) /* no file handle -> Winelib app */
607 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
608 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0 ))
609 goto found;
610 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
611 ExitProcess(1);
614 switch( MODULE_GetBinaryType( main_exe_file ))
616 case BINARY_PE_EXE:
617 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
618 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
619 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
620 ExitProcess(1);
621 case BINARY_PE_DLL:
622 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
623 ExitProcess(1);
624 case BINARY_UNKNOWN:
625 /* check for .com extension */
626 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
628 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
629 ExitProcess(1);
631 /* fall through */
632 case BINARY_WIN16:
633 case BINARY_DOS:
634 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
635 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
636 current_process.flags |= PDB32_WIN16_PROC;
637 strcpy( win16_exe_name, main_exe_name );
638 main_exe_name[0] = 0;
639 *win16_exe_file = main_exe_file;
640 main_exe_file = 0;
641 _EnterWin16Lock();
642 goto found;
643 case BINARY_OS216:
644 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
645 ExitProcess(1);
646 case BINARY_UNIX_EXE:
647 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
648 ExitProcess(1);
649 case BINARY_UNIX_LIB:
651 DOS_FULL_NAME full_name;
652 const char *name = main_exe_name;
653 UNICODE_STRING nameW;
655 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
656 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
657 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
658 RtlFreeUnicodeString(&nameW);
659 CloseHandle( main_exe_file );
660 main_exe_file = 0;
661 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
663 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
664 goto found;
666 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
667 ExitProcess(1);
671 found:
672 /* build command line */
673 if (!ENV_BuildCommandLine( argv )) goto error;
675 /* create 32-bit module for main exe */
676 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
677 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
679 /* allocate main thread stack */
680 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
682 /* switch to the new stack */
683 SYSDEPS_SwitchToThreadStack( start_process );
685 error:
686 ExitProcess( GetLastError() );
690 /***********************************************************************
691 * build_argv
693 * Build an argv array from a command-line.
694 * The command-line is modified to insert nulls.
695 * 'reserved' is the number of args to reserve before the first one.
697 static char **build_argv( char *cmdline, int reserved )
699 int argc;
700 char** argv;
701 char *arg,*s,*d;
702 int in_quotes,bcount;
704 argc=reserved+1;
705 bcount=0;
706 in_quotes=0;
707 s=cmdline;
708 while (1) {
709 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
710 /* space */
711 argc++;
712 /* skip the remaining spaces */
713 while (*s==' ' || *s=='\t') {
714 s++;
716 if (*s=='\0')
717 break;
718 bcount=0;
719 continue;
720 } else if (*s=='\\') {
721 /* '\', count them */
722 bcount++;
723 } else if ((*s=='"') && ((bcount & 1)==0)) {
724 /* unescaped '"' */
725 in_quotes=!in_quotes;
726 bcount=0;
727 } else {
728 /* a regular character */
729 bcount=0;
731 s++;
733 argv=malloc(argc*sizeof(*argv));
734 if (!argv)
735 return NULL;
737 arg=d=s=cmdline;
738 bcount=0;
739 in_quotes=0;
740 argc=reserved;
741 while (*s) {
742 if ((*s==' ' || *s=='\t') && !in_quotes) {
743 /* Close the argument and copy it */
744 *d=0;
745 argv[argc++]=arg;
747 /* skip the remaining spaces */
748 do {
749 s++;
750 } while (*s==' ' || *s=='\t');
752 /* Start with a new argument */
753 arg=d=s;
754 bcount=0;
755 } else if (*s=='\\') {
756 /* '\\' */
757 *d++=*s++;
758 bcount++;
759 } else if (*s=='"') {
760 /* '"' */
761 if ((bcount & 1)==0) {
762 /* Preceeded by an even number of '\', this is half that
763 * number of '\', plus a '"' which we discard.
765 d-=bcount/2;
766 s++;
767 in_quotes=!in_quotes;
768 } else {
769 /* Preceeded by an odd number of '\', this is half that
770 * number of '\' followed by a '"'
772 d=d-bcount/2-1;
773 *d++='"';
774 s++;
776 bcount=0;
777 } else {
778 /* a regular character */
779 *d++=*s++;
780 bcount=0;
783 if (*arg) {
784 *d='\0';
785 argv[argc++]=arg;
787 argv[argc]=NULL;
789 return argv;
793 /***********************************************************************
794 * build_envp
796 * Build the environment of a new child process.
798 static char **build_envp( const char *env, const char *extra_env )
800 const char *p;
801 char **envp;
802 int count = 0;
804 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
805 for (p = env; *p; count++) p += strlen(p) + 1;
806 count += 3;
808 if ((envp = malloc( count * sizeof(*envp) )))
810 extern char **environ;
811 char **envptr = envp;
812 char **unixptr = environ;
813 /* first the extra strings */
814 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
815 /* then put PATH, HOME and WINEPREFIX from the unix env */
816 for (unixptr = environ; unixptr && *unixptr; unixptr++)
817 if (!memcmp( *unixptr, "PATH=", 5 ) ||
818 !memcmp( *unixptr, "HOME=", 5 ) ||
819 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
820 /* now put the Windows environment strings */
821 for (p = env; *p; p += strlen(p) + 1)
823 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
825 char *winepath = malloc( strlen(p) + 5 );
826 strcpy( winepath, "WINE" );
827 strcpy( winepath + 4, p );
828 *envptr++ = winepath;
830 else if (memcmp( p, "HOME=", 5 ) &&
831 memcmp( p, "WINEPATH=", 9 ) &&
832 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
834 *envptr = 0;
836 return envp;
840 /***********************************************************************
841 * exec_wine_binary
843 * Locate the Wine binary to exec for a new Win32 process.
845 static void exec_wine_binary( char **argv, char **envp )
847 const char *path, *pos, *ptr;
849 /* first, try for a WINELOADER environment variable */
850 argv[0] = getenv("WINELOADER");
851 if (argv[0])
852 execve( argv[0], argv, envp );
854 /* next, try bin directory */
855 argv[0] = BINDIR "/wine";
856 execve( argv[0], argv, envp );
858 /* now try the path of argv0 of the current binary */
859 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
860 if ((ptr = strrchr( full_argv0, '/' )))
862 memcpy( argv[0], full_argv0, ptr - full_argv0 );
863 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
864 execve( argv[0], argv, envp );
866 free( argv[0] );
868 /* now search in the Unix path */
869 if ((path = getenv( "PATH" )))
871 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
872 pos = path;
873 for (;;)
875 while (*pos == ':') pos++;
876 if (!*pos) break;
877 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
878 memcpy( argv[0], pos, ptr - pos );
879 strcpy( argv[0] + (ptr - pos), "/wine" );
880 execve( argv[0], argv, envp );
881 pos = ptr;
884 free( argv[0] );
888 /***********************************************************************
889 * fork_and_exec
891 * Fork and exec a new Unix process, checking for errors.
893 static int fork_and_exec( const char *filename, char *cmdline,
894 const char *env, const char *newdir )
896 int fd[2];
897 int pid, err;
898 char *extra_env = NULL;
900 if (!env)
902 env = GetEnvironmentStringsA();
903 extra_env = DRIVE_BuildEnv();
906 if (pipe(fd) == -1)
908 FILE_SetDosError();
909 return -1;
911 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
912 if (!(pid = fork())) /* child */
914 char **argv = build_argv( cmdline, filename ? 0 : 1 );
915 char **envp = build_envp( env, extra_env );
916 close( fd[0] );
918 /* Reset signals that we previously set to SIG_IGN */
919 signal( SIGPIPE, SIG_DFL );
920 signal( SIGCHLD, SIG_DFL );
922 if (newdir) chdir(newdir);
924 if (argv && envp)
926 if (!filename) exec_wine_binary( argv, envp );
927 else execve( filename, argv, envp );
929 err = errno;
930 write( fd[1], &err, sizeof(err) );
931 _exit(1);
933 close( fd[1] );
934 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
936 errno = err;
937 pid = -1;
939 if (pid == -1) FILE_SetDosError();
940 close( fd[0] );
941 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
942 return pid;
946 /***********************************************************************
947 * create_process
949 * Create a new process. If hFile is a valid handle we have an exe
950 * file, otherwise it is a Winelib app.
952 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
953 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
954 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
955 LPPROCESS_INFORMATION info, LPCSTR unixdir )
957 BOOL ret, success = FALSE;
958 HANDLE process_info;
959 startup_info_t startup_info;
961 /* fill the startup info structure */
963 startup_info.size = sizeof(startup_info);
964 /* startup_info.filename_len is set below */
965 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
966 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
967 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
968 startup_info.x = startup->dwX;
969 startup_info.y = startup->dwY;
970 startup_info.cx = startup->dwXSize;
971 startup_info.cy = startup->dwYSize;
972 startup_info.x_chars = startup->dwXCountChars;
973 startup_info.y_chars = startup->dwYCountChars;
974 startup_info.attribute = startup->dwFillAttribute;
975 startup_info.cmd_show = startup->wShowWindow;
976 startup_info.flags = startup->dwFlags;
978 /* create the process on the server side */
980 SERVER_START_REQ( new_process )
982 char buf[MAX_PATH];
983 LPCSTR nameptr;
985 req->inherit_all = inherit;
986 req->create_flags = flags;
987 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
988 req->exe_file = hFile;
989 if (startup->dwFlags & STARTF_USESTDHANDLES)
991 req->hstdin = startup->hStdInput;
992 req->hstdout = startup->hStdOutput;
993 req->hstderr = startup->hStdError;
995 else
997 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
998 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
999 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1002 if (GetLongPathNameA( filename, buf, MAX_PATH ))
1003 nameptr = buf;
1004 else
1005 nameptr = filename;
1007 startup_info.filename_len = strlen(nameptr);
1008 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
1009 wine_server_add_data( req, nameptr, startup_info.filename_len );
1010 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
1011 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
1012 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
1014 ret = !wine_server_call_err( req );
1015 process_info = reply->info;
1017 SERVER_END_REQ;
1018 if (!ret) return FALSE;
1020 /* fork and execute */
1022 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
1024 CloseHandle( process_info );
1025 return FALSE;
1028 /* wait for the new process info to be ready */
1030 WaitForSingleObject( process_info, INFINITE );
1031 SERVER_START_REQ( get_new_process_info )
1033 req->info = process_info;
1034 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1035 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1036 if ((ret = !wine_server_call_err( req )))
1038 info->dwProcessId = (DWORD)reply->pid;
1039 info->dwThreadId = (DWORD)reply->tid;
1040 info->hProcess = reply->phandle;
1041 info->hThread = reply->thandle;
1042 success = reply->success;
1045 SERVER_END_REQ;
1047 if (ret && !success) /* new process failed to start */
1049 DWORD exitcode;
1050 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1051 CloseHandle( info->hThread );
1052 CloseHandle( info->hProcess );
1053 ret = FALSE;
1055 CloseHandle( process_info );
1056 return ret;
1060 /*************************************************************************
1061 * get_file_name
1063 * Helper for CreateProcess: retrieve the file name to load from the
1064 * app name and command line. Store the file name in buffer, and
1065 * return a possibly modified command line.
1066 * Also returns a handle to the opened file if it's a Windows binary.
1068 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1069 int buflen, HANDLE *handle )
1071 char *name, *pos, *ret = NULL;
1072 const char *p;
1074 /* if we have an app name, everything is easy */
1076 if (appname)
1078 /* use the unmodified app name as file name */
1079 lstrcpynA( buffer, appname, buflen );
1080 *handle = open_exe_file( buffer );
1081 if (!(ret = cmdline) || !cmdline[0])
1083 /* no command-line, create one */
1084 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1085 sprintf( ret, "\"%s\"", appname );
1087 return ret;
1090 if (!cmdline)
1092 SetLastError( ERROR_INVALID_PARAMETER );
1093 return NULL;
1096 /* first check for a quoted file name */
1098 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1100 int len = p - cmdline - 1;
1101 /* extract the quoted portion as file name */
1102 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1103 memcpy( name, cmdline + 1, len );
1104 name[len] = 0;
1106 if (find_exe_file( name, buffer, buflen, handle ))
1107 ret = cmdline; /* no change necessary */
1108 goto done;
1111 /* now try the command-line word by word */
1113 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1114 pos = name;
1115 p = cmdline;
1117 while (*p)
1119 do *pos++ = *p++; while (*p && *p != ' ');
1120 *pos = 0;
1121 if (find_exe_file( name, buffer, buflen, handle ))
1123 ret = cmdline;
1124 break;
1128 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1130 /* now build a new command-line with quotes */
1132 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1133 sprintf( ret, "\"%s\"%s", name, p );
1135 done:
1136 HeapFree( GetProcessHeap(), 0, name );
1137 return ret;
1141 /**********************************************************************
1142 * CreateProcessA (KERNEL32.@)
1144 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1145 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1146 DWORD flags, LPVOID env, LPCSTR cur_dir,
1147 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1149 BOOL retv = FALSE;
1150 HANDLE hFile = 0;
1151 const char *unixdir = NULL;
1152 DOS_FULL_NAME full_dir;
1153 char name[MAX_PATH];
1154 LPSTR tidy_cmdline;
1155 char *p;
1157 /* Process the AppName and/or CmdLine to get module name and path */
1159 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1161 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1162 return FALSE;
1163 if (hFile == INVALID_HANDLE_VALUE) goto done;
1165 /* Warn if unsupported features are used */
1167 if (flags & NORMAL_PRIORITY_CLASS)
1168 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1169 if (flags & IDLE_PRIORITY_CLASS)
1170 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1171 if (flags & HIGH_PRIORITY_CLASS)
1172 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1173 if (flags & REALTIME_PRIORITY_CLASS)
1174 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1175 if (flags & CREATE_NEW_PROCESS_GROUP)
1176 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1177 if (flags & CREATE_UNICODE_ENVIRONMENT)
1178 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1179 if (flags & CREATE_SEPARATE_WOW_VDM)
1180 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1181 if (flags & CREATE_SHARED_WOW_VDM)
1182 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1183 if (flags & CREATE_DEFAULT_ERROR_MODE)
1184 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1185 if (flags & CREATE_NO_WINDOW)
1186 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1187 if (flags & PROFILE_USER)
1188 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1189 if (flags & PROFILE_KERNEL)
1190 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1191 if (flags & PROFILE_SERVER)
1192 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1193 if (startup_info->lpDesktop)
1194 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1195 name, debugstr_a(startup_info->lpDesktop));
1196 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1197 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1198 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1199 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1200 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1201 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1202 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1203 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1205 if (cur_dir)
1207 UNICODE_STRING cur_dirW;
1208 RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1209 if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1210 unixdir = full_dir.long_name;
1211 RtlFreeUnicodeString(&cur_dirW);
1213 else
1215 WCHAR buf[MAX_PATH];
1216 if (GetCurrentDirectoryW(MAX_PATH, buf))
1218 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1222 info->hThread = info->hProcess = 0;
1223 info->dwProcessId = info->dwThreadId = 0;
1225 /* Determine executable type */
1227 if (!hFile) /* builtin exe */
1229 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1230 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1231 inherit, flags, startup_info, info, unixdir );
1232 goto done;
1235 switch( MODULE_GetBinaryType( hFile ))
1237 case BINARY_PE_EXE:
1238 case BINARY_WIN16:
1239 case BINARY_DOS:
1240 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1241 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1242 inherit, flags, startup_info, info, unixdir );
1243 break;
1244 case BINARY_OS216:
1245 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1246 SetLastError( ERROR_BAD_EXE_FORMAT );
1247 break;
1248 case BINARY_PE_DLL:
1249 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1250 SetLastError( ERROR_BAD_EXE_FORMAT );
1251 break;
1252 case BINARY_UNIX_LIB:
1253 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1254 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1255 inherit, flags, startup_info, info, unixdir );
1256 break;
1257 case BINARY_UNKNOWN:
1258 /* check for .com or .bat extension */
1259 if ((p = strrchr( name, '.' )))
1261 if (!FILE_strcasecmp( p, ".com" ))
1263 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1264 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1265 inherit, flags, startup_info, info, unixdir );
1266 break;
1268 if (!FILE_strcasecmp( p, ".bat" ))
1270 char comspec[MAX_PATH];
1271 if (GetEnvironmentVariableA("COMSPEC", comspec, sizeof(comspec)))
1273 char *newcmdline, *q = strchr(cmd_line, ' ');
1274 if (!q) q = "";
1275 if ((newcmdline = HeapAlloc( GetProcessHeap(), 0,
1276 strlen(comspec) + strlen(name) + strlen(q) + 8)))
1278 sprintf( newcmdline, "%s /c %s%s", comspec, name, q );
1279 TRACE( "starting %s as batch binary: %s\n",
1280 debugstr_a(name), debugstr_a(newcmdline) );
1281 retv = CreateProcessA( comspec, newcmdline, process_attr, thread_attr,
1282 inherit, flags, env, cur_dir, startup_info, info );
1283 HeapFree( GetProcessHeap(), 0, newcmdline );
1284 break;
1289 /* fall through */
1290 case BINARY_UNIX_EXE:
1292 /* unknown file, try as unix executable */
1293 UNICODE_STRING nameW;
1294 DOS_FULL_NAME full_name;
1295 const char *unixfilename = name;
1297 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1299 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1300 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1301 RtlFreeUnicodeString(&nameW);
1302 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1304 break;
1306 CloseHandle( hFile );
1308 done:
1309 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1310 return retv;
1314 /**********************************************************************
1315 * CreateProcessW (KERNEL32.@)
1316 * NOTES
1317 * lpReserved is not converted
1319 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1320 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1321 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1322 LPPROCESS_INFORMATION info )
1324 BOOL ret;
1325 STARTUPINFOA StartupInfoA;
1327 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1328 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1329 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1331 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1332 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1333 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1335 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1337 if (startup_info->lpReserved)
1338 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1339 debugstr_w(startup_info->lpReserved));
1341 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1342 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1344 HeapFree( GetProcessHeap(), 0, cur_dirA );
1345 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1346 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1347 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1349 return ret;
1353 /***********************************************************************
1354 * ExitProcess (KERNEL32.@)
1356 void WINAPI ExitProcess( DWORD status )
1358 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1359 SERVER_START_REQ( terminate_process )
1361 /* send the exit code to the server */
1362 req->handle = GetCurrentProcess();
1363 req->exit_code = status;
1364 wine_server_call( req );
1366 SERVER_END_REQ;
1367 exit( status );
1370 /***********************************************************************
1371 * ExitProcess (KERNEL.466)
1373 void WINAPI ExitProcess16( WORD status )
1375 DWORD count;
1376 ReleaseThunkLock( &count );
1377 ExitProcess( status );
1380 /******************************************************************************
1381 * TerminateProcess (KERNEL32.@)
1383 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1385 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1386 if (status) SetLastError( RtlNtStatusToDosError(status) );
1387 return !status;
1391 /***********************************************************************
1392 * GetProcessDword (KERNEL.485)
1393 * GetProcessDword (KERNEL32.18)
1394 * 'Of course you cannot directly access Windows internal structures'
1396 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1398 DWORD x, y;
1400 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1402 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1404 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1405 return 0;
1408 switch ( offset )
1410 case GPD_APP_COMPAT_FLAGS:
1411 return GetAppCompatFlags16(0);
1413 case GPD_LOAD_DONE_EVENT:
1414 return (DWORD)current_process.load_done_evt;
1416 case GPD_HINSTANCE16:
1417 return GetTaskDS16();
1419 case GPD_WINDOWS_VERSION:
1420 return GetExeVersion16();
1422 case GPD_THDB:
1423 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1425 case GPD_PDB:
1426 return (DWORD)&current_process;
1428 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1429 return (DWORD)current_startupinfo.hStdOutput;
1431 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1432 return (DWORD)current_startupinfo.hStdInput;
1434 case GPD_STARTF_SHOWWINDOW:
1435 return current_startupinfo.wShowWindow;
1437 case GPD_STARTF_SIZE:
1438 x = current_startupinfo.dwXSize;
1439 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1440 y = current_startupinfo.dwYSize;
1441 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1442 return MAKELONG( x, y );
1444 case GPD_STARTF_POSITION:
1445 x = current_startupinfo.dwX;
1446 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1447 y = current_startupinfo.dwY;
1448 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1449 return MAKELONG( x, y );
1451 case GPD_STARTF_FLAGS:
1452 return current_startupinfo.dwFlags;
1454 case GPD_PARENT:
1455 return 0;
1457 case GPD_FLAGS:
1458 return current_process.flags;
1460 case GPD_USERDATA:
1461 return current_process.process_dword;
1463 default:
1464 ERR_(win32)("Unknown offset %d\n", offset );
1465 return 0;
1469 /***********************************************************************
1470 * SetProcessDword (KERNEL.484)
1471 * 'Of course you cannot directly access Windows internal structures'
1473 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1475 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1477 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1479 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1480 return;
1483 switch ( offset )
1485 case GPD_APP_COMPAT_FLAGS:
1486 case GPD_LOAD_DONE_EVENT:
1487 case GPD_HINSTANCE16:
1488 case GPD_WINDOWS_VERSION:
1489 case GPD_THDB:
1490 case GPD_PDB:
1491 case GPD_STARTF_SHELLDATA:
1492 case GPD_STARTF_HOTKEY:
1493 case GPD_STARTF_SHOWWINDOW:
1494 case GPD_STARTF_SIZE:
1495 case GPD_STARTF_POSITION:
1496 case GPD_STARTF_FLAGS:
1497 case GPD_PARENT:
1498 case GPD_FLAGS:
1499 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1500 break;
1502 case GPD_USERDATA:
1503 current_process.process_dword = value;
1504 break;
1506 default:
1507 ERR_(win32)("Unknown offset %d\n", offset );
1508 break;
1513 /*********************************************************************
1514 * OpenProcess (KERNEL32.@)
1516 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1518 HANDLE ret = 0;
1519 SERVER_START_REQ( open_process )
1521 req->pid = id;
1522 req->access = access;
1523 req->inherit = inherit;
1524 if (!wine_server_call_err( req )) ret = reply->handle;
1526 SERVER_END_REQ;
1527 return ret;
1530 /*********************************************************************
1531 * MapProcessHandle (KERNEL.483)
1533 DWORD WINAPI MapProcessHandle( HANDLE handle )
1535 DWORD ret = 0;
1536 SERVER_START_REQ( get_process_info )
1538 req->handle = handle;
1539 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1541 SERVER_END_REQ;
1542 return ret;
1545 /***********************************************************************
1546 * SetPriorityClass (KERNEL32.@)
1548 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1550 BOOL ret;
1551 SERVER_START_REQ( set_process_info )
1553 req->handle = hprocess;
1554 req->priority = priorityclass;
1555 req->mask = SET_PROCESS_INFO_PRIORITY;
1556 ret = !wine_server_call_err( req );
1558 SERVER_END_REQ;
1559 return ret;
1563 /***********************************************************************
1564 * GetPriorityClass (KERNEL32.@)
1566 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1568 DWORD ret = 0;
1569 SERVER_START_REQ( get_process_info )
1571 req->handle = hprocess;
1572 if (!wine_server_call_err( req )) ret = reply->priority;
1574 SERVER_END_REQ;
1575 return ret;
1579 /***********************************************************************
1580 * SetProcessAffinityMask (KERNEL32.@)
1582 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1584 BOOL ret;
1585 SERVER_START_REQ( set_process_info )
1587 req->handle = hProcess;
1588 req->affinity = affmask;
1589 req->mask = SET_PROCESS_INFO_AFFINITY;
1590 ret = !wine_server_call_err( req );
1592 SERVER_END_REQ;
1593 return ret;
1596 /**********************************************************************
1597 * GetProcessAffinityMask (KERNEL32.@)
1599 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1600 LPDWORD lpProcessAffinityMask,
1601 LPDWORD lpSystemAffinityMask )
1603 BOOL ret = FALSE;
1604 SERVER_START_REQ( get_process_info )
1606 req->handle = hProcess;
1607 if (!wine_server_call_err( req ))
1609 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1610 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1611 ret = TRUE;
1614 SERVER_END_REQ;
1615 return ret;
1619 /***********************************************************************
1620 * GetProcessVersion (KERNEL32.@)
1622 DWORD WINAPI GetProcessVersion( DWORD processid )
1624 IMAGE_NT_HEADERS *nt;
1626 if (processid && processid != GetCurrentProcessId())
1628 FIXME("should use ReadProcessMemory\n");
1629 return 0;
1631 if ((nt = RtlImageNtHeader( current_process.module )))
1632 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1633 nt->OptionalHeader.MinorSubsystemVersion);
1634 return 0;
1637 /***********************************************************************
1638 * GetProcessFlags (KERNEL32.@)
1640 DWORD WINAPI GetProcessFlags( DWORD processid )
1642 if (processid && processid != GetCurrentProcessId()) return 0;
1643 return current_process.flags;
1647 /***********************************************************************
1648 * SetProcessWorkingSetSize [KERNEL32.@]
1649 * Sets the min/max working set sizes for a specified process.
1651 * PARAMS
1652 * hProcess [I] Handle to the process of interest
1653 * minset [I] Specifies minimum working set size
1654 * maxset [I] Specifies maximum working set size
1656 * RETURNS STD
1658 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
1659 SIZE_T maxset)
1661 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1662 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
1663 /* Trim the working set to zero */
1664 /* Swap the process out of physical RAM */
1666 return TRUE;
1669 /***********************************************************************
1670 * GetProcessWorkingSetSize (KERNEL32.@)
1672 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
1673 PSIZE_T maxset)
1675 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
1676 /* 32 MB working set size */
1677 if (minset) *minset = 32*1024*1024;
1678 if (maxset) *maxset = 32*1024*1024;
1679 return TRUE;
1682 /***********************************************************************
1683 * SetProcessShutdownParameters (KERNEL32.@)
1685 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1686 * Now tracks changes made (but does not act on these changes)
1688 static DWORD shutdown_flags = 0;
1689 static DWORD shutdown_priority = 0x280;
1691 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1693 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1694 shutdown_flags = flags;
1695 shutdown_priority = level;
1696 return TRUE;
1700 /***********************************************************************
1701 * GetProcessShutdownParameters (KERNEL32.@)
1704 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1706 *lpdwLevel = shutdown_priority;
1707 *lpdwFlags = shutdown_flags;
1708 return TRUE;
1712 /***********************************************************************
1713 * SetProcessPriorityBoost (KERNEL32.@)
1715 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1717 FIXME("(%p,%d): stub\n",hprocess,disableboost);
1718 /* Say we can do it. I doubt the program will notice that we don't. */
1719 return TRUE;
1723 /***********************************************************************
1724 * ReadProcessMemory (KERNEL32.@)
1726 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
1727 SIZE_T *bytes_read )
1729 DWORD res;
1731 SERVER_START_REQ( read_process_memory )
1733 req->handle = process;
1734 req->addr = (void *)addr;
1735 wine_server_set_reply( req, buffer, size );
1736 if ((res = wine_server_call_err( req ))) size = 0;
1738 SERVER_END_REQ;
1739 if (bytes_read) *bytes_read = size;
1740 return !res;
1744 /***********************************************************************
1745 * WriteProcessMemory (KERNEL32.@)
1747 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
1748 SIZE_T *bytes_written )
1750 static const int zero;
1751 unsigned int first_offset, last_offset, first_mask, last_mask;
1752 DWORD res;
1754 if (!size)
1756 SetLastError( ERROR_INVALID_PARAMETER );
1757 return FALSE;
1760 /* compute the mask for the first int */
1761 first_mask = ~0;
1762 first_offset = (unsigned int)addr % sizeof(int);
1763 memset( &first_mask, 0, first_offset );
1765 /* compute the mask for the last int */
1766 last_offset = (size + first_offset) % sizeof(int);
1767 last_mask = 0;
1768 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1770 SERVER_START_REQ( write_process_memory )
1772 req->handle = process;
1773 req->addr = (char *)addr - first_offset;
1774 req->first_mask = first_mask;
1775 req->last_mask = last_mask;
1776 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1777 wine_server_add_data( req, buffer, size );
1778 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1780 if ((res = wine_server_call_err( req ))) size = 0;
1782 SERVER_END_REQ;
1783 if (bytes_written) *bytes_written = size;
1785 char dummy[32];
1786 SIZE_T read;
1787 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1789 return !res;
1793 /***********************************************************************
1794 * RegisterServiceProcess (KERNEL.491)
1795 * RegisterServiceProcess (KERNEL32.@)
1797 * A service process calls this function to ensure that it continues to run
1798 * even after a user logged off.
1800 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1802 /* I don't think that Wine needs to do anything in that function */
1803 return 1; /* success */
1806 /***********************************************************************
1807 * GetExitCodeProcess [KERNEL32.@]
1809 * Gets termination status of specified process
1811 * RETURNS
1812 * Success: TRUE
1813 * Failure: FALSE
1815 BOOL WINAPI GetExitCodeProcess(
1816 HANDLE hProcess, /* [in] handle to the process */
1817 LPDWORD lpExitCode) /* [out] address to receive termination status */
1819 BOOL ret;
1820 SERVER_START_REQ( get_process_info )
1822 req->handle = hProcess;
1823 ret = !wine_server_call_err( req );
1824 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1826 SERVER_END_REQ;
1827 return ret;
1831 /***********************************************************************
1832 * SetErrorMode (KERNEL32.@)
1834 UINT WINAPI SetErrorMode( UINT mode )
1836 UINT old = current_process.error_mode;
1837 current_process.error_mode = mode;
1838 return old;
1842 /**************************************************************************
1843 * SetFileApisToOEM (KERNEL32.@)
1845 VOID WINAPI SetFileApisToOEM(void)
1847 current_process.flags |= PDB32_FILE_APIS_OEM;
1851 /**************************************************************************
1852 * SetFileApisToANSI (KERNEL32.@)
1854 VOID WINAPI SetFileApisToANSI(void)
1856 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1860 /******************************************************************************
1861 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1863 * RETURNS
1864 * TRUE: Set of file functions is using ANSI code page
1865 * FALSE: Set of file functions is using OEM code page
1867 BOOL WINAPI AreFileApisANSI(void)
1869 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1873 /***********************************************************************
1874 * GetTickCount (KERNEL32.@)
1876 * Returns the number of milliseconds, modulo 2^32, since the start
1877 * of the wineserver.
1879 DWORD WINAPI GetTickCount(void)
1881 struct timeval t;
1882 gettimeofday( &t, NULL );
1883 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1887 /**********************************************************************
1888 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1890 * Allocates a thread local storage index
1892 * RETURNS
1893 * Success: TLS Index
1894 * Failure: 0xFFFFFFFF
1896 DWORD WINAPI TlsAlloc( void )
1898 DWORD i, mask, ret = 0;
1899 DWORD *bits = current_process.tls_bits;
1900 RtlAcquirePebLock();
1901 if (*bits == 0xffffffff)
1903 bits++;
1904 ret = 32;
1905 if (*bits == 0xffffffff)
1907 RtlReleasePebLock();
1908 SetLastError( ERROR_NO_MORE_ITEMS );
1909 return 0xffffffff;
1912 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1913 *bits |= mask;
1914 RtlReleasePebLock();
1915 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1916 return ret + i;
1920 /**********************************************************************
1921 * TlsFree [KERNEL32.@] Releases a TLS index.
1923 * Releases a thread local storage index, making it available for reuse
1925 * RETURNS
1926 * Success: TRUE
1927 * Failure: FALSE
1929 BOOL WINAPI TlsFree(
1930 DWORD index) /* [in] TLS Index to free */
1932 DWORD mask = (1 << (index & 31));
1933 DWORD *bits = current_process.tls_bits;
1934 if (index >= 64)
1936 SetLastError( ERROR_INVALID_PARAMETER );
1937 return FALSE;
1939 if (index >= 32) bits++;
1940 RtlAcquirePebLock();
1941 if (!(*bits & mask)) /* already free? */
1943 RtlReleasePebLock();
1944 SetLastError( ERROR_INVALID_PARAMETER );
1945 return FALSE;
1947 *bits &= ~mask;
1948 NtCurrentTeb()->tls_array[index] = 0;
1949 /* FIXME: should zero all other thread values */
1950 RtlReleasePebLock();
1951 return TRUE;
1955 /**********************************************************************
1956 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1958 * RETURNS
1959 * Success: Value stored in calling thread's TLS slot for index
1960 * Failure: 0 and GetLastError returns NO_ERROR
1962 LPVOID WINAPI TlsGetValue(
1963 DWORD index) /* [in] TLS index to retrieve value for */
1965 if (index >= 64)
1967 SetLastError( ERROR_INVALID_PARAMETER );
1968 return NULL;
1970 SetLastError( ERROR_SUCCESS );
1971 return NtCurrentTeb()->tls_array[index];
1975 /**********************************************************************
1976 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1978 * RETURNS
1979 * Success: TRUE
1980 * Failure: FALSE
1982 BOOL WINAPI TlsSetValue(
1983 DWORD index, /* [in] TLS index to set value for */
1984 LPVOID value) /* [in] Value to be stored */
1986 if (index >= 64)
1988 SetLastError( ERROR_INVALID_PARAMETER );
1989 return FALSE;
1991 NtCurrentTeb()->tls_array[index] = value;
1992 return TRUE;
1996 /***********************************************************************
1997 * GetCurrentProcess (KERNEL32.@)
1999 #undef GetCurrentProcess
2000 HANDLE WINAPI GetCurrentProcess(void)
2002 return (HANDLE)0xffffffff;