- Move "questions and comments" at the top of the document.
[wine/testsucceed.git] / scheduler / process.c
blobe95812dd7e9d1be33d02fcdb6a5d5eca0546fb53
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 int main_create_flags;
120 static unsigned int server_startticks;
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 HFILE main_file = main_exe_file;
454 /* use original argv[0] as name for the main module */
455 if (!main_exe_name[0])
457 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
458 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
461 if (main_file)
463 UINT drive_type = GetDriveTypeA( main_exe_name );
464 /* don't keep the file handle open on removable media */
465 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
468 /* Retrieve entry point address */
469 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
470 PE_HEADER(current_process.module)->OptionalHeader.AddressOfEntryPoint);
471 console_app = (PE_HEADER(current_process.module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
472 if (console_app)
474 current_process.flags |= PDB32_CONSOLE_PROC;
475 if (main_create_flags & CREATE_NEW_CONSOLE) AllocConsole();
478 /* Signal the parent process to continue */
479 SERVER_START_REQ( init_process_done )
481 req->module = (void *)current_process.module;
482 req->module_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfImage;
483 req->entry = entry;
484 /* API requires a double indirection */
485 req->name = &main_exe_name_ptr;
486 req->exe_file = main_file;
487 req->gui = !console_app;
488 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
489 wine_server_call( req );
490 debugged = reply->debugged;
492 SERVER_END_REQ;
494 /* Install signal handlers; this cannot be done before, since we cannot
495 * send exceptions to the debugger before the create process event that
496 * is sent by REQ_INIT_PROCESS_DONE */
497 if (!SIGNAL_Init()) goto error;
499 /* create the main modref and load dependencies */
500 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
501 goto error;
502 wm->refCount++;
504 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
506 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
508 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
509 * context of the parent process. Actually, the USER signal proc
510 * doesn't really care about that, but it *does* require that the
511 * startup parameters are correctly set up, so that GetProcessDword
512 * works. Furthermore, before calling the USER signal proc the
513 * 16-bit stack must be set up, which it is only after TASK_Create
514 * in the case of a 16-bit process. Thus, we send the signal here.
516 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
517 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
518 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
519 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
520 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
521 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
523 if (TRACE_ON(relay))
524 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
525 GetCurrentThreadId(), main_exe_name, entry );
526 if (debugged) DbgBreakPoint();
527 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
528 * Dunno about other OSs */
529 SetLastError(0); /* clear error code */
530 ExitThread( entry(NULL) );
532 error:
533 ExitProcess( GetLastError() );
537 /***********************************************************************
538 * PROCESS_InitWine
540 * Wine initialisation: load and start the main exe file.
542 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
544 char error[100], *p;
545 DWORD stack_size = 0;
547 /* Initialize everything */
548 if (!process_init( argv )) exit(1);
550 argv++; /* remove argv[0] (wine itself) */
552 TRACE( "starting process name=%s file=%x argv[0]=%s\n",
553 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
555 if (!main_exe_name[0])
557 if (!argv[0]) OPTIONS_Usage();
559 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
561 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
562 ExitProcess(1);
564 if (main_exe_file == INVALID_HANDLE_VALUE)
566 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
567 ExitProcess(1);
571 if (!main_exe_file) /* no file handle -> Winelib app */
573 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
574 if (wine_dll_load_main_exe( get_basename(main_exe_name), error, sizeof(error), 0 ))
575 goto found;
576 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
577 ExitProcess(1);
580 switch( MODULE_GetBinaryType( main_exe_file ))
582 case BINARY_PE_EXE:
583 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
584 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
585 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
586 ExitProcess(1);
587 case BINARY_PE_DLL:
588 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
589 ExitProcess(1);
590 case BINARY_UNKNOWN:
591 /* check for .com extension */
592 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
594 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
595 ExitProcess(1);
597 /* fall through */
598 case BINARY_WIN16:
599 case BINARY_DOS:
600 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
601 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
602 current_process.flags |= PDB32_WIN16_PROC;
603 strcpy( win16_exe_name, main_exe_name );
604 main_exe_name[0] = 0;
605 *win16_exe_file = main_exe_file;
606 main_exe_file = 0;
607 _EnterWin16Lock();
608 goto found;
609 case BINARY_OS216:
610 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
611 ExitProcess(1);
612 case BINARY_UNIX_EXE:
613 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
614 ExitProcess(1);
615 case BINARY_UNIX_LIB:
617 DOS_FULL_NAME full_name;
618 const char *name = main_exe_name;
620 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
621 if (DOSFS_GetFullName( name, TRUE, &full_name )) name = full_name.long_name;
622 CloseHandle( main_exe_file );
623 main_exe_file = 0;
624 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) )) goto found;
625 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
626 ExitProcess(1);
630 found:
631 /* build command line */
632 if (!ENV_BuildCommandLine( argv )) goto error;
634 /* create 32-bit module for main exe */
635 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
636 stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
638 /* allocate main thread stack */
639 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
641 /* switch to the new stack */
642 SYSDEPS_SwitchToThreadStack( start_process );
644 error:
645 ExitProcess( GetLastError() );
649 /***********************************************************************
650 * build_argv
652 * Build an argv array from a command-line.
653 * The command-line is modified to insert nulls.
654 * 'reserved' is the number of args to reserve before the first one.
656 static char **build_argv( char *cmdline, int reserved )
658 int argc;
659 char** argv;
660 char *arg,*s,*d;
661 int in_quotes,bcount;
663 argc=reserved+1;
664 bcount=0;
665 in_quotes=0;
666 s=cmdline;
667 while (1) {
668 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
669 /* space */
670 argc++;
671 /* skip the remaining spaces */
672 while (*s==' ' || *s=='\t') {
673 s++;
675 if (*s=='\0')
676 break;
677 bcount=0;
678 continue;
679 } else if (*s=='\\') {
680 /* '\', count them */
681 bcount++;
682 } else if ((*s=='"') && ((bcount & 1)==0)) {
683 /* unescaped '"' */
684 in_quotes=!in_quotes;
685 bcount=0;
686 } else {
687 /* a regular character */
688 bcount=0;
690 s++;
692 argv=malloc(argc*sizeof(*argv));
693 if (!argv)
694 return NULL;
696 arg=d=s=cmdline;
697 bcount=0;
698 in_quotes=0;
699 argc=reserved;
700 while (*s) {
701 if ((*s==' ' || *s=='\t') && !in_quotes) {
702 /* Close the argument and copy it */
703 *d=0;
704 argv[argc++]=arg;
706 /* skip the remaining spaces */
707 do {
708 s++;
709 } while (*s==' ' || *s=='\t');
711 /* Start with a new argument */
712 arg=d=s;
713 bcount=0;
714 } else if (*s=='\\') {
715 /* '\\' */
716 *d++=*s++;
717 bcount++;
718 } else if (*s=='"') {
719 /* '"' */
720 if ((bcount & 1)==0) {
721 /* Preceeded by an even number of '\', this is half that
722 * number of '\', plus a '"' which we discard.
724 d-=bcount/2;
725 s++;
726 in_quotes=!in_quotes;
727 } else {
728 /* Preceeded by an odd number of '\', this is half that
729 * number of '\' followed by a '"'
731 d=d-bcount/2-1;
732 *d++='"';
733 s++;
735 bcount=0;
736 } else {
737 /* a regular character */
738 *d++=*s++;
739 bcount=0;
742 if (*arg) {
743 *d='\0';
744 argv[argc++]=arg;
746 argv[argc]=NULL;
748 return argv;
752 /***********************************************************************
753 * build_envp
755 * Build the environment of a new child process.
757 static char **build_envp( const char *env, const char *extra_env )
759 const char *p;
760 char **envp;
761 int count = 0;
763 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
764 for (p = env; *p; count++) p += strlen(p) + 1;
765 count += 3;
767 if ((envp = malloc( count * sizeof(*envp) )))
769 extern char **environ;
770 char **envptr = envp;
771 char **unixptr = environ;
772 /* first the extra strings */
773 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
774 /* then put PATH, HOME and WINEPREFIX from the unix env */
775 for (unixptr = environ; unixptr && *unixptr; unixptr++)
776 if (!memcmp( *unixptr, "PATH=", 5 ) ||
777 !memcmp( *unixptr, "HOME=", 5 ) ||
778 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
779 /* now put the Windows environment strings */
780 for (p = env; *p; p += strlen(p) + 1)
782 if (memcmp( p, "PATH=", 5 ) &&
783 memcmp( p, "HOME=", 5 ) &&
784 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
786 *envptr = 0;
788 return envp;
792 /***********************************************************************
793 * exec_wine_binary
795 * Locate the Wine binary to exec for a new Win32 process.
797 static void exec_wine_binary( char **argv, char **envp )
799 const char *path, *pos, *ptr;
801 /* first, try for a WINELOADER environment variable */
802 argv[0] = getenv("WINELOADER");
803 if (argv[0])
804 execve( argv[0], argv, envp );
806 /* next, try bin directory */
807 argv[0] = BINDIR "/wine";
808 execve( argv[0], argv, envp );
810 /* now try the path of argv0 of the current binary */
811 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
812 if ((ptr = strrchr( full_argv0, '/' )))
814 memcpy( argv[0], full_argv0, ptr - full_argv0 );
815 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
816 execve( argv[0], argv, envp );
818 free( argv[0] );
820 /* now search in the Unix path */
821 if ((path = getenv( "PATH" )))
823 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
824 pos = path;
825 for (;;)
827 while (*pos == ':') pos++;
828 if (!*pos) break;
829 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
830 memcpy( argv[0], pos, ptr - pos );
831 strcpy( argv[0] + (ptr - pos), "/wine" );
832 execve( argv[0], argv, envp );
833 pos = ptr;
836 free( argv[0] );
840 /***********************************************************************
841 * fork_and_exec
843 * Fork and exec a new Unix process, checking for errors.
845 static int fork_and_exec( const char *filename, char *cmdline,
846 const char *env, const char *newdir )
848 int fd[2];
849 int pid, err;
850 char *extra_env = NULL;
852 if (!env)
854 env = GetEnvironmentStringsA();
855 extra_env = DRIVE_BuildEnv();
858 if (pipe(fd) == -1)
860 FILE_SetDosError();
861 return -1;
863 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
864 if (!(pid = fork())) /* child */
866 char **argv = build_argv( cmdline, filename ? 0 : 1 );
867 char **envp = build_envp( env, extra_env );
868 close( fd[0] );
870 /* Reset signals that we previously set to SIG_IGN */
871 signal( SIGPIPE, SIG_DFL );
872 signal( SIGCHLD, SIG_DFL );
874 if (newdir) chdir(newdir);
876 if (argv && envp)
878 if (!filename) exec_wine_binary( argv, envp );
879 else execve( filename, argv, envp );
881 err = errno;
882 write( fd[1], &err, sizeof(err) );
883 _exit(1);
885 close( fd[1] );
886 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
888 errno = err;
889 pid = -1;
891 if (pid == -1) FILE_SetDosError();
892 close( fd[0] );
893 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
894 return pid;
898 /***********************************************************************
899 * create_process
901 * Create a new process. If hFile is a valid handle we have an exe
902 * file, otherwise it is a Winelib app.
904 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
905 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
906 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
907 LPPROCESS_INFORMATION info, LPCSTR unixdir )
909 BOOL ret, success = FALSE;
910 HANDLE process_info;
911 startup_info_t startup_info;
913 /* fill the startup info structure */
915 startup_info.size = sizeof(startup_info);
916 /* startup_info.filename_len is set below */
917 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
918 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
919 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
920 startup_info.x = startup->dwX;
921 startup_info.y = startup->dwY;
922 startup_info.cx = startup->dwXSize;
923 startup_info.cy = startup->dwYSize;
924 startup_info.x_chars = startup->dwXCountChars;
925 startup_info.y_chars = startup->dwYCountChars;
926 startup_info.attribute = startup->dwFillAttribute;
927 startup_info.cmd_show = startup->wShowWindow;
928 startup_info.flags = startup->dwFlags;
930 /* create the process on the server side */
932 SERVER_START_REQ( new_process )
934 char buf[MAX_PATH];
935 LPCSTR nameptr;
937 req->inherit_all = inherit;
938 req->create_flags = flags;
939 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
940 req->exe_file = hFile;
941 if (startup->dwFlags & STARTF_USESTDHANDLES)
943 req->hstdin = startup->hStdInput;
944 req->hstdout = startup->hStdOutput;
945 req->hstderr = startup->hStdError;
947 else
949 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
950 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
951 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
954 if (GetLongPathNameA( filename, buf, MAX_PATH ))
955 nameptr = buf;
956 else
957 nameptr = filename;
959 startup_info.filename_len = strlen(nameptr);
960 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
961 wine_server_add_data( req, nameptr, startup_info.filename_len );
962 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
963 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
964 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
966 ret = !wine_server_call_err( req );
967 process_info = reply->info;
969 SERVER_END_REQ;
970 if (!ret) return FALSE;
972 /* fork and execute */
974 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
976 CloseHandle( process_info );
977 return FALSE;
980 /* wait for the new process info to be ready */
982 WaitForSingleObject( process_info, INFINITE );
983 SERVER_START_REQ( get_new_process_info )
985 req->info = process_info;
986 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
987 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
988 if ((ret = !wine_server_call_err( req )))
990 info->dwProcessId = (DWORD)reply->pid;
991 info->dwThreadId = (DWORD)reply->tid;
992 info->hProcess = reply->phandle;
993 info->hThread = reply->thandle;
994 success = reply->success;
997 SERVER_END_REQ;
999 if (ret && !success) /* new process failed to start */
1001 DWORD exitcode;
1002 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1003 CloseHandle( info->hThread );
1004 CloseHandle( info->hProcess );
1005 ret = FALSE;
1007 CloseHandle( process_info );
1008 return ret;
1012 /*************************************************************************
1013 * get_file_name
1015 * Helper for CreateProcess: retrieve the file name to load from the
1016 * app name and command line. Store the file name in buffer, and
1017 * return a possibly modified command line.
1018 * Also returns a handle to the opened file if it's a Windows binary.
1020 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1021 int buflen, HANDLE *handle )
1023 char *name, *pos, *ret = NULL;
1024 const char *p;
1026 /* if we have an app name, everything is easy */
1028 if (appname)
1030 /* use the unmodified app name as file name */
1031 lstrcpynA( buffer, appname, buflen );
1032 *handle = open_exe_file( buffer );
1033 if (!(ret = cmdline))
1035 /* no command-line, create one */
1036 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1037 sprintf( ret, "\"%s\"", appname );
1039 return ret;
1042 if (!cmdline)
1044 SetLastError( ERROR_INVALID_PARAMETER );
1045 return NULL;
1048 /* first check for a quoted file name */
1050 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1052 int len = p - cmdline - 1;
1053 /* extract the quoted portion as file name */
1054 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1055 memcpy( name, cmdline + 1, len );
1056 name[len] = 0;
1058 if (find_exe_file( name, buffer, buflen, handle ))
1059 ret = cmdline; /* no change necessary */
1060 goto done;
1063 /* now try the command-line word by word */
1065 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1066 pos = name;
1067 p = cmdline;
1069 while (*p)
1071 do *pos++ = *p++; while (*p && *p != ' ');
1072 *pos = 0;
1073 if (find_exe_file( name, buffer, buflen, handle ))
1075 ret = cmdline;
1076 break;
1080 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1082 /* now build a new command-line with quotes */
1084 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1085 sprintf( ret, "\"%s\"%s", name, p );
1087 done:
1088 HeapFree( GetProcessHeap(), 0, name );
1089 return ret;
1093 /**********************************************************************
1094 * CreateProcessA (KERNEL32.@)
1096 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1097 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1098 DWORD flags, LPVOID env, LPCSTR cur_dir,
1099 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1101 BOOL retv = FALSE;
1102 HANDLE hFile = 0;
1103 const char *unixdir = NULL;
1104 DOS_FULL_NAME full_dir;
1105 char name[MAX_PATH];
1106 LPSTR tidy_cmdline;
1107 char *p;
1109 /* Process the AppName and/or CmdLine to get module name and path */
1111 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1113 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1114 return FALSE;
1115 if (hFile == INVALID_HANDLE_VALUE) goto done;
1117 /* Warn if unsupported features are used */
1119 if (flags & NORMAL_PRIORITY_CLASS)
1120 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1121 if (flags & IDLE_PRIORITY_CLASS)
1122 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1123 if (flags & HIGH_PRIORITY_CLASS)
1124 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1125 if (flags & REALTIME_PRIORITY_CLASS)
1126 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1127 if (flags & CREATE_NEW_PROCESS_GROUP)
1128 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1129 if (flags & CREATE_UNICODE_ENVIRONMENT)
1130 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1131 if (flags & CREATE_SEPARATE_WOW_VDM)
1132 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1133 if (flags & CREATE_SHARED_WOW_VDM)
1134 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1135 if (flags & CREATE_DEFAULT_ERROR_MODE)
1136 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1137 if (flags & CREATE_NO_WINDOW)
1138 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1139 if (flags & PROFILE_USER)
1140 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1141 if (flags & PROFILE_KERNEL)
1142 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1143 if (flags & PROFILE_SERVER)
1144 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1145 if (startup_info->lpDesktop)
1146 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1147 name, debugstr_a(startup_info->lpDesktop));
1148 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1149 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1150 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1151 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1152 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1153 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1154 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1155 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1157 if (cur_dir)
1159 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir ))
1160 unixdir = full_dir.long_name;
1162 else
1164 char buf[MAX_PATH];
1165 if (GetCurrentDirectoryA(sizeof(buf),buf))
1167 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1171 info->hThread = info->hProcess = 0;
1172 info->dwProcessId = info->dwThreadId = 0;
1174 /* Determine executable type */
1176 if (!hFile) /* builtin exe */
1178 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1179 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1180 inherit, flags, startup_info, info, unixdir );
1181 goto done;
1184 switch( MODULE_GetBinaryType( hFile ))
1186 case BINARY_PE_EXE:
1187 case BINARY_WIN16:
1188 case BINARY_DOS:
1189 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1190 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1191 inherit, flags, startup_info, info, unixdir );
1192 break;
1193 case BINARY_OS216:
1194 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1195 SetLastError( ERROR_BAD_EXE_FORMAT );
1196 break;
1197 case BINARY_PE_DLL:
1198 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1199 SetLastError( ERROR_BAD_EXE_FORMAT );
1200 break;
1201 case BINARY_UNIX_LIB:
1202 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1203 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1204 inherit, flags, startup_info, info, unixdir );
1205 break;
1206 case BINARY_UNKNOWN:
1207 /* check for .com extension */
1208 if ((p = strrchr( name, '.' )) && !FILE_strcasecmp( p, ".com" ))
1210 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1211 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1212 inherit, flags, startup_info, info, unixdir );
1213 break;
1215 /* fall through */
1216 case BINARY_UNIX_EXE:
1218 DOS_FULL_NAME full_name;
1219 const char *unixfilename = name;
1221 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1222 if (DOSFS_GetFullName( name, TRUE, &full_name )) unixfilename = full_name.long_name;
1223 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1225 break;
1227 CloseHandle( hFile );
1229 done:
1230 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1231 return retv;
1235 /**********************************************************************
1236 * CreateProcessW (KERNEL32.@)
1237 * NOTES
1238 * lpReserved is not converted
1240 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1241 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1242 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1243 LPPROCESS_INFORMATION info )
1245 BOOL ret;
1246 STARTUPINFOA StartupInfoA;
1248 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1249 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1250 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1252 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1253 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1254 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1256 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1258 if (startup_info->lpReserved)
1259 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1260 debugstr_w(startup_info->lpReserved));
1262 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1263 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1265 HeapFree( GetProcessHeap(), 0, cur_dirA );
1266 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1267 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1268 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1270 return ret;
1274 /***********************************************************************
1275 * ExitProcess (KERNEL32.@)
1277 void WINAPI ExitProcess( DWORD status )
1279 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1280 SERVER_START_REQ( terminate_process )
1282 /* send the exit code to the server */
1283 req->handle = GetCurrentProcess();
1284 req->exit_code = status;
1285 wine_server_call( req );
1287 SERVER_END_REQ;
1288 exit( status );
1291 /***********************************************************************
1292 * ExitProcess (KERNEL.466)
1294 void WINAPI ExitProcess16( WORD status )
1296 DWORD count;
1297 ReleaseThunkLock( &count );
1298 ExitProcess( status );
1301 /******************************************************************************
1302 * TerminateProcess (KERNEL32.@)
1304 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1306 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1307 if (status) SetLastError( RtlNtStatusToDosError(status) );
1308 return !status;
1312 /***********************************************************************
1313 * GetProcessDword (KERNEL.485)
1314 * GetProcessDword (KERNEL32.18)
1315 * 'Of course you cannot directly access Windows internal structures'
1317 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1319 DWORD x, y;
1321 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1323 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1325 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1326 return 0;
1329 switch ( offset )
1331 case GPD_APP_COMPAT_FLAGS:
1332 return GetAppCompatFlags16(0);
1334 case GPD_LOAD_DONE_EVENT:
1335 return current_process.load_done_evt;
1337 case GPD_HINSTANCE16:
1338 return GetTaskDS16();
1340 case GPD_WINDOWS_VERSION:
1341 return GetExeVersion16();
1343 case GPD_THDB:
1344 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1346 case GPD_PDB:
1347 return (DWORD)&current_process;
1349 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1350 return current_startupinfo.hStdOutput;
1352 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1353 return current_startupinfo.hStdInput;
1355 case GPD_STARTF_SHOWWINDOW:
1356 return current_startupinfo.wShowWindow;
1358 case GPD_STARTF_SIZE:
1359 x = current_startupinfo.dwXSize;
1360 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1361 y = current_startupinfo.dwYSize;
1362 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1363 return MAKELONG( x, y );
1365 case GPD_STARTF_POSITION:
1366 x = current_startupinfo.dwX;
1367 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1368 y = current_startupinfo.dwY;
1369 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1370 return MAKELONG( x, y );
1372 case GPD_STARTF_FLAGS:
1373 return current_startupinfo.dwFlags;
1375 case GPD_PARENT:
1376 return 0;
1378 case GPD_FLAGS:
1379 return current_process.flags;
1381 case GPD_USERDATA:
1382 return current_process.process_dword;
1384 default:
1385 ERR_(win32)("Unknown offset %d\n", offset );
1386 return 0;
1390 /***********************************************************************
1391 * SetProcessDword (KERNEL.484)
1392 * 'Of course you cannot directly access Windows internal structures'
1394 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1396 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1398 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1400 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1401 return;
1404 switch ( offset )
1406 case GPD_APP_COMPAT_FLAGS:
1407 case GPD_LOAD_DONE_EVENT:
1408 case GPD_HINSTANCE16:
1409 case GPD_WINDOWS_VERSION:
1410 case GPD_THDB:
1411 case GPD_PDB:
1412 case GPD_STARTF_SHELLDATA:
1413 case GPD_STARTF_HOTKEY:
1414 case GPD_STARTF_SHOWWINDOW:
1415 case GPD_STARTF_SIZE:
1416 case GPD_STARTF_POSITION:
1417 case GPD_STARTF_FLAGS:
1418 case GPD_PARENT:
1419 case GPD_FLAGS:
1420 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1421 break;
1423 case GPD_USERDATA:
1424 current_process.process_dword = value;
1425 break;
1427 default:
1428 ERR_(win32)("Unknown offset %d\n", offset );
1429 break;
1434 /*********************************************************************
1435 * OpenProcess (KERNEL32.@)
1437 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1439 HANDLE ret = 0;
1440 SERVER_START_REQ( open_process )
1442 req->pid = (void *)id;
1443 req->access = access;
1444 req->inherit = inherit;
1445 if (!wine_server_call_err( req )) ret = reply->handle;
1447 SERVER_END_REQ;
1448 return ret;
1451 /*********************************************************************
1452 * MapProcessHandle (KERNEL.483)
1454 DWORD WINAPI MapProcessHandle( HANDLE handle )
1456 DWORD ret = 0;
1457 SERVER_START_REQ( get_process_info )
1459 req->handle = handle;
1460 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1462 SERVER_END_REQ;
1463 return ret;
1466 /***********************************************************************
1467 * SetPriorityClass (KERNEL32.@)
1469 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1471 BOOL ret;
1472 SERVER_START_REQ( set_process_info )
1474 req->handle = hprocess;
1475 req->priority = priorityclass;
1476 req->mask = SET_PROCESS_INFO_PRIORITY;
1477 ret = !wine_server_call_err( req );
1479 SERVER_END_REQ;
1480 return ret;
1484 /***********************************************************************
1485 * GetPriorityClass (KERNEL32.@)
1487 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1489 DWORD ret = 0;
1490 SERVER_START_REQ( get_process_info )
1492 req->handle = hprocess;
1493 if (!wine_server_call_err( req )) ret = reply->priority;
1495 SERVER_END_REQ;
1496 return ret;
1500 /***********************************************************************
1501 * SetProcessAffinityMask (KERNEL32.@)
1503 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1505 BOOL ret;
1506 SERVER_START_REQ( set_process_info )
1508 req->handle = hProcess;
1509 req->affinity = affmask;
1510 req->mask = SET_PROCESS_INFO_AFFINITY;
1511 ret = !wine_server_call_err( req );
1513 SERVER_END_REQ;
1514 return ret;
1517 /**********************************************************************
1518 * GetProcessAffinityMask (KERNEL32.@)
1520 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1521 LPDWORD lpProcessAffinityMask,
1522 LPDWORD lpSystemAffinityMask )
1524 BOOL ret = FALSE;
1525 SERVER_START_REQ( get_process_info )
1527 req->handle = hProcess;
1528 if (!wine_server_call_err( req ))
1530 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1531 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1532 ret = TRUE;
1535 SERVER_END_REQ;
1536 return ret;
1540 /***********************************************************************
1541 * GetProcessVersion (KERNEL32.@)
1543 DWORD WINAPI GetProcessVersion( DWORD processid )
1545 IMAGE_NT_HEADERS *nt;
1547 if (processid && processid != GetCurrentProcessId())
1549 FIXME("should use ReadProcessMemory\n");
1550 return 0;
1552 if ((nt = RtlImageNtHeader( current_process.module )))
1553 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1554 nt->OptionalHeader.MinorSubsystemVersion);
1555 return 0;
1558 /***********************************************************************
1559 * GetProcessFlags (KERNEL32.@)
1561 DWORD WINAPI GetProcessFlags( DWORD processid )
1563 if (processid && processid != GetCurrentProcessId()) return 0;
1564 return current_process.flags;
1568 /***********************************************************************
1569 * SetProcessWorkingSetSize [KERNEL32.@]
1570 * Sets the min/max working set sizes for a specified process.
1572 * PARAMS
1573 * hProcess [I] Handle to the process of interest
1574 * minset [I] Specifies minimum working set size
1575 * maxset [I] Specifies maximum working set size
1577 * RETURNS STD
1579 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1580 DWORD maxset)
1582 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1583 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1584 /* Trim the working set to zero */
1585 /* Swap the process out of physical RAM */
1587 return TRUE;
1590 /***********************************************************************
1591 * GetProcessWorkingSetSize (KERNEL32.@)
1593 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1594 LPDWORD maxset)
1596 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1597 /* 32 MB working set size */
1598 if (minset) *minset = 32*1024*1024;
1599 if (maxset) *maxset = 32*1024*1024;
1600 return TRUE;
1603 /***********************************************************************
1604 * SetProcessShutdownParameters (KERNEL32.@)
1606 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1607 * Now tracks changes made (but does not act on these changes)
1609 static DWORD shutdown_flags = 0;
1610 static DWORD shutdown_priority = 0x280;
1612 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1614 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1615 shutdown_flags = flags;
1616 shutdown_priority = level;
1617 return TRUE;
1621 /***********************************************************************
1622 * GetProcessShutdownParameters (KERNEL32.@)
1625 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1627 *lpdwLevel = shutdown_priority;
1628 *lpdwFlags = shutdown_flags;
1629 return TRUE;
1633 /***********************************************************************
1634 * SetProcessPriorityBoost (KERNEL32.@)
1636 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1638 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1639 /* Say we can do it. I doubt the program will notice that we don't. */
1640 return TRUE;
1644 /***********************************************************************
1645 * ReadProcessMemory (KERNEL32.@)
1647 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1648 LPDWORD bytes_read )
1650 DWORD res;
1652 SERVER_START_REQ( read_process_memory )
1654 req->handle = process;
1655 req->addr = (void *)addr;
1656 wine_server_set_reply( req, buffer, size );
1657 if ((res = wine_server_call_err( req ))) size = 0;
1659 SERVER_END_REQ;
1660 if (bytes_read) *bytes_read = size;
1661 return !res;
1665 /***********************************************************************
1666 * WriteProcessMemory (KERNEL32.@)
1668 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1669 LPDWORD bytes_written )
1671 static const int zero;
1672 unsigned int first_offset, last_offset, first_mask, last_mask;
1673 DWORD res;
1675 if (!size)
1677 SetLastError( ERROR_INVALID_PARAMETER );
1678 return FALSE;
1681 /* compute the mask for the first int */
1682 first_mask = ~0;
1683 first_offset = (unsigned int)addr % sizeof(int);
1684 memset( &first_mask, 0, first_offset );
1686 /* compute the mask for the last int */
1687 last_offset = (size + first_offset) % sizeof(int);
1688 last_mask = 0;
1689 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1691 SERVER_START_REQ( write_process_memory )
1693 req->handle = process;
1694 req->addr = (char *)addr - first_offset;
1695 req->first_mask = first_mask;
1696 req->last_mask = last_mask;
1697 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1698 wine_server_add_data( req, buffer, size );
1699 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1701 if ((res = wine_server_call_err( req ))) size = 0;
1703 SERVER_END_REQ;
1704 if (bytes_written) *bytes_written = size;
1706 char dummy[32];
1707 DWORD read;
1708 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1710 return !res;
1714 /***********************************************************************
1715 * RegisterServiceProcess (KERNEL.491)
1716 * RegisterServiceProcess (KERNEL32.@)
1718 * A service process calls this function to ensure that it continues to run
1719 * even after a user logged off.
1721 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1723 /* I don't think that Wine needs to do anything in that function */
1724 return 1; /* success */
1727 /***********************************************************************
1728 * GetExitCodeProcess [KERNEL32.@]
1730 * Gets termination status of specified process
1732 * RETURNS
1733 * Success: TRUE
1734 * Failure: FALSE
1736 BOOL WINAPI GetExitCodeProcess(
1737 HANDLE hProcess, /* [in] handle to the process */
1738 LPDWORD lpExitCode) /* [out] address to receive termination status */
1740 BOOL ret;
1741 SERVER_START_REQ( get_process_info )
1743 req->handle = hProcess;
1744 ret = !wine_server_call_err( req );
1745 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1747 SERVER_END_REQ;
1748 return ret;
1752 /***********************************************************************
1753 * SetErrorMode (KERNEL32.@)
1755 UINT WINAPI SetErrorMode( UINT mode )
1757 UINT old = current_process.error_mode;
1758 current_process.error_mode = mode;
1759 return old;
1763 /**************************************************************************
1764 * SetFileApisToOEM (KERNEL32.@)
1766 VOID WINAPI SetFileApisToOEM(void)
1768 current_process.flags |= PDB32_FILE_APIS_OEM;
1772 /**************************************************************************
1773 * SetFileApisToANSI (KERNEL32.@)
1775 VOID WINAPI SetFileApisToANSI(void)
1777 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1781 /******************************************************************************
1782 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1784 * RETURNS
1785 * TRUE: Set of file functions is using ANSI code page
1786 * FALSE: Set of file functions is using OEM code page
1788 BOOL WINAPI AreFileApisANSI(void)
1790 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1794 /***********************************************************************
1795 * GetTickCount (KERNEL32.@)
1797 * Returns the number of milliseconds, modulo 2^32, since the start
1798 * of the wineserver.
1800 DWORD WINAPI GetTickCount(void)
1802 struct timeval t;
1803 gettimeofday( &t, NULL );
1804 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1808 /**********************************************************************
1809 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1811 * Allocates a thread local storage index
1813 * RETURNS
1814 * Success: TLS Index
1815 * Failure: 0xFFFFFFFF
1817 DWORD WINAPI TlsAlloc( void )
1819 DWORD i, mask, ret = 0;
1820 DWORD *bits = current_process.tls_bits;
1821 RtlAcquirePebLock();
1822 if (*bits == 0xffffffff)
1824 bits++;
1825 ret = 32;
1826 if (*bits == 0xffffffff)
1828 RtlReleasePebLock();
1829 SetLastError( ERROR_NO_MORE_ITEMS );
1830 return 0xffffffff;
1833 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1834 *bits |= mask;
1835 RtlReleasePebLock();
1836 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1837 return ret + i;
1841 /**********************************************************************
1842 * TlsFree [KERNEL32.@] Releases a TLS index.
1844 * Releases a thread local storage index, making it available for reuse
1846 * RETURNS
1847 * Success: TRUE
1848 * Failure: FALSE
1850 BOOL WINAPI TlsFree(
1851 DWORD index) /* [in] TLS Index to free */
1853 DWORD mask = (1 << (index & 31));
1854 DWORD *bits = current_process.tls_bits;
1855 if (index >= 64)
1857 SetLastError( ERROR_INVALID_PARAMETER );
1858 return FALSE;
1860 if (index >= 32) bits++;
1861 RtlAcquirePebLock();
1862 if (!(*bits & mask)) /* already free? */
1864 RtlReleasePebLock();
1865 SetLastError( ERROR_INVALID_PARAMETER );
1866 return FALSE;
1868 *bits &= ~mask;
1869 NtCurrentTeb()->tls_array[index] = 0;
1870 /* FIXME: should zero all other thread values */
1871 RtlReleasePebLock();
1872 return TRUE;
1876 /**********************************************************************
1877 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1879 * RETURNS
1880 * Success: Value stored in calling thread's TLS slot for index
1881 * Failure: 0 and GetLastError returns NO_ERROR
1883 LPVOID WINAPI TlsGetValue(
1884 DWORD index) /* [in] TLS index to retrieve value for */
1886 if (index >= 64)
1888 SetLastError( ERROR_INVALID_PARAMETER );
1889 return NULL;
1891 SetLastError( ERROR_SUCCESS );
1892 return NtCurrentTeb()->tls_array[index];
1896 /**********************************************************************
1897 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1899 * RETURNS
1900 * Success: TRUE
1901 * Failure: FALSE
1903 BOOL WINAPI TlsSetValue(
1904 DWORD index, /* [in] TLS index to set value for */
1905 LPVOID value) /* [in] Value to be stored */
1907 if (index >= 64)
1909 SetLastError( ERROR_INVALID_PARAMETER );
1910 return FALSE;
1912 NtCurrentTeb()->tls_array[index] = value;
1913 return TRUE;
1917 /***********************************************************************
1918 * GetCurrentProcess (KERNEL32.@)
1920 #undef GetCurrentProcess
1921 HANDLE WINAPI GetCurrentProcess(void)
1923 return 0xffffffff;