Fix existing string functions, implement a bunch of new ones.
[wine/hacks.git] / scheduler / process.c
blobb3efdff8f0a7fe465f891c7585a22b8b560df8a8
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=%x 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;
654 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
655 if (DOSFS_GetFullName( name, TRUE, &full_name )) name = full_name.long_name;
656 CloseHandle( main_exe_file );
657 main_exe_file = 0;
658 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
660 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
661 goto found;
663 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
664 ExitProcess(1);
668 found:
669 /* build command line */
670 if (!ENV_BuildCommandLine( argv )) goto error;
672 /* create 32-bit module for main exe */
673 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
674 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
676 /* allocate main thread stack */
677 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
679 /* switch to the new stack */
680 SYSDEPS_SwitchToThreadStack( start_process );
682 error:
683 ExitProcess( GetLastError() );
687 /***********************************************************************
688 * build_argv
690 * Build an argv array from a command-line.
691 * The command-line is modified to insert nulls.
692 * 'reserved' is the number of args to reserve before the first one.
694 static char **build_argv( char *cmdline, int reserved )
696 int argc;
697 char** argv;
698 char *arg,*s,*d;
699 int in_quotes,bcount;
701 argc=reserved+1;
702 bcount=0;
703 in_quotes=0;
704 s=cmdline;
705 while (1) {
706 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
707 /* space */
708 argc++;
709 /* skip the remaining spaces */
710 while (*s==' ' || *s=='\t') {
711 s++;
713 if (*s=='\0')
714 break;
715 bcount=0;
716 continue;
717 } else if (*s=='\\') {
718 /* '\', count them */
719 bcount++;
720 } else if ((*s=='"') && ((bcount & 1)==0)) {
721 /* unescaped '"' */
722 in_quotes=!in_quotes;
723 bcount=0;
724 } else {
725 /* a regular character */
726 bcount=0;
728 s++;
730 argv=malloc(argc*sizeof(*argv));
731 if (!argv)
732 return NULL;
734 arg=d=s=cmdline;
735 bcount=0;
736 in_quotes=0;
737 argc=reserved;
738 while (*s) {
739 if ((*s==' ' || *s=='\t') && !in_quotes) {
740 /* Close the argument and copy it */
741 *d=0;
742 argv[argc++]=arg;
744 /* skip the remaining spaces */
745 do {
746 s++;
747 } while (*s==' ' || *s=='\t');
749 /* Start with a new argument */
750 arg=d=s;
751 bcount=0;
752 } else if (*s=='\\') {
753 /* '\\' */
754 *d++=*s++;
755 bcount++;
756 } else if (*s=='"') {
757 /* '"' */
758 if ((bcount & 1)==0) {
759 /* Preceeded by an even number of '\', this is half that
760 * number of '\', plus a '"' which we discard.
762 d-=bcount/2;
763 s++;
764 in_quotes=!in_quotes;
765 } else {
766 /* Preceeded by an odd number of '\', this is half that
767 * number of '\' followed by a '"'
769 d=d-bcount/2-1;
770 *d++='"';
771 s++;
773 bcount=0;
774 } else {
775 /* a regular character */
776 *d++=*s++;
777 bcount=0;
780 if (*arg) {
781 *d='\0';
782 argv[argc++]=arg;
784 argv[argc]=NULL;
786 return argv;
790 /***********************************************************************
791 * build_envp
793 * Build the environment of a new child process.
795 static char **build_envp( const char *env, const char *extra_env )
797 const char *p;
798 char **envp;
799 int count = 0;
801 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
802 for (p = env; *p; count++) p += strlen(p) + 1;
803 count += 3;
805 if ((envp = malloc( count * sizeof(*envp) )))
807 extern char **environ;
808 char **envptr = envp;
809 char **unixptr = environ;
810 /* first the extra strings */
811 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
812 /* then put PATH, HOME and WINEPREFIX from the unix env */
813 for (unixptr = environ; unixptr && *unixptr; unixptr++)
814 if (!memcmp( *unixptr, "PATH=", 5 ) ||
815 !memcmp( *unixptr, "HOME=", 5 ) ||
816 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
817 /* now put the Windows environment strings */
818 for (p = env; *p; p += strlen(p) + 1)
820 if (memcmp( p, "PATH=", 5 ) &&
821 memcmp( p, "HOME=", 5 ) &&
822 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
824 *envptr = 0;
826 return envp;
830 /***********************************************************************
831 * exec_wine_binary
833 * Locate the Wine binary to exec for a new Win32 process.
835 static void exec_wine_binary( char **argv, char **envp )
837 const char *path, *pos, *ptr;
839 /* first, try for a WINELOADER environment variable */
840 argv[0] = getenv("WINELOADER");
841 if (argv[0])
842 execve( argv[0], argv, envp );
844 /* next, try bin directory */
845 argv[0] = BINDIR "/wine";
846 execve( argv[0], argv, envp );
848 /* now try the path of argv0 of the current binary */
849 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
850 if ((ptr = strrchr( full_argv0, '/' )))
852 memcpy( argv[0], full_argv0, ptr - full_argv0 );
853 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
854 execve( argv[0], argv, envp );
856 free( argv[0] );
858 /* now search in the Unix path */
859 if ((path = getenv( "PATH" )))
861 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
862 pos = path;
863 for (;;)
865 while (*pos == ':') pos++;
866 if (!*pos) break;
867 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
868 memcpy( argv[0], pos, ptr - pos );
869 strcpy( argv[0] + (ptr - pos), "/wine" );
870 execve( argv[0], argv, envp );
871 pos = ptr;
874 free( argv[0] );
878 /***********************************************************************
879 * fork_and_exec
881 * Fork and exec a new Unix process, checking for errors.
883 static int fork_and_exec( const char *filename, char *cmdline,
884 const char *env, const char *newdir )
886 int fd[2];
887 int pid, err;
888 char *extra_env = NULL;
890 if (!env)
892 env = GetEnvironmentStringsA();
893 extra_env = DRIVE_BuildEnv();
896 if (pipe(fd) == -1)
898 FILE_SetDosError();
899 return -1;
901 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
902 if (!(pid = fork())) /* child */
904 char **argv = build_argv( cmdline, filename ? 0 : 1 );
905 char **envp = build_envp( env, extra_env );
906 close( fd[0] );
908 /* Reset signals that we previously set to SIG_IGN */
909 signal( SIGPIPE, SIG_DFL );
910 signal( SIGCHLD, SIG_DFL );
912 if (newdir) chdir(newdir);
914 if (argv && envp)
916 if (!filename) exec_wine_binary( argv, envp );
917 else execve( filename, argv, envp );
919 err = errno;
920 write( fd[1], &err, sizeof(err) );
921 _exit(1);
923 close( fd[1] );
924 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
926 errno = err;
927 pid = -1;
929 if (pid == -1) FILE_SetDosError();
930 close( fd[0] );
931 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
932 return pid;
936 /***********************************************************************
937 * create_process
939 * Create a new process. If hFile is a valid handle we have an exe
940 * file, otherwise it is a Winelib app.
942 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
943 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
944 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
945 LPPROCESS_INFORMATION info, LPCSTR unixdir )
947 BOOL ret, success = FALSE;
948 HANDLE process_info;
949 startup_info_t startup_info;
951 /* fill the startup info structure */
953 startup_info.size = sizeof(startup_info);
954 /* startup_info.filename_len is set below */
955 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
956 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
957 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
958 startup_info.x = startup->dwX;
959 startup_info.y = startup->dwY;
960 startup_info.cx = startup->dwXSize;
961 startup_info.cy = startup->dwYSize;
962 startup_info.x_chars = startup->dwXCountChars;
963 startup_info.y_chars = startup->dwYCountChars;
964 startup_info.attribute = startup->dwFillAttribute;
965 startup_info.cmd_show = startup->wShowWindow;
966 startup_info.flags = startup->dwFlags;
968 /* create the process on the server side */
970 SERVER_START_REQ( new_process )
972 char buf[MAX_PATH];
973 LPCSTR nameptr;
975 req->inherit_all = inherit;
976 req->create_flags = flags;
977 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
978 req->exe_file = hFile;
979 if (startup->dwFlags & STARTF_USESTDHANDLES)
981 req->hstdin = startup->hStdInput;
982 req->hstdout = startup->hStdOutput;
983 req->hstderr = startup->hStdError;
985 else
987 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
988 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
989 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
992 if (GetLongPathNameA( filename, buf, MAX_PATH ))
993 nameptr = buf;
994 else
995 nameptr = filename;
997 startup_info.filename_len = strlen(nameptr);
998 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
999 wine_server_add_data( req, nameptr, startup_info.filename_len );
1000 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
1001 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
1002 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
1004 ret = !wine_server_call_err( req );
1005 process_info = reply->info;
1007 SERVER_END_REQ;
1008 if (!ret) return FALSE;
1010 /* fork and execute */
1012 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
1014 CloseHandle( process_info );
1015 return FALSE;
1018 /* wait for the new process info to be ready */
1020 WaitForSingleObject( process_info, INFINITE );
1021 SERVER_START_REQ( get_new_process_info )
1023 req->info = process_info;
1024 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1025 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1026 if ((ret = !wine_server_call_err( req )))
1028 info->dwProcessId = (DWORD)reply->pid;
1029 info->dwThreadId = (DWORD)reply->tid;
1030 info->hProcess = reply->phandle;
1031 info->hThread = reply->thandle;
1032 success = reply->success;
1035 SERVER_END_REQ;
1037 if (ret && !success) /* new process failed to start */
1039 DWORD exitcode;
1040 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1041 CloseHandle( info->hThread );
1042 CloseHandle( info->hProcess );
1043 ret = FALSE;
1045 CloseHandle( process_info );
1046 return ret;
1050 /*************************************************************************
1051 * get_file_name
1053 * Helper for CreateProcess: retrieve the file name to load from the
1054 * app name and command line. Store the file name in buffer, and
1055 * return a possibly modified command line.
1056 * Also returns a handle to the opened file if it's a Windows binary.
1058 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1059 int buflen, HANDLE *handle )
1061 char *name, *pos, *ret = NULL;
1062 const char *p;
1064 /* if we have an app name, everything is easy */
1066 if (appname)
1068 /* use the unmodified app name as file name */
1069 lstrcpynA( buffer, appname, buflen );
1070 *handle = open_exe_file( buffer );
1071 if (!(ret = cmdline))
1073 /* no command-line, create one */
1074 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1075 sprintf( ret, "\"%s\"", appname );
1077 return ret;
1080 if (!cmdline)
1082 SetLastError( ERROR_INVALID_PARAMETER );
1083 return NULL;
1086 /* first check for a quoted file name */
1088 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1090 int len = p - cmdline - 1;
1091 /* extract the quoted portion as file name */
1092 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1093 memcpy( name, cmdline + 1, len );
1094 name[len] = 0;
1096 if (find_exe_file( name, buffer, buflen, handle ))
1097 ret = cmdline; /* no change necessary */
1098 goto done;
1101 /* now try the command-line word by word */
1103 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1104 pos = name;
1105 p = cmdline;
1107 while (*p)
1109 do *pos++ = *p++; while (*p && *p != ' ');
1110 *pos = 0;
1111 if (find_exe_file( name, buffer, buflen, handle ))
1113 ret = cmdline;
1114 break;
1118 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1120 /* now build a new command-line with quotes */
1122 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1123 sprintf( ret, "\"%s\"%s", name, p );
1125 done:
1126 HeapFree( GetProcessHeap(), 0, name );
1127 return ret;
1131 /**********************************************************************
1132 * CreateProcessA (KERNEL32.@)
1134 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1135 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1136 DWORD flags, LPVOID env, LPCSTR cur_dir,
1137 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1139 BOOL retv = FALSE;
1140 HANDLE hFile = 0;
1141 const char *unixdir = NULL;
1142 DOS_FULL_NAME full_dir;
1143 char name[MAX_PATH];
1144 LPSTR tidy_cmdline;
1145 char *p;
1147 /* Process the AppName and/or CmdLine to get module name and path */
1149 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1151 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1152 return FALSE;
1153 if (hFile == INVALID_HANDLE_VALUE) goto done;
1155 /* Warn if unsupported features are used */
1157 if (flags & NORMAL_PRIORITY_CLASS)
1158 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1159 if (flags & IDLE_PRIORITY_CLASS)
1160 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1161 if (flags & HIGH_PRIORITY_CLASS)
1162 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1163 if (flags & REALTIME_PRIORITY_CLASS)
1164 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1165 if (flags & CREATE_NEW_PROCESS_GROUP)
1166 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1167 if (flags & CREATE_UNICODE_ENVIRONMENT)
1168 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1169 if (flags & CREATE_SEPARATE_WOW_VDM)
1170 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1171 if (flags & CREATE_SHARED_WOW_VDM)
1172 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1173 if (flags & CREATE_DEFAULT_ERROR_MODE)
1174 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1175 if (flags & CREATE_NO_WINDOW)
1176 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1177 if (flags & PROFILE_USER)
1178 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1179 if (flags & PROFILE_KERNEL)
1180 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1181 if (flags & PROFILE_SERVER)
1182 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1183 if (startup_info->lpDesktop)
1184 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1185 name, debugstr_a(startup_info->lpDesktop));
1186 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1187 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1188 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1189 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1190 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1191 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1192 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1193 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1195 if (cur_dir)
1197 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir ))
1198 unixdir = full_dir.long_name;
1200 else
1202 char buf[MAX_PATH];
1203 if (GetCurrentDirectoryA(sizeof(buf),buf))
1205 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1209 info->hThread = info->hProcess = 0;
1210 info->dwProcessId = info->dwThreadId = 0;
1212 /* Determine executable type */
1214 if (!hFile) /* builtin exe */
1216 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1217 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1218 inherit, flags, startup_info, info, unixdir );
1219 goto done;
1222 switch( MODULE_GetBinaryType( hFile ))
1224 case BINARY_PE_EXE:
1225 case BINARY_WIN16:
1226 case BINARY_DOS:
1227 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1228 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1229 inherit, flags, startup_info, info, unixdir );
1230 break;
1231 case BINARY_OS216:
1232 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1233 SetLastError( ERROR_BAD_EXE_FORMAT );
1234 break;
1235 case BINARY_PE_DLL:
1236 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1237 SetLastError( ERROR_BAD_EXE_FORMAT );
1238 break;
1239 case BINARY_UNIX_LIB:
1240 TRACE( "%s is a Unix library, starting as Winelib app\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_UNKNOWN:
1245 /* check for .com extension */
1246 if ((p = strrchr( name, '.' )) && !FILE_strcasecmp( p, ".com" ))
1248 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1249 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1250 inherit, flags, startup_info, info, unixdir );
1251 break;
1253 /* fall through */
1254 case BINARY_UNIX_EXE:
1256 DOS_FULL_NAME full_name;
1257 const char *unixfilename = name;
1259 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1260 if (DOSFS_GetFullName( name, TRUE, &full_name )) unixfilename = full_name.long_name;
1261 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1263 break;
1265 CloseHandle( hFile );
1267 done:
1268 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1269 return retv;
1273 /**********************************************************************
1274 * CreateProcessW (KERNEL32.@)
1275 * NOTES
1276 * lpReserved is not converted
1278 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1279 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1280 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1281 LPPROCESS_INFORMATION info )
1283 BOOL ret;
1284 STARTUPINFOA StartupInfoA;
1286 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1287 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1288 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1290 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1291 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1292 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1294 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1296 if (startup_info->lpReserved)
1297 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1298 debugstr_w(startup_info->lpReserved));
1300 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1301 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1303 HeapFree( GetProcessHeap(), 0, cur_dirA );
1304 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1305 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1306 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1308 return ret;
1312 /***********************************************************************
1313 * ExitProcess (KERNEL32.@)
1315 void WINAPI ExitProcess( DWORD status )
1317 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1318 SERVER_START_REQ( terminate_process )
1320 /* send the exit code to the server */
1321 req->handle = GetCurrentProcess();
1322 req->exit_code = status;
1323 wine_server_call( req );
1325 SERVER_END_REQ;
1326 exit( status );
1329 /***********************************************************************
1330 * ExitProcess (KERNEL.466)
1332 void WINAPI ExitProcess16( WORD status )
1334 DWORD count;
1335 ReleaseThunkLock( &count );
1336 ExitProcess( status );
1339 /******************************************************************************
1340 * TerminateProcess (KERNEL32.@)
1342 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1344 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1345 if (status) SetLastError( RtlNtStatusToDosError(status) );
1346 return !status;
1350 /***********************************************************************
1351 * GetProcessDword (KERNEL.485)
1352 * GetProcessDword (KERNEL32.18)
1353 * 'Of course you cannot directly access Windows internal structures'
1355 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1357 DWORD x, y;
1359 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1361 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1363 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1364 return 0;
1367 switch ( offset )
1369 case GPD_APP_COMPAT_FLAGS:
1370 return GetAppCompatFlags16(0);
1372 case GPD_LOAD_DONE_EVENT:
1373 return (DWORD)current_process.load_done_evt;
1375 case GPD_HINSTANCE16:
1376 return GetTaskDS16();
1378 case GPD_WINDOWS_VERSION:
1379 return GetExeVersion16();
1381 case GPD_THDB:
1382 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1384 case GPD_PDB:
1385 return (DWORD)&current_process;
1387 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1388 return (DWORD)current_startupinfo.hStdOutput;
1390 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1391 return (DWORD)current_startupinfo.hStdInput;
1393 case GPD_STARTF_SHOWWINDOW:
1394 return current_startupinfo.wShowWindow;
1396 case GPD_STARTF_SIZE:
1397 x = current_startupinfo.dwXSize;
1398 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1399 y = current_startupinfo.dwYSize;
1400 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1401 return MAKELONG( x, y );
1403 case GPD_STARTF_POSITION:
1404 x = current_startupinfo.dwX;
1405 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1406 y = current_startupinfo.dwY;
1407 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1408 return MAKELONG( x, y );
1410 case GPD_STARTF_FLAGS:
1411 return current_startupinfo.dwFlags;
1413 case GPD_PARENT:
1414 return 0;
1416 case GPD_FLAGS:
1417 return current_process.flags;
1419 case GPD_USERDATA:
1420 return current_process.process_dword;
1422 default:
1423 ERR_(win32)("Unknown offset %d\n", offset );
1424 return 0;
1428 /***********************************************************************
1429 * SetProcessDword (KERNEL.484)
1430 * 'Of course you cannot directly access Windows internal structures'
1432 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1434 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1436 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1438 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1439 return;
1442 switch ( offset )
1444 case GPD_APP_COMPAT_FLAGS:
1445 case GPD_LOAD_DONE_EVENT:
1446 case GPD_HINSTANCE16:
1447 case GPD_WINDOWS_VERSION:
1448 case GPD_THDB:
1449 case GPD_PDB:
1450 case GPD_STARTF_SHELLDATA:
1451 case GPD_STARTF_HOTKEY:
1452 case GPD_STARTF_SHOWWINDOW:
1453 case GPD_STARTF_SIZE:
1454 case GPD_STARTF_POSITION:
1455 case GPD_STARTF_FLAGS:
1456 case GPD_PARENT:
1457 case GPD_FLAGS:
1458 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1459 break;
1461 case GPD_USERDATA:
1462 current_process.process_dword = value;
1463 break;
1465 default:
1466 ERR_(win32)("Unknown offset %d\n", offset );
1467 break;
1472 /*********************************************************************
1473 * OpenProcess (KERNEL32.@)
1475 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1477 HANDLE ret = 0;
1478 SERVER_START_REQ( open_process )
1480 req->pid = (void *)id;
1481 req->access = access;
1482 req->inherit = inherit;
1483 if (!wine_server_call_err( req )) ret = reply->handle;
1485 SERVER_END_REQ;
1486 return ret;
1489 /*********************************************************************
1490 * MapProcessHandle (KERNEL.483)
1492 DWORD WINAPI MapProcessHandle( HANDLE handle )
1494 DWORD ret = 0;
1495 SERVER_START_REQ( get_process_info )
1497 req->handle = handle;
1498 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1500 SERVER_END_REQ;
1501 return ret;
1504 /***********************************************************************
1505 * SetPriorityClass (KERNEL32.@)
1507 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1509 BOOL ret;
1510 SERVER_START_REQ( set_process_info )
1512 req->handle = hprocess;
1513 req->priority = priorityclass;
1514 req->mask = SET_PROCESS_INFO_PRIORITY;
1515 ret = !wine_server_call_err( req );
1517 SERVER_END_REQ;
1518 return ret;
1522 /***********************************************************************
1523 * GetPriorityClass (KERNEL32.@)
1525 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1527 DWORD ret = 0;
1528 SERVER_START_REQ( get_process_info )
1530 req->handle = hprocess;
1531 if (!wine_server_call_err( req )) ret = reply->priority;
1533 SERVER_END_REQ;
1534 return ret;
1538 /***********************************************************************
1539 * SetProcessAffinityMask (KERNEL32.@)
1541 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1543 BOOL ret;
1544 SERVER_START_REQ( set_process_info )
1546 req->handle = hProcess;
1547 req->affinity = affmask;
1548 req->mask = SET_PROCESS_INFO_AFFINITY;
1549 ret = !wine_server_call_err( req );
1551 SERVER_END_REQ;
1552 return ret;
1555 /**********************************************************************
1556 * GetProcessAffinityMask (KERNEL32.@)
1558 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1559 LPDWORD lpProcessAffinityMask,
1560 LPDWORD lpSystemAffinityMask )
1562 BOOL ret = FALSE;
1563 SERVER_START_REQ( get_process_info )
1565 req->handle = hProcess;
1566 if (!wine_server_call_err( req ))
1568 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1569 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1570 ret = TRUE;
1573 SERVER_END_REQ;
1574 return ret;
1578 /***********************************************************************
1579 * GetProcessVersion (KERNEL32.@)
1581 DWORD WINAPI GetProcessVersion( DWORD processid )
1583 IMAGE_NT_HEADERS *nt;
1585 if (processid && processid != GetCurrentProcessId())
1587 FIXME("should use ReadProcessMemory\n");
1588 return 0;
1590 if ((nt = RtlImageNtHeader( current_process.module )))
1591 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1592 nt->OptionalHeader.MinorSubsystemVersion);
1593 return 0;
1596 /***********************************************************************
1597 * GetProcessFlags (KERNEL32.@)
1599 DWORD WINAPI GetProcessFlags( DWORD processid )
1601 if (processid && processid != GetCurrentProcessId()) return 0;
1602 return current_process.flags;
1606 /***********************************************************************
1607 * SetProcessWorkingSetSize [KERNEL32.@]
1608 * Sets the min/max working set sizes for a specified process.
1610 * PARAMS
1611 * hProcess [I] Handle to the process of interest
1612 * minset [I] Specifies minimum working set size
1613 * maxset [I] Specifies maximum working set size
1615 * RETURNS STD
1617 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1618 DWORD maxset)
1620 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1621 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1622 /* Trim the working set to zero */
1623 /* Swap the process out of physical RAM */
1625 return TRUE;
1628 /***********************************************************************
1629 * GetProcessWorkingSetSize (KERNEL32.@)
1631 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1632 LPDWORD maxset)
1634 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1635 /* 32 MB working set size */
1636 if (minset) *minset = 32*1024*1024;
1637 if (maxset) *maxset = 32*1024*1024;
1638 return TRUE;
1641 /***********************************************************************
1642 * SetProcessShutdownParameters (KERNEL32.@)
1644 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1645 * Now tracks changes made (but does not act on these changes)
1647 static DWORD shutdown_flags = 0;
1648 static DWORD shutdown_priority = 0x280;
1650 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1652 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1653 shutdown_flags = flags;
1654 shutdown_priority = level;
1655 return TRUE;
1659 /***********************************************************************
1660 * GetProcessShutdownParameters (KERNEL32.@)
1663 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1665 *lpdwLevel = shutdown_priority;
1666 *lpdwFlags = shutdown_flags;
1667 return TRUE;
1671 /***********************************************************************
1672 * SetProcessPriorityBoost (KERNEL32.@)
1674 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1676 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1677 /* Say we can do it. I doubt the program will notice that we don't. */
1678 return TRUE;
1682 /***********************************************************************
1683 * ReadProcessMemory (KERNEL32.@)
1685 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1686 LPDWORD bytes_read )
1688 DWORD res;
1690 SERVER_START_REQ( read_process_memory )
1692 req->handle = process;
1693 req->addr = (void *)addr;
1694 wine_server_set_reply( req, buffer, size );
1695 if ((res = wine_server_call_err( req ))) size = 0;
1697 SERVER_END_REQ;
1698 if (bytes_read) *bytes_read = size;
1699 return !res;
1703 /***********************************************************************
1704 * WriteProcessMemory (KERNEL32.@)
1706 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1707 LPDWORD bytes_written )
1709 static const int zero;
1710 unsigned int first_offset, last_offset, first_mask, last_mask;
1711 DWORD res;
1713 if (!size)
1715 SetLastError( ERROR_INVALID_PARAMETER );
1716 return FALSE;
1719 /* compute the mask for the first int */
1720 first_mask = ~0;
1721 first_offset = (unsigned int)addr % sizeof(int);
1722 memset( &first_mask, 0, first_offset );
1724 /* compute the mask for the last int */
1725 last_offset = (size + first_offset) % sizeof(int);
1726 last_mask = 0;
1727 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1729 SERVER_START_REQ( write_process_memory )
1731 req->handle = process;
1732 req->addr = (char *)addr - first_offset;
1733 req->first_mask = first_mask;
1734 req->last_mask = last_mask;
1735 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1736 wine_server_add_data( req, buffer, size );
1737 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1739 if ((res = wine_server_call_err( req ))) size = 0;
1741 SERVER_END_REQ;
1742 if (bytes_written) *bytes_written = size;
1744 char dummy[32];
1745 DWORD read;
1746 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1748 return !res;
1752 /***********************************************************************
1753 * RegisterServiceProcess (KERNEL.491)
1754 * RegisterServiceProcess (KERNEL32.@)
1756 * A service process calls this function to ensure that it continues to run
1757 * even after a user logged off.
1759 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1761 /* I don't think that Wine needs to do anything in that function */
1762 return 1; /* success */
1765 /***********************************************************************
1766 * GetExitCodeProcess [KERNEL32.@]
1768 * Gets termination status of specified process
1770 * RETURNS
1771 * Success: TRUE
1772 * Failure: FALSE
1774 BOOL WINAPI GetExitCodeProcess(
1775 HANDLE hProcess, /* [in] handle to the process */
1776 LPDWORD lpExitCode) /* [out] address to receive termination status */
1778 BOOL ret;
1779 SERVER_START_REQ( get_process_info )
1781 req->handle = hProcess;
1782 ret = !wine_server_call_err( req );
1783 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1785 SERVER_END_REQ;
1786 return ret;
1790 /***********************************************************************
1791 * SetErrorMode (KERNEL32.@)
1793 UINT WINAPI SetErrorMode( UINT mode )
1795 UINT old = current_process.error_mode;
1796 current_process.error_mode = mode;
1797 return old;
1801 /**************************************************************************
1802 * SetFileApisToOEM (KERNEL32.@)
1804 VOID WINAPI SetFileApisToOEM(void)
1806 current_process.flags |= PDB32_FILE_APIS_OEM;
1810 /**************************************************************************
1811 * SetFileApisToANSI (KERNEL32.@)
1813 VOID WINAPI SetFileApisToANSI(void)
1815 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1819 /******************************************************************************
1820 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1822 * RETURNS
1823 * TRUE: Set of file functions is using ANSI code page
1824 * FALSE: Set of file functions is using OEM code page
1826 BOOL WINAPI AreFileApisANSI(void)
1828 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1832 /***********************************************************************
1833 * GetTickCount (KERNEL32.@)
1835 * Returns the number of milliseconds, modulo 2^32, since the start
1836 * of the wineserver.
1838 DWORD WINAPI GetTickCount(void)
1840 struct timeval t;
1841 gettimeofday( &t, NULL );
1842 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1846 /**********************************************************************
1847 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1849 * Allocates a thread local storage index
1851 * RETURNS
1852 * Success: TLS Index
1853 * Failure: 0xFFFFFFFF
1855 DWORD WINAPI TlsAlloc( void )
1857 DWORD i, mask, ret = 0;
1858 DWORD *bits = current_process.tls_bits;
1859 RtlAcquirePebLock();
1860 if (*bits == 0xffffffff)
1862 bits++;
1863 ret = 32;
1864 if (*bits == 0xffffffff)
1866 RtlReleasePebLock();
1867 SetLastError( ERROR_NO_MORE_ITEMS );
1868 return 0xffffffff;
1871 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1872 *bits |= mask;
1873 RtlReleasePebLock();
1874 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1875 return ret + i;
1879 /**********************************************************************
1880 * TlsFree [KERNEL32.@] Releases a TLS index.
1882 * Releases a thread local storage index, making it available for reuse
1884 * RETURNS
1885 * Success: TRUE
1886 * Failure: FALSE
1888 BOOL WINAPI TlsFree(
1889 DWORD index) /* [in] TLS Index to free */
1891 DWORD mask = (1 << (index & 31));
1892 DWORD *bits = current_process.tls_bits;
1893 if (index >= 64)
1895 SetLastError( ERROR_INVALID_PARAMETER );
1896 return FALSE;
1898 if (index >= 32) bits++;
1899 RtlAcquirePebLock();
1900 if (!(*bits & mask)) /* already free? */
1902 RtlReleasePebLock();
1903 SetLastError( ERROR_INVALID_PARAMETER );
1904 return FALSE;
1906 *bits &= ~mask;
1907 NtCurrentTeb()->tls_array[index] = 0;
1908 /* FIXME: should zero all other thread values */
1909 RtlReleasePebLock();
1910 return TRUE;
1914 /**********************************************************************
1915 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1917 * RETURNS
1918 * Success: Value stored in calling thread's TLS slot for index
1919 * Failure: 0 and GetLastError returns NO_ERROR
1921 LPVOID WINAPI TlsGetValue(
1922 DWORD index) /* [in] TLS index to retrieve value for */
1924 if (index >= 64)
1926 SetLastError( ERROR_INVALID_PARAMETER );
1927 return NULL;
1929 SetLastError( ERROR_SUCCESS );
1930 return NtCurrentTeb()->tls_array[index];
1934 /**********************************************************************
1935 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1937 * RETURNS
1938 * Success: TRUE
1939 * Failure: FALSE
1941 BOOL WINAPI TlsSetValue(
1942 DWORD index, /* [in] TLS index to set value for */
1943 LPVOID value) /* [in] Value to be stored */
1945 if (index >= 64)
1947 SetLastError( ERROR_INVALID_PARAMETER );
1948 return FALSE;
1950 NtCurrentTeb()->tls_array[index] = value;
1951 return TRUE;
1955 /***********************************************************************
1956 * GetCurrentProcess (KERNEL32.@)
1958 #undef GetCurrentProcess
1959 HANDLE WINAPI GetCurrentProcess(void)
1961 return (HANDLE)0xffffffff;