Throw exception only for Wine internal locks.
[wine/gsoc_dplay.git] / scheduler / process.c
blob3d351419807b508b508ec37172dc0746c97248cb
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 #include <unistd.h>
33 #include "wine/winbase16.h"
34 #include "wine/winuser16.h"
35 #include "wine/exception.h"
36 #include "wine/library.h"
37 #include "drive.h"
38 #include "module.h"
39 #include "file.h"
40 #include "heap.h"
41 #include "thread.h"
42 #include "winerror.h"
43 #include "wincon.h"
44 #include "wine/server.h"
45 #include "options.h"
46 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(process);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
50 WINE_DECLARE_DEBUG_CHANNEL(snoop);
51 WINE_DECLARE_DEBUG_CHANNEL(win32);
53 struct _ENVDB;
55 /* Win32 process database */
56 typedef struct _PDB
58 LONG header[2]; /* 00 Kernel object header */
59 HMODULE module; /* 08 Main exe module (NT) */
60 void *event; /* 0c Pointer to an event object (unused) */
61 DWORD exit_code; /* 10 Process exit code */
62 DWORD unknown2; /* 14 Unknown */
63 HANDLE heap; /* 18 Default process heap */
64 HANDLE mem_context; /* 1c Process memory context */
65 DWORD flags; /* 20 Flags */
66 void *pdb16; /* 24 DOS PSP */
67 WORD PSP_sel; /* 28 Selector to DOS PSP */
68 WORD imte; /* 2a IMTE for the process module */
69 WORD threads; /* 2c Number of threads */
70 WORD running_threads; /* 2e Number of running threads */
71 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
72 WORD ring0_threads; /* 32 Number of ring 0 threads */
73 HANDLE system_heap; /* 34 System heap to allocate handles */
74 HTASK task; /* 38 Win16 task */
75 void *mem_map_files; /* 3c Pointer to mem-mapped files */
76 struct _ENVDB *env_db; /* 40 Environment database */
77 void *handle_table; /* 44 Handle table */
78 struct _PDB *parent; /* 48 Parent process */
79 void *modref_list; /* 4c MODREF list */
80 void *thread_list; /* 50 List of threads */
81 void *debuggee_CB; /* 54 Debuggee context block */
82 void *local_heap_free; /* 58 Head of local heap free list */
83 DWORD unknown4; /* 5c Unknown */
84 CRITICAL_SECTION crit_section; /* 60 Critical section */
85 DWORD unknown5[3]; /* 78 Unknown */
86 void *console; /* 84 Console */
87 DWORD tls_bits[2]; /* 88 TLS in-use bits */
88 DWORD process_dword; /* 90 Unknown */
89 struct _PDB *group; /* 94 Process group */
90 void *exe_modref; /* 98 MODREF for the process EXE */
91 void *top_filter; /* 9c Top exception filter */
92 DWORD priority; /* a0 Priority level */
93 HANDLE heap_list; /* a4 Head of process heap list */
94 void *heap_handles; /* a8 Head of heap handles list */
95 DWORD unknown6; /* ac Unknown */
96 void *console_provider; /* b0 Console provider (??) */
97 WORD env_selector; /* b4 Selector to process environment */
98 WORD error_mode; /* b6 Error mode */
99 HANDLE load_done_evt; /* b8 Event for process loading done */
100 void *UTState; /* bc Head of Univeral Thunk list */
101 DWORD unknown8; /* c0 Unknown (NT) */
102 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
103 } PDB;
105 PDB current_process;
107 /* Process flags */
108 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
109 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
110 #define PDB32_DOS_PROC 0x0010 /* Dos process */
111 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
112 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
113 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
115 static char main_exe_name[MAX_PATH];
116 static char *main_exe_name_ptr = main_exe_name;
117 static HANDLE main_exe_file;
118 static unsigned int server_startticks;
120 int main_create_flags = 0;
122 /* memory/environ.c */
123 extern struct _ENVDB *ENV_InitStartupInfo( size_t info_size, char *main_exe_name,
124 size_t main_exe_size );
125 extern BOOL ENV_BuildCommandLine( char **argv );
126 extern STARTUPINFOA current_startupinfo;
128 /* scheduler/pthread.c */
129 extern void PTHREAD_init_done(void);
131 extern void RELAY_InitDebugLists(void);
132 extern BOOL MAIN_MainInit(void);
134 typedef WORD (WINAPI *pUserSignalProc)( UINT, DWORD, DWORD, HMODULE16 );
136 /***********************************************************************
137 * PROCESS_CallUserSignalProc
139 * FIXME: Some of the signals aren't sent correctly!
141 * The exact meaning of the USER signals is undocumented, but this
142 * should cover the basic idea:
144 * USIG_DLL_UNLOAD_WIN16
145 * This is sent when a 16-bit module is unloaded.
147 * USIG_DLL_UNLOAD_WIN32
148 * This is sent when a 32-bit module is unloaded.
150 * USIG_DLL_UNLOAD_ORPHANS
151 * This is sent after the last Win3.1 module is unloaded,
152 * to allow removal of orphaned menus.
154 * USIG_FAULT_DIALOG_PUSH
155 * USIG_FAULT_DIALOG_POP
156 * These are called to allow USER to prepare for displaying a
157 * fault dialog, even though the fault might have happened while
158 * inside a USER critical section.
160 * USIG_THREAD_INIT
161 * This is called from the context of a new thread, as soon as it
162 * has started to run.
164 * USIG_THREAD_EXIT
165 * This is called, still in its context, just before a thread is
166 * about to terminate.
168 * USIG_PROCESS_CREATE
169 * This is called, in the parent process context, after a new process
170 * has been created.
172 * USIG_PROCESS_INIT
173 * This is called in the new process context, just after the main thread
174 * has started execution (after the main thread's USIG_THREAD_INIT has
175 * been sent).
177 * USIG_PROCESS_LOADED
178 * This is called after the executable file has been loaded into the
179 * new process context.
181 * USIG_PROCESS_RUNNING
182 * This is called immediately before the main entry point is called.
184 * USIG_PROCESS_EXIT
185 * This is called in the context of a process that is about to
186 * terminate (but before the last thread's USIG_THREAD_EXIT has
187 * been sent).
189 * USIG_PROCESS_DESTROY
190 * This is called after a process has terminated.
193 * The meaning of the dwFlags bits is as follows:
195 * USIG_FLAGS_WIN32
196 * Current process is 32-bit.
198 * USIG_FLAGS_GUI
199 * Current process is a (Win32) GUI process.
201 * USIG_FLAGS_FEEDBACK
202 * Current process needs 'feedback' (determined from the STARTUPINFO
203 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
205 * USIG_FLAGS_FAULT
206 * The signal is being sent due to a fault.
208 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
210 DWORD dwFlags = 0;
211 HMODULE user;
212 pUserSignalProc proc;
214 if (!(user = GetModuleHandleA( "user32.dll" ))) return;
215 if (!(proc = (pUserSignalProc)GetProcAddress( user, "UserSignalProc" ))) return;
217 /* Determine dwFlags */
219 if ( !(current_process.flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
220 if ( !(current_process.flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
222 if ( dwFlags & USIG_FLAGS_GUI )
224 /* Feedback defaults to ON */
225 if ( !(current_startupinfo.dwFlags & STARTF_FORCEOFFFEEDBACK) )
226 dwFlags |= USIG_FLAGS_FEEDBACK;
228 else
230 /* Feedback defaults to OFF */
231 if (current_startupinfo.dwFlags & STARTF_FORCEONFEEDBACK)
232 dwFlags |= USIG_FLAGS_FEEDBACK;
235 /* Call USER signal proc */
237 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
238 proc( uCode, GetCurrentThreadId(), dwFlags, hModule );
239 else
240 proc( uCode, GetCurrentProcessId(), dwFlags, hModule );
244 /***********************************************************************
245 * get_basename
247 inline static const char *get_basename( const char *name )
249 char *p;
251 if ((p = strrchr( name, '/' ))) name = p + 1;
252 if ((p = strrchr( name, '\\' ))) name = p + 1;
253 return name;
257 /***********************************************************************
258 * open_exe_file
260 * Open an exe file, taking load order into account.
261 * Returns the file handle or 0 for a builtin exe.
263 static HANDLE open_exe_file( const char *name )
265 enum loadorder_type loadorder[LOADORDER_NTYPES];
266 HANDLE handle;
267 int i;
269 SetLastError( ERROR_FILE_NOT_FOUND );
270 MODULE_GetLoadOrder( loadorder, name, TRUE );
272 for(i = 0; i < LOADORDER_NTYPES; i++)
274 if (loadorder[i] == LOADORDER_INVALID) break;
275 switch(loadorder[i])
277 case LOADORDER_DLL:
278 TRACE( "Trying native exe %s\n", debugstr_a(name) );
279 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
280 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
281 return handle;
282 if (GetLastError() != ERROR_FILE_NOT_FOUND) return INVALID_HANDLE_VALUE;
283 break;
284 case LOADORDER_BI:
285 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
286 if (wine_dll_load_main_exe( get_basename(name), NULL, 0, 1 )) return 0;
287 break;
288 default:
289 break;
292 return INVALID_HANDLE_VALUE;
296 /***********************************************************************
297 * find_exe_file
299 * Open an exe file, and return the full name and file handle.
300 * Returns FALSE if file could not be found.
301 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
302 * If file is a builtin exe, returns TRUE and sets handle to 0.
304 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
306 enum loadorder_type loadorder[LOADORDER_NTYPES];
307 int i;
309 TRACE("looking for %s\n", debugstr_a(name) );
311 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ))
313 *handle = open_exe_file( buffer );
314 return TRUE;
317 /* no such file in path, try builtin with .exe extension */
319 lstrcpynA( buffer, get_basename(name), buflen );
320 if (!strchr( buffer, '.' ))
322 char *p = buffer + strlen(buffer);
323 lstrcpynA( p, ".exe", buflen - (p - buffer) );
326 MODULE_GetLoadOrder( loadorder, buffer, TRUE );
327 for (i = 0; i < LOADORDER_NTYPES; i++)
329 if (loadorder[i] == LOADORDER_BI)
331 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
332 if (wine_dll_load_main_exe( buffer, NULL, 0, 1 ))
334 *handle = 0;
335 return TRUE;
337 break;
339 if (loadorder[i] == LOADORDER_INVALID) break;
342 /* no builtin found, try native without extension in case it is a Unix app */
344 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
346 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
347 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
348 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
349 return TRUE;
351 return FALSE;
355 /***********************************************************************
356 * process_init
358 * Main process initialisation code
360 static BOOL process_init( char *argv[] )
362 BOOL ret;
363 size_t info_size = 0;
365 /* store the program name */
366 argv0 = argv[0];
368 /* Fill the initial process structure */
369 current_process.exit_code = STILL_ACTIVE;
370 current_process.threads = 1;
371 current_process.running_threads = 1;
372 current_process.ring0_threads = 1;
373 current_process.group = &current_process;
374 current_process.priority = 8; /* Normal */
376 /* Setup the server connection */
377 CLIENT_InitServer();
379 /* Retrieve startup info from the server */
380 SERVER_START_REQ( init_process )
382 req->ldt_copy = &wine_ldt_copy;
383 req->ppid = getppid();
384 if ((ret = !wine_server_call_err( req )))
386 main_exe_file = reply->exe_file;
387 main_create_flags = reply->create_flags;
388 info_size = reply->info_size;
389 server_startticks = reply->server_start;
390 current_startupinfo.hStdInput = reply->hstdin;
391 current_startupinfo.hStdOutput = reply->hstdout;
392 current_startupinfo.hStdError = reply->hstderr;
395 SERVER_END_REQ;
396 if (!ret) return FALSE;
398 /* Create the process heap */
399 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
401 if (main_create_flags == 0 &&
402 current_startupinfo.hStdInput == 0 &&
403 current_startupinfo.hStdOutput == 0 &&
404 current_startupinfo.hStdError == 0)
406 /* no parent, and no new console requested, create a simple console with bare handles to
407 * unix stdio input & output streams (aka simple console)
409 HANDLE handle;
410 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &handle );
411 SetStdHandle( STD_INPUT_HANDLE, handle );
412 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
413 SetStdHandle( STD_OUTPUT_HANDLE, handle );
414 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
415 SetStdHandle( STD_ERROR_HANDLE, handle );
417 else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
419 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
420 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
421 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
424 /* Now we can use the pthreads routines */
425 PTHREAD_init_done();
427 /* Copy the parent environment */
428 if (!(current_process.env_db = ENV_InitStartupInfo( info_size, main_exe_name,
429 sizeof(main_exe_name) )))
430 return FALSE;
432 /* Parse command line arguments */
433 OPTIONS_ParseOptions( !info_size ? argv : NULL );
435 ret = MAIN_MainInit();
436 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
438 return ret;
442 /***********************************************************************
443 * start_process
445 * Startup routine of a new process. Runs on the new process stack.
447 static void start_process(void)
449 int debugged, console_app;
450 LPTHREAD_START_ROUTINE entry;
451 WINE_MODREF *wm;
452 HANDLE main_file = main_exe_file;
453 IMAGE_NT_HEADERS *nt;
455 /* use original argv[0] as name for the main module */
456 if (!main_exe_name[0])
458 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
459 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
462 if (main_file)
464 UINT drive_type = GetDriveTypeA( main_exe_name );
465 /* don't keep the file handle open on removable media */
466 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
469 /* Retrieve entry point address */
470 nt = RtlImageNtHeader( current_process.module );
471 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
472 nt->OptionalHeader.AddressOfEntryPoint);
473 console_app = (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
474 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
476 /* Signal the parent process to continue */
477 SERVER_START_REQ( init_process_done )
479 req->module = (void *)current_process.module;
480 req->module_size = nt->OptionalHeader.SizeOfImage;
481 req->entry = entry;
482 /* API requires a double indirection */
483 req->name = &main_exe_name_ptr;
484 req->exe_file = main_file;
485 req->gui = !console_app;
486 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
487 wine_server_call( req );
488 debugged = reply->debugged;
490 SERVER_END_REQ;
492 /* Install signal handlers; this cannot be done before, since we cannot
493 * send exceptions to the debugger before the create process event that
494 * is sent by REQ_INIT_PROCESS_DONE */
495 if (!SIGNAL_Init()) goto error;
497 /* create the main modref and load dependencies */
498 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
499 goto error;
500 wm->refCount++;
502 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
504 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
506 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
507 * context of the parent process. Actually, the USER signal proc
508 * doesn't really care about that, but it *does* require that the
509 * startup parameters are correctly set up, so that GetProcessDword
510 * works. Furthermore, before calling the USER signal proc the
511 * 16-bit stack must be set up, which it is only after TASK_Create
512 * in the case of a 16-bit process. Thus, we send the signal here.
514 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
515 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
516 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
517 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
518 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
519 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
521 if (TRACE_ON(relay))
522 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
523 GetCurrentThreadId(), main_exe_name, entry );
524 if (debugged) DbgBreakPoint();
525 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
526 * Dunno about other OSs */
527 SetLastError(0); /* clear error code */
528 ExitThread( entry(NULL) );
530 error:
531 ExitProcess( GetLastError() );
535 /***********************************************************************
536 * PROCESS_InitWine
538 * Wine initialisation: load and start the main exe file.
540 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
542 char error[100], *p;
543 DWORD stack_size = 0;
545 /* Initialize everything */
546 if (!process_init( argv )) exit(1);
548 argv++; /* remove argv[0] (wine itself) */
550 TRACE( "starting process name=%s file=%x argv[0]=%s\n",
551 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
553 if (!main_exe_name[0])
555 if (!argv[0]) OPTIONS_Usage();
557 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
559 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
560 ExitProcess(1);
562 if (main_exe_file == INVALID_HANDLE_VALUE)
564 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
565 ExitProcess(1);
569 if (!main_exe_file) /* no file handle -> Winelib app */
571 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
572 if (wine_dll_load_main_exe( get_basename(main_exe_name), error, sizeof(error), 0 ))
573 goto found;
574 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
575 ExitProcess(1);
578 switch( MODULE_GetBinaryType( main_exe_file ))
580 case BINARY_PE_EXE:
581 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
582 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
583 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
584 ExitProcess(1);
585 case BINARY_PE_DLL:
586 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
587 ExitProcess(1);
588 case BINARY_UNKNOWN:
589 /* check for .com extension */
590 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
592 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
593 ExitProcess(1);
595 /* fall through */
596 case BINARY_WIN16:
597 case BINARY_DOS:
598 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
599 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
600 current_process.flags |= PDB32_WIN16_PROC;
601 strcpy( win16_exe_name, main_exe_name );
602 main_exe_name[0] = 0;
603 *win16_exe_file = main_exe_file;
604 main_exe_file = 0;
605 _EnterWin16Lock();
606 goto found;
607 case BINARY_OS216:
608 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
609 ExitProcess(1);
610 case BINARY_UNIX_EXE:
611 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
612 ExitProcess(1);
613 case BINARY_UNIX_LIB:
615 DOS_FULL_NAME full_name;
616 const char *name = main_exe_name;
618 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
619 if (DOSFS_GetFullName( name, TRUE, &full_name )) name = full_name.long_name;
620 CloseHandle( main_exe_file );
621 main_exe_file = 0;
622 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
624 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
625 goto found;
627 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
628 ExitProcess(1);
632 found:
633 /* build command line */
634 if (!ENV_BuildCommandLine( argv )) goto error;
636 /* create 32-bit module for main exe */
637 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
638 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
640 /* allocate main thread stack */
641 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
643 /* switch to the new stack */
644 SYSDEPS_SwitchToThreadStack( start_process );
646 error:
647 ExitProcess( GetLastError() );
651 /***********************************************************************
652 * build_argv
654 * Build an argv array from a command-line.
655 * The command-line is modified to insert nulls.
656 * 'reserved' is the number of args to reserve before the first one.
658 static char **build_argv( char *cmdline, int reserved )
660 int argc;
661 char** argv;
662 char *arg,*s,*d;
663 int in_quotes,bcount;
665 argc=reserved+1;
666 bcount=0;
667 in_quotes=0;
668 s=cmdline;
669 while (1) {
670 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
671 /* space */
672 argc++;
673 /* skip the remaining spaces */
674 while (*s==' ' || *s=='\t') {
675 s++;
677 if (*s=='\0')
678 break;
679 bcount=0;
680 continue;
681 } else if (*s=='\\') {
682 /* '\', count them */
683 bcount++;
684 } else if ((*s=='"') && ((bcount & 1)==0)) {
685 /* unescaped '"' */
686 in_quotes=!in_quotes;
687 bcount=0;
688 } else {
689 /* a regular character */
690 bcount=0;
692 s++;
694 argv=malloc(argc*sizeof(*argv));
695 if (!argv)
696 return NULL;
698 arg=d=s=cmdline;
699 bcount=0;
700 in_quotes=0;
701 argc=reserved;
702 while (*s) {
703 if ((*s==' ' || *s=='\t') && !in_quotes) {
704 /* Close the argument and copy it */
705 *d=0;
706 argv[argc++]=arg;
708 /* skip the remaining spaces */
709 do {
710 s++;
711 } while (*s==' ' || *s=='\t');
713 /* Start with a new argument */
714 arg=d=s;
715 bcount=0;
716 } else if (*s=='\\') {
717 /* '\\' */
718 *d++=*s++;
719 bcount++;
720 } else if (*s=='"') {
721 /* '"' */
722 if ((bcount & 1)==0) {
723 /* Preceeded by an even number of '\', this is half that
724 * number of '\', plus a '"' which we discard.
726 d-=bcount/2;
727 s++;
728 in_quotes=!in_quotes;
729 } else {
730 /* Preceeded by an odd number of '\', this is half that
731 * number of '\' followed by a '"'
733 d=d-bcount/2-1;
734 *d++='"';
735 s++;
737 bcount=0;
738 } else {
739 /* a regular character */
740 *d++=*s++;
741 bcount=0;
744 if (*arg) {
745 *d='\0';
746 argv[argc++]=arg;
748 argv[argc]=NULL;
750 return argv;
754 /***********************************************************************
755 * build_envp
757 * Build the environment of a new child process.
759 static char **build_envp( const char *env, const char *extra_env )
761 const char *p;
762 char **envp;
763 int count = 0;
765 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
766 for (p = env; *p; count++) p += strlen(p) + 1;
767 count += 3;
769 if ((envp = malloc( count * sizeof(*envp) )))
771 extern char **environ;
772 char **envptr = envp;
773 char **unixptr = environ;
774 /* first the extra strings */
775 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
776 /* then put PATH, HOME and WINEPREFIX from the unix env */
777 for (unixptr = environ; unixptr && *unixptr; unixptr++)
778 if (!memcmp( *unixptr, "PATH=", 5 ) ||
779 !memcmp( *unixptr, "HOME=", 5 ) ||
780 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
781 /* now put the Windows environment strings */
782 for (p = env; *p; p += strlen(p) + 1)
784 if (memcmp( p, "PATH=", 5 ) &&
785 memcmp( p, "HOME=", 5 ) &&
786 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
788 *envptr = 0;
790 return envp;
794 /***********************************************************************
795 * exec_wine_binary
797 * Locate the Wine binary to exec for a new Win32 process.
799 static void exec_wine_binary( char **argv, char **envp )
801 const char *path, *pos, *ptr;
803 /* first, try for a WINELOADER environment variable */
804 argv[0] = getenv("WINELOADER");
805 if (argv[0])
806 execve( argv[0], argv, envp );
808 /* next, try bin directory */
809 argv[0] = BINDIR "/wine";
810 execve( argv[0], argv, envp );
812 /* now try the path of argv0 of the current binary */
813 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
814 if ((ptr = strrchr( full_argv0, '/' )))
816 memcpy( argv[0], full_argv0, ptr - full_argv0 );
817 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
818 execve( argv[0], argv, envp );
820 free( argv[0] );
822 /* now search in the Unix path */
823 if ((path = getenv( "PATH" )))
825 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
826 pos = path;
827 for (;;)
829 while (*pos == ':') pos++;
830 if (!*pos) break;
831 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
832 memcpy( argv[0], pos, ptr - pos );
833 strcpy( argv[0] + (ptr - pos), "/wine" );
834 execve( argv[0], argv, envp );
835 pos = ptr;
838 free( argv[0] );
842 /***********************************************************************
843 * fork_and_exec
845 * Fork and exec a new Unix process, checking for errors.
847 static int fork_and_exec( const char *filename, char *cmdline,
848 const char *env, const char *newdir )
850 int fd[2];
851 int pid, err;
852 char *extra_env = NULL;
854 if (!env)
856 env = GetEnvironmentStringsA();
857 extra_env = DRIVE_BuildEnv();
860 if (pipe(fd) == -1)
862 FILE_SetDosError();
863 return -1;
865 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
866 if (!(pid = fork())) /* child */
868 char **argv = build_argv( cmdline, filename ? 0 : 1 );
869 char **envp = build_envp( env, extra_env );
870 close( fd[0] );
872 /* Reset signals that we previously set to SIG_IGN */
873 signal( SIGPIPE, SIG_DFL );
874 signal( SIGCHLD, SIG_DFL );
876 if (newdir) chdir(newdir);
878 if (argv && envp)
880 if (!filename) exec_wine_binary( argv, envp );
881 else execve( filename, argv, envp );
883 err = errno;
884 write( fd[1], &err, sizeof(err) );
885 _exit(1);
887 close( fd[1] );
888 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
890 errno = err;
891 pid = -1;
893 if (pid == -1) FILE_SetDosError();
894 close( fd[0] );
895 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
896 return pid;
900 /***********************************************************************
901 * create_process
903 * Create a new process. If hFile is a valid handle we have an exe
904 * file, otherwise it is a Winelib app.
906 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
907 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
908 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
909 LPPROCESS_INFORMATION info, LPCSTR unixdir )
911 BOOL ret, success = FALSE;
912 HANDLE process_info;
913 startup_info_t startup_info;
915 /* fill the startup info structure */
917 startup_info.size = sizeof(startup_info);
918 /* startup_info.filename_len is set below */
919 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
920 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
921 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
922 startup_info.x = startup->dwX;
923 startup_info.y = startup->dwY;
924 startup_info.cx = startup->dwXSize;
925 startup_info.cy = startup->dwYSize;
926 startup_info.x_chars = startup->dwXCountChars;
927 startup_info.y_chars = startup->dwYCountChars;
928 startup_info.attribute = startup->dwFillAttribute;
929 startup_info.cmd_show = startup->wShowWindow;
930 startup_info.flags = startup->dwFlags;
932 /* create the process on the server side */
934 SERVER_START_REQ( new_process )
936 char buf[MAX_PATH];
937 LPCSTR nameptr;
939 req->inherit_all = inherit;
940 req->create_flags = flags;
941 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
942 req->exe_file = hFile;
943 if (startup->dwFlags & STARTF_USESTDHANDLES)
945 req->hstdin = startup->hStdInput;
946 req->hstdout = startup->hStdOutput;
947 req->hstderr = startup->hStdError;
949 else
951 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
952 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
953 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
956 if (GetLongPathNameA( filename, buf, MAX_PATH ))
957 nameptr = buf;
958 else
959 nameptr = filename;
961 startup_info.filename_len = strlen(nameptr);
962 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
963 wine_server_add_data( req, nameptr, startup_info.filename_len );
964 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
965 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
966 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
968 ret = !wine_server_call_err( req );
969 process_info = reply->info;
971 SERVER_END_REQ;
972 if (!ret) return FALSE;
974 /* fork and execute */
976 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
978 CloseHandle( process_info );
979 return FALSE;
982 /* wait for the new process info to be ready */
984 WaitForSingleObject( process_info, INFINITE );
985 SERVER_START_REQ( get_new_process_info )
987 req->info = process_info;
988 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
989 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
990 if ((ret = !wine_server_call_err( req )))
992 info->dwProcessId = (DWORD)reply->pid;
993 info->dwThreadId = (DWORD)reply->tid;
994 info->hProcess = reply->phandle;
995 info->hThread = reply->thandle;
996 success = reply->success;
999 SERVER_END_REQ;
1001 if (ret && !success) /* new process failed to start */
1003 DWORD exitcode;
1004 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1005 CloseHandle( info->hThread );
1006 CloseHandle( info->hProcess );
1007 ret = FALSE;
1009 CloseHandle( process_info );
1010 return ret;
1014 /*************************************************************************
1015 * get_file_name
1017 * Helper for CreateProcess: retrieve the file name to load from the
1018 * app name and command line. Store the file name in buffer, and
1019 * return a possibly modified command line.
1020 * Also returns a handle to the opened file if it's a Windows binary.
1022 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1023 int buflen, HANDLE *handle )
1025 char *name, *pos, *ret = NULL;
1026 const char *p;
1028 /* if we have an app name, everything is easy */
1030 if (appname)
1032 /* use the unmodified app name as file name */
1033 lstrcpynA( buffer, appname, buflen );
1034 *handle = open_exe_file( buffer );
1035 if (!(ret = cmdline))
1037 /* no command-line, create one */
1038 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1039 sprintf( ret, "\"%s\"", appname );
1041 return ret;
1044 if (!cmdline)
1046 SetLastError( ERROR_INVALID_PARAMETER );
1047 return NULL;
1050 /* first check for a quoted file name */
1052 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1054 int len = p - cmdline - 1;
1055 /* extract the quoted portion as file name */
1056 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1057 memcpy( name, cmdline + 1, len );
1058 name[len] = 0;
1060 if (find_exe_file( name, buffer, buflen, handle ))
1061 ret = cmdline; /* no change necessary */
1062 goto done;
1065 /* now try the command-line word by word */
1067 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1068 pos = name;
1069 p = cmdline;
1071 while (*p)
1073 do *pos++ = *p++; while (*p && *p != ' ');
1074 *pos = 0;
1075 if (find_exe_file( name, buffer, buflen, handle ))
1077 ret = cmdline;
1078 break;
1082 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1084 /* now build a new command-line with quotes */
1086 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1087 sprintf( ret, "\"%s\"%s", name, p );
1089 done:
1090 HeapFree( GetProcessHeap(), 0, name );
1091 return ret;
1095 /**********************************************************************
1096 * CreateProcessA (KERNEL32.@)
1098 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1099 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1100 DWORD flags, LPVOID env, LPCSTR cur_dir,
1101 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1103 BOOL retv = FALSE;
1104 HANDLE hFile = 0;
1105 const char *unixdir = NULL;
1106 DOS_FULL_NAME full_dir;
1107 char name[MAX_PATH];
1108 LPSTR tidy_cmdline;
1109 char *p;
1111 /* Process the AppName and/or CmdLine to get module name and path */
1113 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1115 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1116 return FALSE;
1117 if (hFile == INVALID_HANDLE_VALUE) goto done;
1119 /* Warn if unsupported features are used */
1121 if (flags & NORMAL_PRIORITY_CLASS)
1122 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1123 if (flags & IDLE_PRIORITY_CLASS)
1124 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1125 if (flags & HIGH_PRIORITY_CLASS)
1126 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1127 if (flags & REALTIME_PRIORITY_CLASS)
1128 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1129 if (flags & CREATE_NEW_PROCESS_GROUP)
1130 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1131 if (flags & CREATE_UNICODE_ENVIRONMENT)
1132 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1133 if (flags & CREATE_SEPARATE_WOW_VDM)
1134 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1135 if (flags & CREATE_SHARED_WOW_VDM)
1136 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1137 if (flags & CREATE_DEFAULT_ERROR_MODE)
1138 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1139 if (flags & CREATE_NO_WINDOW)
1140 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1141 if (flags & PROFILE_USER)
1142 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1143 if (flags & PROFILE_KERNEL)
1144 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1145 if (flags & PROFILE_SERVER)
1146 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1147 if (startup_info->lpDesktop)
1148 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1149 name, debugstr_a(startup_info->lpDesktop));
1150 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1151 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1152 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1153 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1154 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1155 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1156 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1157 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1159 if (cur_dir)
1161 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir ))
1162 unixdir = full_dir.long_name;
1164 else
1166 char buf[MAX_PATH];
1167 if (GetCurrentDirectoryA(sizeof(buf),buf))
1169 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1173 info->hThread = info->hProcess = 0;
1174 info->dwProcessId = info->dwThreadId = 0;
1176 /* Determine executable type */
1178 if (!hFile) /* builtin exe */
1180 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1181 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1182 inherit, flags, startup_info, info, unixdir );
1183 goto done;
1186 switch( MODULE_GetBinaryType( hFile ))
1188 case BINARY_PE_EXE:
1189 case BINARY_WIN16:
1190 case BINARY_DOS:
1191 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1192 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1193 inherit, flags, startup_info, info, unixdir );
1194 break;
1195 case BINARY_OS216:
1196 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1197 SetLastError( ERROR_BAD_EXE_FORMAT );
1198 break;
1199 case BINARY_PE_DLL:
1200 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1201 SetLastError( ERROR_BAD_EXE_FORMAT );
1202 break;
1203 case BINARY_UNIX_LIB:
1204 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1205 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1206 inherit, flags, startup_info, info, unixdir );
1207 break;
1208 case BINARY_UNKNOWN:
1209 /* check for .com extension */
1210 if ((p = strrchr( name, '.' )) && !FILE_strcasecmp( p, ".com" ))
1212 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1213 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1214 inherit, flags, startup_info, info, unixdir );
1215 break;
1217 /* fall through */
1218 case BINARY_UNIX_EXE:
1220 DOS_FULL_NAME full_name;
1221 const char *unixfilename = name;
1223 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1224 if (DOSFS_GetFullName( name, TRUE, &full_name )) unixfilename = full_name.long_name;
1225 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1227 break;
1229 CloseHandle( hFile );
1231 done:
1232 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1233 return retv;
1237 /**********************************************************************
1238 * CreateProcessW (KERNEL32.@)
1239 * NOTES
1240 * lpReserved is not converted
1242 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1243 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1244 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1245 LPPROCESS_INFORMATION info )
1247 BOOL ret;
1248 STARTUPINFOA StartupInfoA;
1250 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1251 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1252 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1254 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1255 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1256 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1258 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1260 if (startup_info->lpReserved)
1261 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1262 debugstr_w(startup_info->lpReserved));
1264 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1265 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1267 HeapFree( GetProcessHeap(), 0, cur_dirA );
1268 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1269 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1270 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1272 return ret;
1276 /***********************************************************************
1277 * ExitProcess (KERNEL32.@)
1279 void WINAPI ExitProcess( DWORD status )
1281 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1282 SERVER_START_REQ( terminate_process )
1284 /* send the exit code to the server */
1285 req->handle = GetCurrentProcess();
1286 req->exit_code = status;
1287 wine_server_call( req );
1289 SERVER_END_REQ;
1290 exit( status );
1293 /***********************************************************************
1294 * ExitProcess (KERNEL.466)
1296 void WINAPI ExitProcess16( WORD status )
1298 DWORD count;
1299 ReleaseThunkLock( &count );
1300 ExitProcess( status );
1303 /******************************************************************************
1304 * TerminateProcess (KERNEL32.@)
1306 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1308 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1309 if (status) SetLastError( RtlNtStatusToDosError(status) );
1310 return !status;
1314 /***********************************************************************
1315 * GetProcessDword (KERNEL.485)
1316 * GetProcessDword (KERNEL32.18)
1317 * 'Of course you cannot directly access Windows internal structures'
1319 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1321 DWORD x, y;
1323 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1325 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1327 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1328 return 0;
1331 switch ( offset )
1333 case GPD_APP_COMPAT_FLAGS:
1334 return GetAppCompatFlags16(0);
1336 case GPD_LOAD_DONE_EVENT:
1337 return (DWORD)current_process.load_done_evt;
1339 case GPD_HINSTANCE16:
1340 return GetTaskDS16();
1342 case GPD_WINDOWS_VERSION:
1343 return GetExeVersion16();
1345 case GPD_THDB:
1346 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1348 case GPD_PDB:
1349 return (DWORD)&current_process;
1351 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1352 return (DWORD)current_startupinfo.hStdOutput;
1354 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1355 return (DWORD)current_startupinfo.hStdInput;
1357 case GPD_STARTF_SHOWWINDOW:
1358 return current_startupinfo.wShowWindow;
1360 case GPD_STARTF_SIZE:
1361 x = current_startupinfo.dwXSize;
1362 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1363 y = current_startupinfo.dwYSize;
1364 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1365 return MAKELONG( x, y );
1367 case GPD_STARTF_POSITION:
1368 x = current_startupinfo.dwX;
1369 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1370 y = current_startupinfo.dwY;
1371 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1372 return MAKELONG( x, y );
1374 case GPD_STARTF_FLAGS:
1375 return current_startupinfo.dwFlags;
1377 case GPD_PARENT:
1378 return 0;
1380 case GPD_FLAGS:
1381 return current_process.flags;
1383 case GPD_USERDATA:
1384 return current_process.process_dword;
1386 default:
1387 ERR_(win32)("Unknown offset %d\n", offset );
1388 return 0;
1392 /***********************************************************************
1393 * SetProcessDword (KERNEL.484)
1394 * 'Of course you cannot directly access Windows internal structures'
1396 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1398 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1400 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1402 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1403 return;
1406 switch ( offset )
1408 case GPD_APP_COMPAT_FLAGS:
1409 case GPD_LOAD_DONE_EVENT:
1410 case GPD_HINSTANCE16:
1411 case GPD_WINDOWS_VERSION:
1412 case GPD_THDB:
1413 case GPD_PDB:
1414 case GPD_STARTF_SHELLDATA:
1415 case GPD_STARTF_HOTKEY:
1416 case GPD_STARTF_SHOWWINDOW:
1417 case GPD_STARTF_SIZE:
1418 case GPD_STARTF_POSITION:
1419 case GPD_STARTF_FLAGS:
1420 case GPD_PARENT:
1421 case GPD_FLAGS:
1422 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1423 break;
1425 case GPD_USERDATA:
1426 current_process.process_dword = value;
1427 break;
1429 default:
1430 ERR_(win32)("Unknown offset %d\n", offset );
1431 break;
1436 /*********************************************************************
1437 * OpenProcess (KERNEL32.@)
1439 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1441 HANDLE ret = 0;
1442 SERVER_START_REQ( open_process )
1444 req->pid = (void *)id;
1445 req->access = access;
1446 req->inherit = inherit;
1447 if (!wine_server_call_err( req )) ret = reply->handle;
1449 SERVER_END_REQ;
1450 return ret;
1453 /*********************************************************************
1454 * MapProcessHandle (KERNEL.483)
1456 DWORD WINAPI MapProcessHandle( HANDLE handle )
1458 DWORD ret = 0;
1459 SERVER_START_REQ( get_process_info )
1461 req->handle = handle;
1462 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1464 SERVER_END_REQ;
1465 return ret;
1468 /***********************************************************************
1469 * SetPriorityClass (KERNEL32.@)
1471 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1473 BOOL ret;
1474 SERVER_START_REQ( set_process_info )
1476 req->handle = hprocess;
1477 req->priority = priorityclass;
1478 req->mask = SET_PROCESS_INFO_PRIORITY;
1479 ret = !wine_server_call_err( req );
1481 SERVER_END_REQ;
1482 return ret;
1486 /***********************************************************************
1487 * GetPriorityClass (KERNEL32.@)
1489 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1491 DWORD ret = 0;
1492 SERVER_START_REQ( get_process_info )
1494 req->handle = hprocess;
1495 if (!wine_server_call_err( req )) ret = reply->priority;
1497 SERVER_END_REQ;
1498 return ret;
1502 /***********************************************************************
1503 * SetProcessAffinityMask (KERNEL32.@)
1505 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1507 BOOL ret;
1508 SERVER_START_REQ( set_process_info )
1510 req->handle = hProcess;
1511 req->affinity = affmask;
1512 req->mask = SET_PROCESS_INFO_AFFINITY;
1513 ret = !wine_server_call_err( req );
1515 SERVER_END_REQ;
1516 return ret;
1519 /**********************************************************************
1520 * GetProcessAffinityMask (KERNEL32.@)
1522 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1523 LPDWORD lpProcessAffinityMask,
1524 LPDWORD lpSystemAffinityMask )
1526 BOOL ret = FALSE;
1527 SERVER_START_REQ( get_process_info )
1529 req->handle = hProcess;
1530 if (!wine_server_call_err( req ))
1532 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1533 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1534 ret = TRUE;
1537 SERVER_END_REQ;
1538 return ret;
1542 /***********************************************************************
1543 * GetProcessVersion (KERNEL32.@)
1545 DWORD WINAPI GetProcessVersion( DWORD processid )
1547 IMAGE_NT_HEADERS *nt;
1549 if (processid && processid != GetCurrentProcessId())
1551 FIXME("should use ReadProcessMemory\n");
1552 return 0;
1554 if ((nt = RtlImageNtHeader( current_process.module )))
1555 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1556 nt->OptionalHeader.MinorSubsystemVersion);
1557 return 0;
1560 /***********************************************************************
1561 * GetProcessFlags (KERNEL32.@)
1563 DWORD WINAPI GetProcessFlags( DWORD processid )
1565 if (processid && processid != GetCurrentProcessId()) return 0;
1566 return current_process.flags;
1570 /***********************************************************************
1571 * SetProcessWorkingSetSize [KERNEL32.@]
1572 * Sets the min/max working set sizes for a specified process.
1574 * PARAMS
1575 * hProcess [I] Handle to the process of interest
1576 * minset [I] Specifies minimum working set size
1577 * maxset [I] Specifies maximum working set size
1579 * RETURNS STD
1581 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1582 DWORD maxset)
1584 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1585 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1586 /* Trim the working set to zero */
1587 /* Swap the process out of physical RAM */
1589 return TRUE;
1592 /***********************************************************************
1593 * GetProcessWorkingSetSize (KERNEL32.@)
1595 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1596 LPDWORD maxset)
1598 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1599 /* 32 MB working set size */
1600 if (minset) *minset = 32*1024*1024;
1601 if (maxset) *maxset = 32*1024*1024;
1602 return TRUE;
1605 /***********************************************************************
1606 * SetProcessShutdownParameters (KERNEL32.@)
1608 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1609 * Now tracks changes made (but does not act on these changes)
1611 static DWORD shutdown_flags = 0;
1612 static DWORD shutdown_priority = 0x280;
1614 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1616 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1617 shutdown_flags = flags;
1618 shutdown_priority = level;
1619 return TRUE;
1623 /***********************************************************************
1624 * GetProcessShutdownParameters (KERNEL32.@)
1627 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1629 *lpdwLevel = shutdown_priority;
1630 *lpdwFlags = shutdown_flags;
1631 return TRUE;
1635 /***********************************************************************
1636 * SetProcessPriorityBoost (KERNEL32.@)
1638 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1640 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1641 /* Say we can do it. I doubt the program will notice that we don't. */
1642 return TRUE;
1646 /***********************************************************************
1647 * ReadProcessMemory (KERNEL32.@)
1649 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1650 LPDWORD bytes_read )
1652 DWORD res;
1654 SERVER_START_REQ( read_process_memory )
1656 req->handle = process;
1657 req->addr = (void *)addr;
1658 wine_server_set_reply( req, buffer, size );
1659 if ((res = wine_server_call_err( req ))) size = 0;
1661 SERVER_END_REQ;
1662 if (bytes_read) *bytes_read = size;
1663 return !res;
1667 /***********************************************************************
1668 * WriteProcessMemory (KERNEL32.@)
1670 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1671 LPDWORD bytes_written )
1673 static const int zero;
1674 unsigned int first_offset, last_offset, first_mask, last_mask;
1675 DWORD res;
1677 if (!size)
1679 SetLastError( ERROR_INVALID_PARAMETER );
1680 return FALSE;
1683 /* compute the mask for the first int */
1684 first_mask = ~0;
1685 first_offset = (unsigned int)addr % sizeof(int);
1686 memset( &first_mask, 0, first_offset );
1688 /* compute the mask for the last int */
1689 last_offset = (size + first_offset) % sizeof(int);
1690 last_mask = 0;
1691 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1693 SERVER_START_REQ( write_process_memory )
1695 req->handle = process;
1696 req->addr = (char *)addr - first_offset;
1697 req->first_mask = first_mask;
1698 req->last_mask = last_mask;
1699 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1700 wine_server_add_data( req, buffer, size );
1701 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1703 if ((res = wine_server_call_err( req ))) size = 0;
1705 SERVER_END_REQ;
1706 if (bytes_written) *bytes_written = size;
1708 char dummy[32];
1709 DWORD read;
1710 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1712 return !res;
1716 /***********************************************************************
1717 * RegisterServiceProcess (KERNEL.491)
1718 * RegisterServiceProcess (KERNEL32.@)
1720 * A service process calls this function to ensure that it continues to run
1721 * even after a user logged off.
1723 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1725 /* I don't think that Wine needs to do anything in that function */
1726 return 1; /* success */
1729 /***********************************************************************
1730 * GetExitCodeProcess [KERNEL32.@]
1732 * Gets termination status of specified process
1734 * RETURNS
1735 * Success: TRUE
1736 * Failure: FALSE
1738 BOOL WINAPI GetExitCodeProcess(
1739 HANDLE hProcess, /* [in] handle to the process */
1740 LPDWORD lpExitCode) /* [out] address to receive termination status */
1742 BOOL ret;
1743 SERVER_START_REQ( get_process_info )
1745 req->handle = hProcess;
1746 ret = !wine_server_call_err( req );
1747 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1749 SERVER_END_REQ;
1750 return ret;
1754 /***********************************************************************
1755 * SetErrorMode (KERNEL32.@)
1757 UINT WINAPI SetErrorMode( UINT mode )
1759 UINT old = current_process.error_mode;
1760 current_process.error_mode = mode;
1761 return old;
1765 /**************************************************************************
1766 * SetFileApisToOEM (KERNEL32.@)
1768 VOID WINAPI SetFileApisToOEM(void)
1770 current_process.flags |= PDB32_FILE_APIS_OEM;
1774 /**************************************************************************
1775 * SetFileApisToANSI (KERNEL32.@)
1777 VOID WINAPI SetFileApisToANSI(void)
1779 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1783 /******************************************************************************
1784 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1786 * RETURNS
1787 * TRUE: Set of file functions is using ANSI code page
1788 * FALSE: Set of file functions is using OEM code page
1790 BOOL WINAPI AreFileApisANSI(void)
1792 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1796 /***********************************************************************
1797 * GetTickCount (KERNEL32.@)
1799 * Returns the number of milliseconds, modulo 2^32, since the start
1800 * of the wineserver.
1802 DWORD WINAPI GetTickCount(void)
1804 struct timeval t;
1805 gettimeofday( &t, NULL );
1806 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1810 /**********************************************************************
1811 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1813 * Allocates a thread local storage index
1815 * RETURNS
1816 * Success: TLS Index
1817 * Failure: 0xFFFFFFFF
1819 DWORD WINAPI TlsAlloc( void )
1821 DWORD i, mask, ret = 0;
1822 DWORD *bits = current_process.tls_bits;
1823 RtlAcquirePebLock();
1824 if (*bits == 0xffffffff)
1826 bits++;
1827 ret = 32;
1828 if (*bits == 0xffffffff)
1830 RtlReleasePebLock();
1831 SetLastError( ERROR_NO_MORE_ITEMS );
1832 return 0xffffffff;
1835 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1836 *bits |= mask;
1837 RtlReleasePebLock();
1838 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1839 return ret + i;
1843 /**********************************************************************
1844 * TlsFree [KERNEL32.@] Releases a TLS index.
1846 * Releases a thread local storage index, making it available for reuse
1848 * RETURNS
1849 * Success: TRUE
1850 * Failure: FALSE
1852 BOOL WINAPI TlsFree(
1853 DWORD index) /* [in] TLS Index to free */
1855 DWORD mask = (1 << (index & 31));
1856 DWORD *bits = current_process.tls_bits;
1857 if (index >= 64)
1859 SetLastError( ERROR_INVALID_PARAMETER );
1860 return FALSE;
1862 if (index >= 32) bits++;
1863 RtlAcquirePebLock();
1864 if (!(*bits & mask)) /* already free? */
1866 RtlReleasePebLock();
1867 SetLastError( ERROR_INVALID_PARAMETER );
1868 return FALSE;
1870 *bits &= ~mask;
1871 NtCurrentTeb()->tls_array[index] = 0;
1872 /* FIXME: should zero all other thread values */
1873 RtlReleasePebLock();
1874 return TRUE;
1878 /**********************************************************************
1879 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1881 * RETURNS
1882 * Success: Value stored in calling thread's TLS slot for index
1883 * Failure: 0 and GetLastError returns NO_ERROR
1885 LPVOID WINAPI TlsGetValue(
1886 DWORD index) /* [in] TLS index to retrieve value for */
1888 if (index >= 64)
1890 SetLastError( ERROR_INVALID_PARAMETER );
1891 return NULL;
1893 SetLastError( ERROR_SUCCESS );
1894 return NtCurrentTeb()->tls_array[index];
1898 /**********************************************************************
1899 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1901 * RETURNS
1902 * Success: TRUE
1903 * Failure: FALSE
1905 BOOL WINAPI TlsSetValue(
1906 DWORD index, /* [in] TLS index to set value for */
1907 LPVOID value) /* [in] Value to be stored */
1909 if (index >= 64)
1911 SetLastError( ERROR_INVALID_PARAMETER );
1912 return FALSE;
1914 NtCurrentTeb()->tls_array[index] = value;
1915 return TRUE;
1919 /***********************************************************************
1920 * GetCurrentProcess (KERNEL32.@)
1922 #undef GetCurrentProcess
1923 HANDLE WINAPI GetCurrentProcess(void)
1925 return (HANDLE)0xffffffff;