Add few SFGAO_CAN* attributes to supported list.
[wine/hacks.git] / scheduler / process.c
blobea9a3056bf45ac030e08d434421e83a0a731f418
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 if ((ret = !wine_server_call_err( req )))
421 main_exe_file = reply->exe_file;
422 main_create_flags = reply->create_flags;
423 info_size = reply->info_size;
424 server_startticks = reply->server_start;
425 current_startupinfo.hStdInput = reply->hstdin;
426 current_startupinfo.hStdOutput = reply->hstdout;
427 current_startupinfo.hStdError = reply->hstderr;
430 SERVER_END_REQ;
431 if (!ret) return FALSE;
433 /* Create the process heap */
434 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
436 if (main_create_flags == 0 &&
437 current_startupinfo.hStdInput == 0 &&
438 current_startupinfo.hStdOutput == 0 &&
439 current_startupinfo.hStdError == 0)
441 /* no parent, and no new console requested, create a simple console with bare handles to
442 * unix stdio input & output streams (aka simple console)
444 HANDLE handle;
445 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &handle );
446 SetStdHandle( STD_INPUT_HANDLE, handle );
447 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
448 SetStdHandle( STD_OUTPUT_HANDLE, handle );
449 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
450 SetStdHandle( STD_ERROR_HANDLE, handle );
452 else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
454 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
455 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
456 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
459 /* Now we can use the pthreads routines */
460 PTHREAD_init_done();
462 /* Copy the parent environment */
463 if (!(current_process.env_db = ENV_InitStartupInfo( info_size, main_exe_name,
464 sizeof(main_exe_name) )))
465 return FALSE;
467 /* Parse command line arguments */
468 OPTIONS_ParseOptions( !info_size ? argv : NULL );
470 ret = MAIN_MainInit();
471 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
473 return ret;
477 /***********************************************************************
478 * start_process
480 * Startup routine of a new process. Runs on the new process stack.
482 static void start_process(void)
484 int debugged, console_app;
485 LPTHREAD_START_ROUTINE entry;
486 WINE_MODREF *wm;
487 HANDLE main_file = main_exe_file;
488 IMAGE_NT_HEADERS *nt;
490 /* use original argv[0] as name for the main module */
491 if (!main_exe_name[0])
493 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
494 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
497 if (main_file)
499 UINT drive_type = GetDriveTypeA( main_exe_name );
500 /* don't keep the file handle open on removable media */
501 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
504 /* Retrieve entry point address */
505 nt = RtlImageNtHeader( current_process.module );
506 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
507 nt->OptionalHeader.AddressOfEntryPoint);
508 console_app = (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
509 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
511 /* Install signal handlers; this cannot be done before, since we cannot
512 * send exceptions to the debugger before the create process event that
513 * is sent by REQ_INIT_PROCESS_DONE.
514 * We do need the handlers in place by the time the request is over, so
515 * we set them up here. If we segfault between here and the server call
516 * something is very wrong... */
517 if (!SIGNAL_Init()) goto error;
519 /* Signal the parent process to continue */
520 SERVER_START_REQ( init_process_done )
522 req->module = (void *)current_process.module;
523 req->module_size = nt->OptionalHeader.SizeOfImage;
524 req->entry = entry;
525 /* API requires a double indirection */
526 req->name = &main_exe_name_ptr;
527 req->exe_file = main_file;
528 req->gui = !console_app;
529 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
530 wine_server_call( req );
531 debugged = reply->debugged;
533 SERVER_END_REQ;
535 /* create the main modref and load dependencies */
536 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
537 goto error;
538 wm->refCount++;
540 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
542 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
544 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
545 * context of the parent process. Actually, the USER signal proc
546 * doesn't really care about that, but it *does* require that the
547 * startup parameters are correctly set up, so that GetProcessDword
548 * works. Furthermore, before calling the USER signal proc the
549 * 16-bit stack must be set up, which it is only after TASK_Create
550 * in the case of a 16-bit process. Thus, we send the signal here.
552 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
553 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
554 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
555 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
556 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
557 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
559 if (TRACE_ON(relay))
560 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n",
561 GetCurrentThreadId(), main_exe_name, entry );
562 if (debugged) DbgBreakPoint();
563 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
564 * Dunno about other OSs */
565 SetLastError(0); /* clear error code */
566 ExitThread( entry(NULL) );
568 error:
569 ExitProcess( GetLastError() );
573 /***********************************************************************
574 * PROCESS_InitWine
576 * Wine initialisation: load and start the main exe file.
578 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
580 char error[1024], *p;
581 DWORD stack_size = 0;
583 /* Initialize everything */
584 if (!process_init( argv )) exit(1);
586 argv++; /* remove argv[0] (wine itself) */
588 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
589 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
591 if (!main_exe_name[0])
593 if (!argv[0]) OPTIONS_Usage();
595 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
597 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
598 ExitProcess(1);
600 if (main_exe_file == INVALID_HANDLE_VALUE)
602 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
603 ExitProcess(1);
607 if (!main_exe_file) /* no file handle -> Winelib app */
609 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
610 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0 ))
611 goto found;
612 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
613 ExitProcess(1);
616 switch( MODULE_GetBinaryType( main_exe_file ))
618 case BINARY_PE_EXE:
619 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
620 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
621 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
622 ExitProcess(1);
623 case BINARY_PE_DLL:
624 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
625 ExitProcess(1);
626 case BINARY_UNKNOWN:
627 /* check for .com extension */
628 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
630 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
631 ExitProcess(1);
633 /* fall through */
634 case BINARY_WIN16:
635 case BINARY_DOS:
636 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
637 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
638 current_process.flags |= PDB32_WIN16_PROC;
639 strcpy( win16_exe_name, main_exe_name );
640 main_exe_name[0] = 0;
641 *win16_exe_file = main_exe_file;
642 main_exe_file = 0;
643 _EnterWin16Lock();
644 goto found;
645 case BINARY_OS216:
646 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
647 ExitProcess(1);
648 case BINARY_UNIX_EXE:
649 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
650 ExitProcess(1);
651 case BINARY_UNIX_LIB:
653 DOS_FULL_NAME full_name;
654 const char *name = main_exe_name;
655 UNICODE_STRING nameW;
657 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
658 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
659 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
660 RtlFreeUnicodeString(&nameW);
661 CloseHandle( main_exe_file );
662 main_exe_file = 0;
663 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
665 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
666 goto found;
668 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
669 ExitProcess(1);
673 found:
674 /* build command line */
675 if (!ENV_BuildCommandLine( argv )) goto error;
677 /* create 32-bit module for main exe */
678 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
679 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
681 /* allocate main thread stack */
682 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
684 /* switch to the new stack */
685 SYSDEPS_SwitchToThreadStack( start_process );
687 error:
688 ExitProcess( GetLastError() );
692 /***********************************************************************
693 * build_argv
695 * Build an argv array from a command-line.
696 * The command-line is modified to insert nulls.
697 * 'reserved' is the number of args to reserve before the first one.
699 static char **build_argv( char *cmdline, int reserved )
701 int argc;
702 char** argv;
703 char *arg,*s,*d;
704 int in_quotes,bcount;
706 argc=reserved+1;
707 bcount=0;
708 in_quotes=0;
709 s=cmdline;
710 while (1) {
711 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
712 /* space */
713 argc++;
714 /* skip the remaining spaces */
715 while (*s==' ' || *s=='\t') {
716 s++;
718 if (*s=='\0')
719 break;
720 bcount=0;
721 continue;
722 } else if (*s=='\\') {
723 /* '\', count them */
724 bcount++;
725 } else if ((*s=='"') && ((bcount & 1)==0)) {
726 /* unescaped '"' */
727 in_quotes=!in_quotes;
728 bcount=0;
729 } else {
730 /* a regular character */
731 bcount=0;
733 s++;
735 argv=malloc(argc*sizeof(*argv));
736 if (!argv)
737 return NULL;
739 arg=d=s=cmdline;
740 bcount=0;
741 in_quotes=0;
742 argc=reserved;
743 while (*s) {
744 if ((*s==' ' || *s=='\t') && !in_quotes) {
745 /* Close the argument and copy it */
746 *d=0;
747 argv[argc++]=arg;
749 /* skip the remaining spaces */
750 do {
751 s++;
752 } while (*s==' ' || *s=='\t');
754 /* Start with a new argument */
755 arg=d=s;
756 bcount=0;
757 } else if (*s=='\\') {
758 /* '\\' */
759 *d++=*s++;
760 bcount++;
761 } else if (*s=='"') {
762 /* '"' */
763 if ((bcount & 1)==0) {
764 /* Preceeded by an even number of '\', this is half that
765 * number of '\', plus a '"' which we discard.
767 d-=bcount/2;
768 s++;
769 in_quotes=!in_quotes;
770 } else {
771 /* Preceeded by an odd number of '\', this is half that
772 * number of '\' followed by a '"'
774 d=d-bcount/2-1;
775 *d++='"';
776 s++;
778 bcount=0;
779 } else {
780 /* a regular character */
781 *d++=*s++;
782 bcount=0;
785 if (*arg) {
786 *d='\0';
787 argv[argc++]=arg;
789 argv[argc]=NULL;
791 return argv;
795 /***********************************************************************
796 * build_envp
798 * Build the environment of a new child process.
800 static char **build_envp( const char *env, const char *extra_env )
802 const char *p;
803 char **envp;
804 int count = 0;
806 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
807 for (p = env; *p; count++) p += strlen(p) + 1;
808 count += 3;
810 if ((envp = malloc( count * sizeof(*envp) )))
812 extern char **environ;
813 char **envptr = envp;
814 char **unixptr = environ;
815 /* first the extra strings */
816 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
817 /* then put PATH, HOME and WINEPREFIX from the unix env */
818 for (unixptr = environ; unixptr && *unixptr; unixptr++)
819 if (!memcmp( *unixptr, "PATH=", 5 ) ||
820 !memcmp( *unixptr, "HOME=", 5 ) ||
821 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
822 /* now put the Windows environment strings */
823 for (p = env; *p; p += strlen(p) + 1)
825 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
827 char *winepath = malloc( strlen(p) + 5 );
828 strcpy( winepath, "WINE" );
829 strcpy( winepath + 4, p );
830 *envptr++ = winepath;
832 else if (memcmp( p, "HOME=", 5 ) &&
833 memcmp( p, "WINEPATH=", 9 ) &&
834 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
836 *envptr = 0;
838 return envp;
842 /***********************************************************************
843 * exec_wine_binary
845 * Locate the Wine binary to exec for a new Win32 process.
847 static void exec_wine_binary( char **argv, char **envp )
849 const char *path, *pos, *ptr;
851 /* first, try for a WINELOADER environment variable */
852 argv[0] = getenv("WINELOADER");
853 if (argv[0])
854 execve( argv[0], argv, envp );
856 /* next, try bin directory */
857 argv[0] = BINDIR "/wine";
858 execve( argv[0], argv, envp );
860 /* now try the path of argv0 of the current binary */
861 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
862 if ((ptr = strrchr( full_argv0, '/' )))
864 memcpy( argv[0], full_argv0, ptr - full_argv0 );
865 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
866 execve( argv[0], argv, envp );
868 free( argv[0] );
870 /* now search in the Unix path */
871 if ((path = getenv( "PATH" )))
873 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
874 pos = path;
875 for (;;)
877 while (*pos == ':') pos++;
878 if (!*pos) break;
879 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
880 memcpy( argv[0], pos, ptr - pos );
881 strcpy( argv[0] + (ptr - pos), "/wine" );
882 execve( argv[0], argv, envp );
883 pos = ptr;
886 free( argv[0] );
890 /***********************************************************************
891 * fork_and_exec
893 * Fork and exec a new Unix binary, checking for errors.
895 static int fork_and_exec( const char *filename, char *cmdline,
896 const char *env, const char *newdir )
898 int fd[2];
899 int pid, err;
901 if (!env) env = GetEnvironmentStringsA();
903 if (pipe(fd) == -1)
905 FILE_SetDosError();
906 return -1;
908 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
909 if (!(pid = fork())) /* child */
911 char **argv = build_argv( cmdline, 0 );
912 char **envp = build_envp( env, NULL );
913 close( fd[0] );
915 /* Reset signals that we previously set to SIG_IGN */
916 signal( SIGPIPE, SIG_DFL );
917 signal( SIGCHLD, SIG_DFL );
919 if (newdir) chdir(newdir);
921 if (argv && envp) execve( filename, argv, envp );
922 err = errno;
923 write( fd[1], &err, sizeof(err) );
924 _exit(1);
926 close( fd[1] );
927 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
929 errno = err;
930 pid = -1;
932 if (pid == -1) FILE_SetDosError();
933 close( fd[0] );
934 return pid;
938 /***********************************************************************
939 * create_process
941 * Create a new process. If hFile is a valid handle we have an exe
942 * file, otherwise it is a Winelib app.
944 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
945 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
946 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
947 LPPROCESS_INFORMATION info, LPCSTR unixdir )
949 BOOL ret, success = FALSE;
950 HANDLE process_info;
951 startup_info_t startup_info;
952 char *extra_env = NULL;
953 int startfd[2];
954 int execfd[2];
955 pid_t pid;
956 int err;
957 char dummy;
959 if (!env)
961 env = GetEnvironmentStringsA();
962 extra_env = DRIVE_BuildEnv();
965 /* create the synchronization pipes */
967 if (pipe( startfd ) == -1)
969 FILE_SetDosError();
970 return FALSE;
972 if (pipe( execfd ) == -1)
974 close( startfd[0] );
975 close( startfd[1] );
976 FILE_SetDosError();
977 return FALSE;
979 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
981 /* create the child process */
983 if (!(pid = fork())) /* child */
985 char **argv = build_argv( cmd_line, 1 );
986 char **envp = build_envp( env, extra_env );
988 close( startfd[1] );
989 close( execfd[0] );
991 /* wait for parent to tell us to start */
992 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
994 close( startfd[0] );
995 /* Reset signals that we previously set to SIG_IGN */
996 signal( SIGPIPE, SIG_DFL );
997 signal( SIGCHLD, SIG_DFL );
999 if (unixdir) chdir(unixdir);
1001 if (argv && envp) exec_wine_binary( argv, envp );
1003 err = errno;
1004 write( execfd[1], &err, sizeof(err) );
1005 _exit(1);
1008 /* this is the parent */
1010 close( startfd[0] );
1011 close( execfd[1] );
1012 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1013 if (pid == -1)
1015 close( startfd[1] );
1016 close( execfd[0] );
1017 FILE_SetDosError();
1018 return FALSE;
1021 /* fill the startup info structure */
1023 startup_info.size = sizeof(startup_info);
1024 /* startup_info.filename_len is set below */
1025 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
1026 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
1027 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
1028 startup_info.x = startup->dwX;
1029 startup_info.y = startup->dwY;
1030 startup_info.cx = startup->dwXSize;
1031 startup_info.cy = startup->dwYSize;
1032 startup_info.x_chars = startup->dwXCountChars;
1033 startup_info.y_chars = startup->dwYCountChars;
1034 startup_info.attribute = startup->dwFillAttribute;
1035 startup_info.cmd_show = startup->wShowWindow;
1036 startup_info.flags = startup->dwFlags;
1038 /* create the process on the server side */
1040 SERVER_START_REQ( new_process )
1042 char buf[MAX_PATH];
1043 LPCSTR nameptr;
1045 req->inherit_all = inherit;
1046 req->create_flags = flags;
1047 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
1048 req->unix_pid = pid;
1049 req->exe_file = hFile;
1050 if (startup->dwFlags & STARTF_USESTDHANDLES)
1052 req->hstdin = startup->hStdInput;
1053 req->hstdout = startup->hStdOutput;
1054 req->hstderr = startup->hStdError;
1056 else
1058 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1059 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1060 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1063 if (GetLongPathNameA( filename, buf, MAX_PATH ))
1064 nameptr = buf;
1065 else
1066 nameptr = filename;
1068 startup_info.filename_len = strlen(nameptr);
1069 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
1070 wine_server_add_data( req, nameptr, startup_info.filename_len );
1071 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
1072 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
1073 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
1075 ret = !wine_server_call_err( req );
1076 process_info = reply->info;
1078 SERVER_END_REQ;
1080 if (!ret)
1082 close( startfd[1] );
1083 close( execfd[0] );
1084 return FALSE;
1087 /* tell child to start and wait for it to exec */
1089 write( startfd[1], &dummy, 1 );
1090 close( startfd[1] );
1092 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1094 errno = err;
1095 FILE_SetDosError();
1096 close( execfd[0] );
1097 CloseHandle( process_info );
1098 return FALSE;
1101 /* wait for the new process info to be ready */
1103 WaitForSingleObject( process_info, INFINITE );
1104 SERVER_START_REQ( get_new_process_info )
1106 req->info = process_info;
1107 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1108 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1109 if ((ret = !wine_server_call_err( req )))
1111 info->dwProcessId = (DWORD)reply->pid;
1112 info->dwThreadId = (DWORD)reply->tid;
1113 info->hProcess = reply->phandle;
1114 info->hThread = reply->thandle;
1115 success = reply->success;
1118 SERVER_END_REQ;
1120 if (ret && !success) /* new process failed to start */
1122 DWORD exitcode;
1123 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1124 CloseHandle( info->hThread );
1125 CloseHandle( info->hProcess );
1126 ret = FALSE;
1128 CloseHandle( process_info );
1129 return ret;
1133 /*************************************************************************
1134 * get_file_name
1136 * Helper for CreateProcess: retrieve the file name to load from the
1137 * app name and command line. Store the file name in buffer, and
1138 * return a possibly modified command line.
1139 * Also returns a handle to the opened file if it's a Windows binary.
1141 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1142 int buflen, HANDLE *handle )
1144 char *name, *pos, *ret = NULL;
1145 const char *p;
1147 /* if we have an app name, everything is easy */
1149 if (appname)
1151 /* use the unmodified app name as file name */
1152 lstrcpynA( buffer, appname, buflen );
1153 *handle = open_exe_file( buffer );
1154 if (!(ret = cmdline) || !cmdline[0])
1156 /* no command-line, create one */
1157 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1158 sprintf( ret, "\"%s\"", appname );
1160 return ret;
1163 if (!cmdline)
1165 SetLastError( ERROR_INVALID_PARAMETER );
1166 return NULL;
1169 /* first check for a quoted file name */
1171 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1173 int len = p - cmdline - 1;
1174 /* extract the quoted portion as file name */
1175 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1176 memcpy( name, cmdline + 1, len );
1177 name[len] = 0;
1179 if (find_exe_file( name, buffer, buflen, handle ))
1180 ret = cmdline; /* no change necessary */
1181 goto done;
1184 /* now try the command-line word by word */
1186 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1187 pos = name;
1188 p = cmdline;
1190 while (*p)
1192 do *pos++ = *p++; while (*p && *p != ' ');
1193 *pos = 0;
1194 if (find_exe_file( name, buffer, buflen, handle ))
1196 ret = cmdline;
1197 break;
1201 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1203 /* now build a new command-line with quotes */
1205 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1206 sprintf( ret, "\"%s\"%s", name, p );
1208 done:
1209 HeapFree( GetProcessHeap(), 0, name );
1210 return ret;
1214 /**********************************************************************
1215 * CreateProcessA (KERNEL32.@)
1217 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1218 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1219 DWORD flags, LPVOID env, LPCSTR cur_dir,
1220 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1222 BOOL retv = FALSE;
1223 HANDLE hFile = 0;
1224 const char *unixdir = NULL;
1225 DOS_FULL_NAME full_dir;
1226 char name[MAX_PATH];
1227 LPSTR tidy_cmdline;
1228 char *p;
1230 /* Process the AppName and/or CmdLine to get module name and path */
1232 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1234 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1235 return FALSE;
1236 if (hFile == INVALID_HANDLE_VALUE) goto done;
1238 /* Warn if unsupported features are used */
1240 if (flags & NORMAL_PRIORITY_CLASS)
1241 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1242 if (flags & IDLE_PRIORITY_CLASS)
1243 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1244 if (flags & HIGH_PRIORITY_CLASS)
1245 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1246 if (flags & REALTIME_PRIORITY_CLASS)
1247 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1248 if (flags & CREATE_NEW_PROCESS_GROUP)
1249 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1250 if (flags & CREATE_UNICODE_ENVIRONMENT)
1251 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1252 if (flags & CREATE_SEPARATE_WOW_VDM)
1253 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1254 if (flags & CREATE_SHARED_WOW_VDM)
1255 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1256 if (flags & CREATE_DEFAULT_ERROR_MODE)
1257 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1258 if (flags & CREATE_NO_WINDOW)
1259 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1260 if (flags & PROFILE_USER)
1261 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1262 if (flags & PROFILE_KERNEL)
1263 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1264 if (flags & PROFILE_SERVER)
1265 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1266 if (startup_info->lpDesktop)
1267 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1268 name, debugstr_a(startup_info->lpDesktop));
1269 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1270 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1271 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1272 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1273 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1274 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1275 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1276 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1278 if (cur_dir)
1280 UNICODE_STRING cur_dirW;
1281 RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1282 if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1283 unixdir = full_dir.long_name;
1284 RtlFreeUnicodeString(&cur_dirW);
1286 else
1288 WCHAR buf[MAX_PATH];
1289 if (GetCurrentDirectoryW(MAX_PATH, buf))
1291 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1295 info->hThread = info->hProcess = 0;
1296 info->dwProcessId = info->dwThreadId = 0;
1298 /* Determine executable type */
1300 if (!hFile) /* builtin exe */
1302 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1303 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1304 inherit, flags, startup_info, info, unixdir );
1305 goto done;
1308 switch( MODULE_GetBinaryType( hFile ))
1310 case BINARY_PE_EXE:
1311 case BINARY_WIN16:
1312 case BINARY_DOS:
1313 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1314 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1315 inherit, flags, startup_info, info, unixdir );
1316 break;
1317 case BINARY_OS216:
1318 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1319 SetLastError( ERROR_BAD_EXE_FORMAT );
1320 break;
1321 case BINARY_PE_DLL:
1322 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1323 SetLastError( ERROR_BAD_EXE_FORMAT );
1324 break;
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 );
1329 break;
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_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1338 inherit, flags, startup_info, info, unixdir );
1339 break;
1341 if (!FILE_strcasecmp( p, ".bat" ))
1343 char comspec[MAX_PATH];
1344 if (GetEnvironmentVariableA("COMSPEC", comspec, sizeof(comspec)))
1346 char *newcmdline, *q = strchr(cmd_line, ' ');
1347 if (!q) q = "";
1348 if ((newcmdline = HeapAlloc( GetProcessHeap(), 0,
1349 strlen(comspec) + strlen(name) + strlen(q) + 8)))
1351 sprintf( newcmdline, "%s /c %s%s", comspec, name, q );
1352 TRACE( "starting %s as batch binary: %s\n",
1353 debugstr_a(name), debugstr_a(newcmdline) );
1354 retv = CreateProcessA( comspec, newcmdline, process_attr, thread_attr,
1355 inherit, flags, env, cur_dir, startup_info, info );
1356 HeapFree( GetProcessHeap(), 0, newcmdline );
1357 break;
1362 /* fall through */
1363 case BINARY_UNIX_EXE:
1365 /* unknown file, try as unix executable */
1366 UNICODE_STRING nameW;
1367 DOS_FULL_NAME full_name;
1368 const char *unixfilename = name;
1370 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1372 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1373 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1374 RtlFreeUnicodeString(&nameW);
1375 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1377 break;
1379 CloseHandle( hFile );
1381 done:
1382 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1383 return retv;
1387 /**********************************************************************
1388 * CreateProcessW (KERNEL32.@)
1389 * NOTES
1390 * lpReserved is not converted
1392 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1393 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1394 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1395 LPPROCESS_INFORMATION info )
1397 BOOL ret;
1398 STARTUPINFOA StartupInfoA;
1400 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1401 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1402 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1404 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1405 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1406 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1408 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1410 if (startup_info->lpReserved)
1411 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1412 debugstr_w(startup_info->lpReserved));
1414 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1415 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1417 HeapFree( GetProcessHeap(), 0, cur_dirA );
1418 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1419 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1420 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1422 return ret;
1426 /***********************************************************************
1427 * ExitProcess (KERNEL32.@)
1429 void WINAPI ExitProcess( DWORD status )
1431 LdrShutdownProcess();
1432 SERVER_START_REQ( terminate_process )
1434 /* send the exit code to the server */
1435 req->handle = GetCurrentProcess();
1436 req->exit_code = status;
1437 wine_server_call( req );
1439 SERVER_END_REQ;
1440 exit( status );
1443 /***********************************************************************
1444 * ExitProcess (KERNEL.466)
1446 void WINAPI ExitProcess16( WORD status )
1448 DWORD count;
1449 ReleaseThunkLock( &count );
1450 ExitProcess( status );
1453 /******************************************************************************
1454 * TerminateProcess (KERNEL32.@)
1456 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1458 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1459 if (status) SetLastError( RtlNtStatusToDosError(status) );
1460 return !status;
1464 /***********************************************************************
1465 * GetProcessDword (KERNEL.485)
1466 * GetProcessDword (KERNEL32.18)
1467 * 'Of course you cannot directly access Windows internal structures'
1469 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1471 DWORD x, y;
1473 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1475 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1477 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1478 return 0;
1481 switch ( offset )
1483 case GPD_APP_COMPAT_FLAGS:
1484 return GetAppCompatFlags16(0);
1486 case GPD_LOAD_DONE_EVENT:
1487 return (DWORD)current_process.load_done_evt;
1489 case GPD_HINSTANCE16:
1490 return GetTaskDS16();
1492 case GPD_WINDOWS_VERSION:
1493 return GetExeVersion16();
1495 case GPD_THDB:
1496 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1498 case GPD_PDB:
1499 return (DWORD)&current_process;
1501 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1502 return (DWORD)current_startupinfo.hStdOutput;
1504 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1505 return (DWORD)current_startupinfo.hStdInput;
1507 case GPD_STARTF_SHOWWINDOW:
1508 return current_startupinfo.wShowWindow;
1510 case GPD_STARTF_SIZE:
1511 x = current_startupinfo.dwXSize;
1512 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1513 y = current_startupinfo.dwYSize;
1514 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1515 return MAKELONG( x, y );
1517 case GPD_STARTF_POSITION:
1518 x = current_startupinfo.dwX;
1519 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1520 y = current_startupinfo.dwY;
1521 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1522 return MAKELONG( x, y );
1524 case GPD_STARTF_FLAGS:
1525 return current_startupinfo.dwFlags;
1527 case GPD_PARENT:
1528 return 0;
1530 case GPD_FLAGS:
1531 return current_process.flags;
1533 case GPD_USERDATA:
1534 return current_process.process_dword;
1536 default:
1537 ERR_(win32)("Unknown offset %d\n", offset );
1538 return 0;
1542 /***********************************************************************
1543 * SetProcessDword (KERNEL.484)
1544 * 'Of course you cannot directly access Windows internal structures'
1546 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1548 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1550 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1552 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1553 return;
1556 switch ( offset )
1558 case GPD_APP_COMPAT_FLAGS:
1559 case GPD_LOAD_DONE_EVENT:
1560 case GPD_HINSTANCE16:
1561 case GPD_WINDOWS_VERSION:
1562 case GPD_THDB:
1563 case GPD_PDB:
1564 case GPD_STARTF_SHELLDATA:
1565 case GPD_STARTF_HOTKEY:
1566 case GPD_STARTF_SHOWWINDOW:
1567 case GPD_STARTF_SIZE:
1568 case GPD_STARTF_POSITION:
1569 case GPD_STARTF_FLAGS:
1570 case GPD_PARENT:
1571 case GPD_FLAGS:
1572 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1573 break;
1575 case GPD_USERDATA:
1576 current_process.process_dword = value;
1577 break;
1579 default:
1580 ERR_(win32)("Unknown offset %d\n", offset );
1581 break;
1586 /*********************************************************************
1587 * OpenProcess (KERNEL32.@)
1589 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1591 HANDLE ret = 0;
1592 SERVER_START_REQ( open_process )
1594 req->pid = id;
1595 req->access = access;
1596 req->inherit = inherit;
1597 if (!wine_server_call_err( req )) ret = reply->handle;
1599 SERVER_END_REQ;
1600 return ret;
1603 /*********************************************************************
1604 * MapProcessHandle (KERNEL.483)
1606 DWORD WINAPI MapProcessHandle( HANDLE handle )
1608 DWORD ret = 0;
1609 SERVER_START_REQ( get_process_info )
1611 req->handle = handle;
1612 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1614 SERVER_END_REQ;
1615 return ret;
1618 /***********************************************************************
1619 * SetPriorityClass (KERNEL32.@)
1621 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1623 BOOL ret;
1624 SERVER_START_REQ( set_process_info )
1626 req->handle = hprocess;
1627 req->priority = priorityclass;
1628 req->mask = SET_PROCESS_INFO_PRIORITY;
1629 ret = !wine_server_call_err( req );
1631 SERVER_END_REQ;
1632 return ret;
1636 /***********************************************************************
1637 * GetPriorityClass (KERNEL32.@)
1639 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1641 DWORD ret = 0;
1642 SERVER_START_REQ( get_process_info )
1644 req->handle = hprocess;
1645 if (!wine_server_call_err( req )) ret = reply->priority;
1647 SERVER_END_REQ;
1648 return ret;
1652 /***********************************************************************
1653 * SetProcessAffinityMask (KERNEL32.@)
1655 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1657 BOOL ret;
1658 SERVER_START_REQ( set_process_info )
1660 req->handle = hProcess;
1661 req->affinity = affmask;
1662 req->mask = SET_PROCESS_INFO_AFFINITY;
1663 ret = !wine_server_call_err( req );
1665 SERVER_END_REQ;
1666 return ret;
1669 /**********************************************************************
1670 * GetProcessAffinityMask (KERNEL32.@)
1672 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1673 LPDWORD lpProcessAffinityMask,
1674 LPDWORD lpSystemAffinityMask )
1676 BOOL ret = FALSE;
1677 SERVER_START_REQ( get_process_info )
1679 req->handle = hProcess;
1680 if (!wine_server_call_err( req ))
1682 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1683 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1684 ret = TRUE;
1687 SERVER_END_REQ;
1688 return ret;
1692 /***********************************************************************
1693 * GetProcessVersion (KERNEL32.@)
1695 DWORD WINAPI GetProcessVersion( DWORD processid )
1697 IMAGE_NT_HEADERS *nt;
1699 if (processid && processid != GetCurrentProcessId())
1701 FIXME("should use ReadProcessMemory\n");
1702 return 0;
1704 if ((nt = RtlImageNtHeader( current_process.module )))
1705 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1706 nt->OptionalHeader.MinorSubsystemVersion);
1707 return 0;
1710 /***********************************************************************
1711 * GetProcessFlags (KERNEL32.@)
1713 DWORD WINAPI GetProcessFlags( DWORD processid )
1715 if (processid && processid != GetCurrentProcessId()) return 0;
1716 return current_process.flags;
1720 /***********************************************************************
1721 * SetProcessWorkingSetSize [KERNEL32.@]
1722 * Sets the min/max working set sizes for a specified process.
1724 * PARAMS
1725 * hProcess [I] Handle to the process of interest
1726 * minset [I] Specifies minimum working set size
1727 * maxset [I] Specifies maximum working set size
1729 * RETURNS STD
1731 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
1732 SIZE_T maxset)
1734 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1735 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
1736 /* Trim the working set to zero */
1737 /* Swap the process out of physical RAM */
1739 return TRUE;
1742 /***********************************************************************
1743 * GetProcessWorkingSetSize (KERNEL32.@)
1745 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
1746 PSIZE_T maxset)
1748 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
1749 /* 32 MB working set size */
1750 if (minset) *minset = 32*1024*1024;
1751 if (maxset) *maxset = 32*1024*1024;
1752 return TRUE;
1755 /***********************************************************************
1756 * SetProcessShutdownParameters (KERNEL32.@)
1758 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1759 * Now tracks changes made (but does not act on these changes)
1761 static DWORD shutdown_flags = 0;
1762 static DWORD shutdown_priority = 0x280;
1764 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1766 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1767 shutdown_flags = flags;
1768 shutdown_priority = level;
1769 return TRUE;
1773 /***********************************************************************
1774 * GetProcessShutdownParameters (KERNEL32.@)
1777 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1779 *lpdwLevel = shutdown_priority;
1780 *lpdwFlags = shutdown_flags;
1781 return TRUE;
1785 /***********************************************************************
1786 * SetProcessPriorityBoost (KERNEL32.@)
1788 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1790 FIXME("(%p,%d): stub\n",hprocess,disableboost);
1791 /* Say we can do it. I doubt the program will notice that we don't. */
1792 return TRUE;
1796 /***********************************************************************
1797 * ReadProcessMemory (KERNEL32.@)
1799 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
1800 SIZE_T *bytes_read )
1802 DWORD res;
1804 SERVER_START_REQ( read_process_memory )
1806 req->handle = process;
1807 req->addr = (void *)addr;
1808 wine_server_set_reply( req, buffer, size );
1809 if ((res = wine_server_call_err( req ))) size = 0;
1811 SERVER_END_REQ;
1812 if (bytes_read) *bytes_read = size;
1813 return !res;
1817 /***********************************************************************
1818 * WriteProcessMemory (KERNEL32.@)
1820 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
1821 SIZE_T *bytes_written )
1823 static const int zero;
1824 unsigned int first_offset, last_offset, first_mask, last_mask;
1825 DWORD res;
1827 if (!size)
1829 SetLastError( ERROR_INVALID_PARAMETER );
1830 return FALSE;
1833 /* compute the mask for the first int */
1834 first_mask = ~0;
1835 first_offset = (unsigned int)addr % sizeof(int);
1836 memset( &first_mask, 0, first_offset );
1838 /* compute the mask for the last int */
1839 last_offset = (size + first_offset) % sizeof(int);
1840 last_mask = 0;
1841 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1843 SERVER_START_REQ( write_process_memory )
1845 req->handle = process;
1846 req->addr = (char *)addr - first_offset;
1847 req->first_mask = first_mask;
1848 req->last_mask = last_mask;
1849 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1850 wine_server_add_data( req, buffer, size );
1851 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1853 if ((res = wine_server_call_err( req ))) size = 0;
1855 SERVER_END_REQ;
1856 if (bytes_written) *bytes_written = size;
1858 char dummy[32];
1859 SIZE_T read;
1860 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1862 return !res;
1866 /***********************************************************************
1867 * RegisterServiceProcess (KERNEL.491)
1868 * RegisterServiceProcess (KERNEL32.@)
1870 * A service process calls this function to ensure that it continues to run
1871 * even after a user logged off.
1873 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1875 /* I don't think that Wine needs to do anything in that function */
1876 return 1; /* success */
1879 /***********************************************************************
1880 * GetExitCodeProcess [KERNEL32.@]
1882 * Gets termination status of specified process
1884 * RETURNS
1885 * Success: TRUE
1886 * Failure: FALSE
1888 BOOL WINAPI GetExitCodeProcess(
1889 HANDLE hProcess, /* [in] handle to the process */
1890 LPDWORD lpExitCode) /* [out] address to receive termination status */
1892 BOOL ret;
1893 SERVER_START_REQ( get_process_info )
1895 req->handle = hProcess;
1896 ret = !wine_server_call_err( req );
1897 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1899 SERVER_END_REQ;
1900 return ret;
1904 /***********************************************************************
1905 * SetErrorMode (KERNEL32.@)
1907 UINT WINAPI SetErrorMode( UINT mode )
1909 UINT old = current_process.error_mode;
1910 current_process.error_mode = mode;
1911 return old;
1915 /**************************************************************************
1916 * SetFileApisToOEM (KERNEL32.@)
1918 VOID WINAPI SetFileApisToOEM(void)
1920 current_process.flags |= PDB32_FILE_APIS_OEM;
1924 /**************************************************************************
1925 * SetFileApisToANSI (KERNEL32.@)
1927 VOID WINAPI SetFileApisToANSI(void)
1929 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1933 /******************************************************************************
1934 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1936 * RETURNS
1937 * TRUE: Set of file functions is using ANSI code page
1938 * FALSE: Set of file functions is using OEM code page
1940 BOOL WINAPI AreFileApisANSI(void)
1942 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1946 /***********************************************************************
1947 * GetTickCount (KERNEL32.@)
1949 * Returns the number of milliseconds, modulo 2^32, since the start
1950 * of the wineserver.
1952 DWORD WINAPI GetTickCount(void)
1954 struct timeval t;
1955 gettimeofday( &t, NULL );
1956 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1960 /**********************************************************************
1961 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1963 * Allocates a thread local storage index
1965 * RETURNS
1966 * Success: TLS Index
1967 * Failure: 0xFFFFFFFF
1969 DWORD WINAPI TlsAlloc( void )
1971 DWORD i, mask, ret = 0;
1972 DWORD *bits = current_process.tls_bits;
1973 RtlAcquirePebLock();
1974 if (*bits == 0xffffffff)
1976 bits++;
1977 ret = 32;
1978 if (*bits == 0xffffffff)
1980 RtlReleasePebLock();
1981 SetLastError( ERROR_NO_MORE_ITEMS );
1982 return 0xffffffff;
1985 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1986 *bits |= mask;
1987 RtlReleasePebLock();
1988 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1989 return ret + i;
1993 /**********************************************************************
1994 * TlsFree [KERNEL32.@] Releases a TLS index.
1996 * Releases a thread local storage index, making it available for reuse
1998 * RETURNS
1999 * Success: TRUE
2000 * Failure: FALSE
2002 BOOL WINAPI TlsFree(
2003 DWORD index) /* [in] TLS Index to free */
2005 DWORD mask = (1 << (index & 31));
2006 DWORD *bits = current_process.tls_bits;
2007 if (index >= 64)
2009 SetLastError( ERROR_INVALID_PARAMETER );
2010 return FALSE;
2012 if (index >= 32) bits++;
2013 RtlAcquirePebLock();
2014 if (!(*bits & mask)) /* already free? */
2016 RtlReleasePebLock();
2017 SetLastError( ERROR_INVALID_PARAMETER );
2018 return FALSE;
2020 *bits &= ~mask;
2021 NtCurrentTeb()->tls_array[index] = 0;
2022 /* FIXME: should zero all other thread values */
2023 RtlReleasePebLock();
2024 return TRUE;
2028 /**********************************************************************
2029 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2031 * RETURNS
2032 * Success: Value stored in calling thread's TLS slot for index
2033 * Failure: 0 and GetLastError returns NO_ERROR
2035 LPVOID WINAPI TlsGetValue(
2036 DWORD index) /* [in] TLS index to retrieve value for */
2038 if (index >= 64)
2040 SetLastError( ERROR_INVALID_PARAMETER );
2041 return NULL;
2043 SetLastError( ERROR_SUCCESS );
2044 return NtCurrentTeb()->tls_array[index];
2048 /**********************************************************************
2049 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2051 * RETURNS
2052 * Success: TRUE
2053 * Failure: FALSE
2055 BOOL WINAPI TlsSetValue(
2056 DWORD index, /* [in] TLS index to set value for */
2057 LPVOID value) /* [in] Value to be stored */
2059 if (index >= 64)
2061 SetLastError( ERROR_INVALID_PARAMETER );
2062 return FALSE;
2064 NtCurrentTeb()->tls_array[index] = value;
2065 return TRUE;
2069 /***********************************************************************
2070 * GetCurrentProcess (KERNEL32.@)
2072 #undef GetCurrentProcess
2073 HANDLE WINAPI GetCurrentProcess(void)
2075 return (HANDLE)0xffffffff;