Added handlers for some IME messages in DefWindowProc.
[wine] / scheduler / process.c
1 /*
2  * Win32 processes
3  *
4  * Copyright 1996, 1998 Alexandre Julliard
5  */
6
7 #include <assert.h>
8 #include <ctype.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include "wine/winbase16.h"
16 #include "wine/exception.h"
17 #include "wine/library.h"
18 #include "process.h"
19 #include "drive.h"
20 #include "main.h"
21 #include "module.h"
22 #include "file.h"
23 #include "global.h"
24 #include "heap.h"
25 #include "task.h"
26 #include "ldt.h"
27 #include "thread.h"
28 #include "winerror.h"
29 #include "server.h"
30 #include "options.h"
31 #include "callback.h"
32 #include "debugtools.h"
33
34 DEFAULT_DEBUG_CHANNEL(process);
35 DECLARE_DEBUG_CHANNEL(relay);
36 DECLARE_DEBUG_CHANNEL(win32);
37
38 PDB current_process;
39
40 static char **main_exe_argv;
41 static char main_exe_name[MAX_PATH];
42 static HANDLE main_exe_file = INVALID_HANDLE_VALUE;
43 static HMODULE main_module;
44
45 unsigned int server_startticks;
46
47 /***********************************************************************
48  *           PROCESS_CallUserSignalProc
49  *
50  * FIXME:  Some of the signals aren't sent correctly!
51  *
52  * The exact meaning of the USER signals is undocumented, but this 
53  * should cover the basic idea:
54  *
55  * USIG_DLL_UNLOAD_WIN16
56  *     This is sent when a 16-bit module is unloaded.
57  *
58  * USIG_DLL_UNLOAD_WIN32
59  *     This is sent when a 32-bit module is unloaded.
60  *
61  * USIG_DLL_UNLOAD_ORPHANS
62  *     This is sent after the last Win3.1 module is unloaded,
63  *     to allow removal of orphaned menus.
64  *
65  * USIG_FAULT_DIALOG_PUSH
66  * USIG_FAULT_DIALOG_POP
67  *     These are called to allow USER to prepare for displaying a
68  *     fault dialog, even though the fault might have happened while
69  *     inside a USER critical section.
70  *
71  * USIG_THREAD_INIT
72  *     This is called from the context of a new thread, as soon as it
73  *     has started to run.
74  *
75  * USIG_THREAD_EXIT
76  *     This is called, still in its context, just before a thread is
77  *     about to terminate.
78  *
79  * USIG_PROCESS_CREATE
80  *     This is called, in the parent process context, after a new process
81  *     has been created.
82  *
83  * USIG_PROCESS_INIT
84  *     This is called in the new process context, just after the main thread
85  *     has started execution (after the main thread's USIG_THREAD_INIT has
86  *     been sent).
87  *
88  * USIG_PROCESS_LOADED
89  *     This is called after the executable file has been loaded into the
90  *     new process context.
91  *
92  * USIG_PROCESS_RUNNING
93  *     This is called immediately before the main entry point is called.
94  *
95  * USIG_PROCESS_EXIT
96  *     This is called in the context of a process that is about to
97  *     terminate (but before the last thread's USIG_THREAD_EXIT has
98  *     been sent).
99  *
100  * USIG_PROCESS_DESTROY
101  *     This is called after a process has terminated.
102  *
103  *
104  * The meaning of the dwFlags bits is as follows:
105  *
106  * USIG_FLAGS_WIN32
107  *     Current process is 32-bit.
108  *
109  * USIG_FLAGS_GUI
110  *     Current process is a (Win32) GUI process.
111  *
112  * USIG_FLAGS_FEEDBACK 
113  *     Current process needs 'feedback' (determined from the STARTUPINFO
114  *     flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
115  *
116  * USIG_FLAGS_FAULT
117  *     The signal is being sent due to a fault.
118  */
119 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE hModule )
120 {
121     DWORD flags = current_process.flags;
122     DWORD startup_flags = current_startupinfo.dwFlags;
123     DWORD dwFlags = 0;
124
125     /* Determine dwFlags */
126
127     if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
128
129     if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
130
131     if ( dwFlags & USIG_FLAGS_GUI )
132     {
133         /* Feedback defaults to ON */
134         if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
135             dwFlags |= USIG_FLAGS_FEEDBACK;
136     }
137     else
138     {
139         /* Feedback defaults to OFF */
140         if (startup_flags & STARTF_FORCEONFEEDBACK)
141             dwFlags |= USIG_FLAGS_FEEDBACK;
142     }
143
144     /* Convert module handle to 16-bit */
145
146     if ( HIWORD( hModule ) )
147         hModule = MapHModuleLS( hModule );
148
149     /* Call USER signal proc */
150
151     if ( Callout.UserSignalProc )
152     {
153         if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
154             Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
155         else
156             Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
157     }
158 }
159
160
161 /***********************************************************************
162  *           process_init
163  *
164  * Main process initialisation code
165  */
166 static BOOL process_init( char *argv[] )
167 {
168     BOOL ret;
169
170     /* store the program name */
171     argv0 = argv[0];
172     main_exe_argv = argv;
173
174     /* Fill the initial process structure */
175     current_process.exit_code       = STILL_ACTIVE;
176     current_process.threads         = 1;
177     current_process.running_threads = 1;
178     current_process.ring0_threads   = 1;
179     current_process.group           = &current_process;
180     current_process.priority        = 8;  /* Normal */
181     current_process.env_db          = &current_envdb;
182
183     /* Setup the server connection */
184     NtCurrentTeb()->socket = CLIENT_InitServer();
185     if (CLIENT_InitThread()) return FALSE;
186
187     /* Retrieve startup info from the server */
188     SERVER_START_REQ
189     {
190         struct init_process_request *req = server_alloc_req( sizeof(*req),
191                                                              sizeof(main_exe_name)-1 );
192
193         req->ldt_copy  = &wine_ldt_copy;
194         req->ppid      = getppid();
195         if ((ret = !server_call( REQ_INIT_PROCESS )))
196         {
197             size_t len = server_data_size( req );
198             memcpy( main_exe_name, server_data_ptr(req), len );
199             main_exe_name[len] = 0;
200             main_exe_file = req->exe_file;
201             current_startupinfo.dwFlags     = req->start_flags;
202             server_startticks               = req->server_start;
203             current_startupinfo.wShowWindow = req->cmd_show;
204             current_envdb.hStdin   = current_startupinfo.hStdInput  = req->hstdin;
205             current_envdb.hStdout  = current_startupinfo.hStdOutput = req->hstdout;
206             current_envdb.hStderr  = current_startupinfo.hStdError  = req->hstderr;
207         }
208     }
209     SERVER_END_REQ;
210     if (!ret) return FALSE;
211
212     /* Create the system and process heaps */
213     if (!HEAP_CreateSystemHeap()) return FALSE;
214     current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
215
216     /* Copy the parent environment */
217     if (!ENV_BuildEnvironment()) return FALSE;
218
219     /* Initialize the critical sections */
220     InitializeCriticalSection( &current_process.crit_section );
221
222     /* Parse command line arguments */
223     OPTIONS_ParseOptions( argv );
224
225     return MAIN_MainInit();
226 }
227
228
229 /***********************************************************************
230  *           build_command_line
231  *
232  * Build the command line of a process from the argv array.
233  *
234  * Note that it does NOT necessarily include the file name.
235  * Sometimes we don't even have any command line options at all.
236  */
237 static inline char *build_command_line( char **argv )
238 {
239     int len, quote = 0;
240     char *cmdline, *p, **arg;
241
242     for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
243     if ((argv[0]) && (quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
244     if (!(p = cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
245     arg = argv;
246     if (quote)
247     {
248         *p++ = '\"';
249         strcpy( p, *arg );
250         p += strlen(p);
251         *p++ = '\"';
252         *p++ = ' ';
253         arg++;
254     }
255     while (*arg)
256     {
257         strcpy( p, *arg );
258         p += strlen(p);
259         *p++ = ' ';
260         arg++;
261     }
262     if (p > cmdline) p--;  /* remove last space */
263     *p = 0;
264     return cmdline;
265 }
266
267
268 /***********************************************************************
269  *           start_process
270  *
271  * Startup routine of a new process. Runs on the new process stack.
272  */
273 static void start_process(void)
274 {
275     int debugged, console_app;
276     LPTHREAD_START_ROUTINE entry;
277     WINE_MODREF *wm;
278
279     /* build command line */
280     if (!(current_envdb.cmd_line = build_command_line( main_exe_argv ))) goto error;
281
282     /* create 32-bit module for main exe */
283     if (!(main_module = BUILTIN32_LoadExeModule( main_module ))) goto error;
284
285     /* use original argv[0] as name for the main module */
286     if (!main_exe_name[0])
287     {
288         if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
289             lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
290     }
291
292     /* Retrieve entry point address */
293     entry = (LPTHREAD_START_ROUTINE)((char*)main_module +
294                                      PE_HEADER(main_module)->OptionalHeader.AddressOfEntryPoint);
295     console_app = (PE_HEADER(main_module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
296     if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
297
298     /* Signal the parent process to continue */
299     SERVER_START_REQ
300     {
301         struct init_process_done_request *req = server_alloc_req( sizeof(*req), 0 );
302         req->module = (void *)main_module;
303         req->entry  = entry;
304         req->name   = main_exe_name;
305         req->gui    = !console_app;
306         server_call( REQ_INIT_PROCESS_DONE );
307         debugged = req->debugged;
308     }
309     SERVER_END_REQ;
310
311     /* Install signal handlers; this cannot be done before, since we cannot
312      * send exceptions to the debugger before the create process event that
313      * is sent by REQ_INIT_PROCESS_DONE */
314     if (!SIGNAL_Init()) goto error;
315
316     /* create the main modref and load dependencies */
317     if (!(wm = PE_CreateModule( main_module, main_exe_name, 0, main_exe_file, FALSE )))
318         goto error;
319     wm->refCount++;
320
321     EnterCriticalSection( &current_process.crit_section );
322     PE_InitTls();
323     MODULE_DllProcessAttach( current_process.exe_modref, (LPVOID)1 );
324     LeaveCriticalSection( &current_process.crit_section );
325
326     /* Get pointers to USER routines called by KERNEL */
327     THUNK_InitCallout();
328
329     /* Call FinalUserInit routine */
330     if (Callout.FinalUserInit16) Callout.FinalUserInit16();
331
332     /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
333      *       context of the parent process.  Actually, the USER signal proc
334      *       doesn't really care about that, but it *does* require that the
335      *       startup parameters are correctly set up, so that GetProcessDword
336      *       works.  Furthermore, before calling the USER signal proc the 
337      *       16-bit stack must be set up, which it is only after TASK_Create
338      *       in the case of a 16-bit process. Thus, we send the signal here.
339      */
340     PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
341     PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
342     PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
343     PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
344     /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
345     if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
346
347     TRACE_(relay)( "Starting Win32 process %s (entryproc=%p)\n", current_process.exe_modref->filename, entry );
348     if (debugged) DbgBreakPoint();
349     /* FIXME: should use _PEB as parameter for NT 3.5 programs !
350      * Dunno about other OSs */
351     SetLastError(0);  /* clear error code */
352     ExitThread( entry(NULL) );
353
354  error:
355     ExitProcess( GetLastError() );
356 }
357
358
359 /***********************************************************************
360  *           open_winelib_app
361  *
362  * Try to open the Winelib app .so file based on argv[0] or WINEPRELOAD.
363  */
364 void *open_winelib_app( char *argv[] )
365 {
366     void *ret = NULL;
367     char *tmp;
368     const char *name;
369
370     if ((name = getenv( "WINEPRELOAD" )))
371     {
372         if (!(ret = wine_dll_load_main_exe( name, 0 )))
373         {
374             MESSAGE( "%s: could not load '%s' as specified in the WINEPRELOAD environment variable\n",
375                      argv[0], name );
376             ExitProcess(1);
377         }
378     }
379     else
380     {
381         /* if argv[0] is "wine", don't try to load anything */
382         if (!(name = strrchr( argv[0], '/' ))) name = argv[0];
383         else name++;
384         if (!strcmp( name, "wine" )) return NULL;
385
386         /* now try argv[0] with ".so" appended */
387         if ((tmp = HeapAlloc( GetProcessHeap(), 0, strlen(argv[0]) + 4 )))
388         {
389             strcpy( tmp, argv[0] );
390             strcat( tmp, ".so" );
391             /* search in PATH only if there was no '/' in argv[0] */
392             ret = wine_dll_load_main_exe( tmp, (name == argv[0]) );
393             if (!ret && !argv[1])
394             {
395                 /* if no argv[1], this will be better than displaying usage */
396                 MESSAGE( "%s: could not load library '%s' as Winelib application\n",
397                          argv[0], tmp );
398                 ExitProcess(1);
399             }
400             HeapFree( GetProcessHeap(), 0, tmp );
401         }
402     }
403     return ret;
404 }
405
406 /***********************************************************************
407  *           PROCESS_InitWine
408  *
409  * Wine initialisation: load and start the main exe file.
410  */
411 void PROCESS_InitWine( int argc, char *argv[] )
412 {
413     DWORD stack_size = 0;
414
415     /* Initialize everything */
416     if (!process_init( argv )) exit(1);
417
418     if (open_winelib_app( argv )) goto found; /* try to open argv[0] as a winelib app */
419
420     main_exe_argv = ++argv;  /* remove argv[0] (wine itself) */
421
422     if (!main_exe_name[0])
423     {
424         if (!argv[0]) OPTIONS_Usage();
425
426         /* open the exe file */
427         if (!SearchPathA( NULL, argv[0], ".exe", sizeof(main_exe_name), main_exe_name, NULL ) &&
428             !SearchPathA( NULL, argv[0], NULL, sizeof(main_exe_name), main_exe_name, NULL ))
429         {
430             MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
431             goto error;
432         }
433     }
434
435     if (main_exe_file == INVALID_HANDLE_VALUE)
436     {
437         if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
438                                           NULL, OPEN_EXISTING, 0, -1 )) == INVALID_HANDLE_VALUE)
439         {
440             MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
441             goto error;
442         }
443     }
444
445     /* first try Win32 format; this will fail if the file is not a PE binary */
446     if ((main_module = PE_LoadImage( main_exe_file, main_exe_name, 0 )))
447     {
448         if (PE_HEADER(main_module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
449             ExitProcess( ERROR_BAD_EXE_FORMAT );
450         stack_size = PE_HEADER(main_module)->OptionalHeader.SizeOfStackReserve;
451         goto found;
452     }
453
454     /* it must be 16-bit or DOS format */
455     NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
456     current_process.flags |= PDB32_WIN16_PROC;
457     main_exe_name[0] = 0;
458     CloseHandle( main_exe_file );
459     main_exe_file = INVALID_HANDLE_VALUE;
460     _EnterWin16Lock();
461
462  found:
463     /* allocate main thread stack */
464     if (!THREAD_InitStack( NtCurrentTeb(), stack_size, TRUE )) goto error;
465
466     /* switch to the new stack */
467     SYSDEPS_SwitchToThreadStack( start_process );
468
469  error:
470     ExitProcess( GetLastError() );
471 }
472
473
474 /***********************************************************************
475  *           PROCESS_InitWinelib
476  *
477  * Initialisation of a new Winelib process.
478  */
479 void PROCESS_InitWinelib( int argc, char *argv[] )
480 {
481     if (!process_init( argv )) exit(1);
482
483     /* allocate main thread stack */
484     if (!THREAD_InitStack( NtCurrentTeb(), 0, TRUE )) ExitProcess( GetLastError() );
485
486     /* switch to the new stack */
487     SYSDEPS_SwitchToThreadStack( start_process );
488 }
489
490
491 /***********************************************************************
492  *           build_argv
493  *
494  * Build an argv array from a command-line.
495  * The command-line is modified to insert nulls.
496  * 'reserved' is the number of args to reserve before the first one.
497  */
498 static char **build_argv( char *cmdline, int reserved )
499 {
500     char **argv;
501     int count = reserved + 1;
502     char *p = cmdline;
503
504     /* if first word is quoted store it as a single arg */
505     if (*cmdline == '\"')
506     {
507         if ((p = strchr( cmdline + 1, '\"' )))
508         {
509             p++;
510             count++;
511         }
512         else p = cmdline;
513     }
514     while (*p)
515     {
516         while (*p && isspace(*p)) p++;
517         if (!*p) break;
518         count++;
519         while (*p && !isspace(*p)) p++;
520     }
521
522     if ((argv = malloc( count * sizeof(*argv) )))
523     {
524         char **argvptr = argv + reserved;
525         p = cmdline;
526         if (*cmdline == '\"')
527         {
528             if ((p = strchr( cmdline + 1, '\"' )))
529             {
530                 *argvptr++ = cmdline + 1;
531                 *p++ = 0;
532             }
533             else p = cmdline;
534         }
535         while (*p)
536         {
537             while (*p && isspace(*p)) *p++ = 0;
538             if (!*p) break;
539             *argvptr++ = p;
540             while (*p && !isspace(*p)) p++;
541         }
542         *argvptr = 0;
543     }
544     return argv;
545 }
546
547
548 /***********************************************************************
549  *           build_envp
550  *
551  * Build the environment of a new child process.
552  */
553 static char **build_envp( const char *env, const char *extra_env )
554 {
555     const char *p;
556     char **envp;
557     int count = 0;
558
559     if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
560     for (p = env; *p; count++) p += strlen(p) + 1;
561     count += 3;
562
563     if ((envp = malloc( count * sizeof(*envp) )))
564     {
565         extern char **environ;
566         char **envptr = envp;
567         char **unixptr = environ;
568         /* first the extra strings */
569         if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
570         /* then put PATH, HOME and WINEPREFIX from the unix env */
571         for (unixptr = environ; unixptr && *unixptr; unixptr++)
572             if (!memcmp( *unixptr, "PATH=", 5 ) ||
573                 !memcmp( *unixptr, "HOME=", 5 ) ||
574                 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
575         /* now put the Windows environment strings */
576         for (p = env; *p; p += strlen(p) + 1)
577         {
578             if (memcmp( p, "PATH=", 5 ) &&
579                 memcmp( p, "HOME=", 5 ) &&
580                 memcmp( p, "WINEPRELOAD=", 12 ) &&
581                 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
582         }
583         *envptr = 0;
584     }
585     return envp;
586 }
587
588
589 /***********************************************************************
590  *           exec_wine_binary
591  *
592  * Locate the Wine binary to exec for a new Win32 process.
593  */
594 static void exec_wine_binary( char **argv, char **envp )
595 {
596     const char *path, *pos, *ptr;
597
598     /* first, try for a WINELOADER environment variable */
599     argv[0] = getenv("WINELOADER");
600     if (argv[0])
601         execve( argv[0], argv, envp );
602
603     /* next, try bin directory */
604     argv[0] = BINDIR "/wine";
605     execve( argv[0], argv, envp );
606
607     /* now try the path of argv0 of the current binary */
608     if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
609     if ((ptr = strrchr( full_argv0, '/' )))
610     {
611         memcpy( argv[0], full_argv0, ptr - full_argv0 );
612         strcpy( argv[0] + (ptr - full_argv0), "/wine" );
613         execve( argv[0], argv, envp );
614     }
615     free( argv[0] );
616
617     /* now search in the Unix path */
618     if ((path = getenv( "PATH" )))
619     {
620         if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
621         pos = path;
622         for (;;)
623         {
624             while (*pos == ':') pos++;
625             if (!*pos) break;
626             if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
627             memcpy( argv[0], pos, ptr - pos );
628             strcpy( argv[0] + (ptr - pos), "/wine" );
629             execve( argv[0], argv, envp );
630             pos = ptr;
631         }
632     }
633     free( argv[0] );
634
635     /* finally try the current directory */
636     argv[0] = "./wine";
637     execve( argv[0], argv, envp );
638 }
639
640
641 /***********************************************************************
642  *           fork_and_exec
643  *
644  * Fork and exec a new Unix process, checking for errors.
645  */
646 static int fork_and_exec( const char *filename, char *cmdline,
647                           const char *env, const char *newdir )
648 {
649     int fd[2];
650     int pid, err;
651     char *extra_env = NULL;
652
653     if (!env)
654     {
655         env = GetEnvironmentStringsA();
656         extra_env = DRIVE_BuildEnv();
657     }
658
659     if (pipe(fd) == -1)
660     {
661         FILE_SetDosError();
662         return -1;
663     }
664     fcntl( fd[1], F_SETFD, 1 );  /* set close on exec */
665     if (!(pid = fork()))  /* child */
666     {
667         char **argv = build_argv( cmdline, filename ? 0 : 2 );
668         char **envp = build_envp( env, extra_env );
669         close( fd[0] );
670
671         if (newdir) chdir(newdir);
672
673         if (argv && envp)
674         {
675             if (!filename)
676             {
677                 argv[1] = "--";
678                 exec_wine_binary( argv, envp );
679             }
680             else execve( filename, argv, envp );
681         }
682         err = errno;
683         write( fd[1], &err, sizeof(err) );
684         _exit(1);
685     }
686     close( fd[1] );
687     if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
688     {
689         errno = err;
690         pid = -1;
691     }
692     if (pid == -1) FILE_SetDosError();
693     close( fd[0] );
694     if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
695     return pid;
696 }
697
698
699 /***********************************************************************
700  *           PROCESS_Create
701  *
702  * Create a new process. If hFile is a valid handle we have an exe
703  * file, and we exec a new copy of wine to load it; otherwise we
704  * simply exec the specified filename as a Unix process.
705  */
706 BOOL PROCESS_Create( HFILE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env, 
707                      LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
708                      BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
709                      LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
710 {
711     BOOL ret;
712     int pid;
713     const char *unixfilename = NULL;
714     const char *unixdir = NULL;
715     DOS_FULL_NAME full_name;
716     HANDLE load_done_evt = (HANDLE)-1;
717
718     info->hThread = info->hProcess = INVALID_HANDLE_VALUE;
719
720     if (lpCurrentDirectory)
721     {
722         if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_name ))
723             unixdir = full_name.long_name;
724     }
725     else
726     {
727         char buf[MAX_PATH];
728         if (GetCurrentDirectoryA(sizeof(buf),buf))
729         {
730             if (DOSFS_GetFullName( buf, TRUE, &full_name ))
731                 unixdir = full_name.long_name;
732         }
733     }
734
735     /* create the process on the server side */
736
737     SERVER_START_REQ
738     {
739         size_t len = (hFile == -1) ? 0 : MAX_PATH;
740         struct new_process_request *req = server_alloc_req( sizeof(*req), len );
741         req->inherit_all  = inherit;
742         req->create_flags = flags;
743         req->start_flags  = startup->dwFlags;
744         req->exe_file     = hFile;
745         if (startup->dwFlags & STARTF_USESTDHANDLES)
746         {
747             req->hstdin  = startup->hStdInput;
748             req->hstdout = startup->hStdOutput;
749             req->hstderr = startup->hStdError;
750         }
751         else
752         {
753             req->hstdin  = GetStdHandle( STD_INPUT_HANDLE );
754             req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
755             req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
756         }
757         req->cmd_show = startup->wShowWindow;
758         req->alloc_fd = 0;
759
760         if (hFile == -1)  /* unix process */
761         {
762             unixfilename = filename;
763             if (DOSFS_GetFullName( filename, TRUE, &full_name ))
764                 unixfilename = full_name.long_name;
765         }
766         else  /* new wine process */
767         {
768             if (!GetLongPathNameA( filename, server_data_ptr(req), MAX_PATH ))
769                 lstrcpynA( server_data_ptr(req), filename, MAX_PATH );
770         }
771         ret = !server_call( REQ_NEW_PROCESS );
772     }
773     SERVER_END_REQ;
774     if (!ret) return FALSE;
775
776     /* fork and execute */
777
778     pid = fork_and_exec( unixfilename, cmd_line, env, unixdir );
779
780     SERVER_START_REQ
781     {
782         struct wait_process_request *req = server_alloc_req( sizeof(*req), 0 );
783         req->cancel   = (pid == -1);
784         req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
785         req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
786         req->timeout  = 2000;
787         if ((ret = !server_call( REQ_WAIT_PROCESS )) && (pid != -1))
788         {
789             info->dwProcessId = (DWORD)req->pid;
790             info->dwThreadId  = (DWORD)req->tid;
791             info->hProcess    = req->phandle;
792             info->hThread     = req->thandle;
793             load_done_evt     = req->event;
794         }
795     }
796     SERVER_END_REQ;
797     if (!ret || (pid == -1)) goto error;
798
799     /* Wait until process is initialized (or initialization failed) */
800     if (load_done_evt != (HANDLE)-1)
801     {
802         DWORD res;
803         HANDLE handles[2];
804
805         handles[0] = info->hProcess;
806         handles[1] = load_done_evt;
807         res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
808         CloseHandle( load_done_evt );
809         if (res == STATUS_WAIT_0)  /* the process died */
810         {
811             DWORD exitcode;
812             if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
813             CloseHandle( info->hThread );
814             CloseHandle( info->hProcess );
815             return FALSE;
816         }
817     }
818     return TRUE;
819
820 error:
821     if (load_done_evt != (HANDLE)-1) CloseHandle( load_done_evt );
822     if (info->hThread != INVALID_HANDLE_VALUE) CloseHandle( info->hThread );
823     if (info->hProcess != INVALID_HANDLE_VALUE) CloseHandle( info->hProcess );
824     return FALSE;
825 }
826
827
828 /***********************************************************************
829  *           ExitProcess   (KERNEL32.100)
830  */
831 void WINAPI ExitProcess( DWORD status )
832 {
833     MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
834     SERVER_START_REQ
835     {
836         struct terminate_process_request *req = server_alloc_req( sizeof(*req), 0 );
837         /* send the exit code to the server */
838         req->handle    = GetCurrentProcess();
839         req->exit_code = status;
840         server_call( REQ_TERMINATE_PROCESS );
841     }
842     SERVER_END_REQ;
843     exit( status );
844 }
845
846 /***********************************************************************
847  *           ExitProcess16   (KERNEL.466)
848  */
849 void WINAPI ExitProcess16( WORD status )
850 {
851     DWORD count;
852     ReleaseThunkLock( &count );
853     ExitProcess( status );
854 }
855
856 /******************************************************************************
857  *           TerminateProcess   (KERNEL32.684)
858  */
859 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
860 {
861     NTSTATUS status = NtTerminateProcess( handle, exit_code );
862     if (status) SetLastError( RtlNtStatusToDosError(status) );
863     return !status;
864 }
865
866
867 /***********************************************************************
868  *           GetProcessDword    (KERNEL32.18) (KERNEL.485)
869  * 'Of course you cannot directly access Windows internal structures'
870  */
871 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
872 {
873     TDB *pTask;
874     DWORD x, y;
875
876     TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
877
878     if (dwProcessID && dwProcessID != GetCurrentProcessId())
879     {
880         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
881         return 0;
882     }
883
884     switch ( offset ) 
885     {
886     case GPD_APP_COMPAT_FLAGS:
887         pTask = (TDB *)GlobalLock16( GetCurrentTask() );
888         return pTask? pTask->compat_flags : 0;
889
890     case GPD_LOAD_DONE_EVENT:
891         return current_process.load_done_evt;
892
893     case GPD_HINSTANCE16:
894         pTask = (TDB *)GlobalLock16( GetCurrentTask() );
895         return pTask? pTask->hInstance : 0;
896
897     case GPD_WINDOWS_VERSION:
898         pTask = (TDB *)GlobalLock16( GetCurrentTask() );
899         return pTask? pTask->version : 0;
900
901     case GPD_THDB:
902         return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
903
904     case GPD_PDB:
905         return (DWORD)&current_process;
906
907     case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
908         return current_startupinfo.hStdOutput;
909
910     case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
911         return current_startupinfo.hStdInput;
912
913     case GPD_STARTF_SHOWWINDOW:
914         return current_startupinfo.wShowWindow;
915
916     case GPD_STARTF_SIZE:
917         x = current_startupinfo.dwXSize;
918         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
919         y = current_startupinfo.dwYSize;
920         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
921         return MAKELONG( x, y );
922
923     case GPD_STARTF_POSITION:
924         x = current_startupinfo.dwX;
925         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
926         y = current_startupinfo.dwY;
927         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
928         return MAKELONG( x, y );
929
930     case GPD_STARTF_FLAGS:
931         return current_startupinfo.dwFlags;
932
933     case GPD_PARENT:
934         return 0;
935
936     case GPD_FLAGS:
937         return current_process.flags;
938
939     case GPD_USERDATA:
940         return current_process.process_dword;
941
942     default:
943         ERR_(win32)("Unknown offset %d\n", offset );
944         return 0;
945     }
946 }
947
948 /***********************************************************************
949  *           SetProcessDword    (KERNEL.484)
950  * 'Of course you cannot directly access Windows internal structures'
951  */
952 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
953 {
954     TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
955
956     if (dwProcessID && dwProcessID != GetCurrentProcessId())
957     {
958         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
959         return;
960     }
961
962     switch ( offset ) 
963     {
964     case GPD_APP_COMPAT_FLAGS:
965     case GPD_LOAD_DONE_EVENT:
966     case GPD_HINSTANCE16:
967     case GPD_WINDOWS_VERSION:
968     case GPD_THDB:
969     case GPD_PDB:
970     case GPD_STARTF_SHELLDATA:
971     case GPD_STARTF_HOTKEY:
972     case GPD_STARTF_SHOWWINDOW:
973     case GPD_STARTF_SIZE:
974     case GPD_STARTF_POSITION:
975     case GPD_STARTF_FLAGS:
976     case GPD_PARENT:
977     case GPD_FLAGS:
978         ERR_(win32)("Not allowed to modify offset %d\n", offset );
979         break;
980
981     case GPD_USERDATA:
982         current_process.process_dword = value; 
983         break;
984
985     default:
986         ERR_(win32)("Unknown offset %d\n", offset );
987         break;
988     }
989 }
990
991
992 /*********************************************************************
993  *           OpenProcess   (KERNEL32.543)
994  */
995 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
996 {
997     HANDLE ret = 0;
998     SERVER_START_REQ
999     {
1000         struct open_process_request *req = server_alloc_req( sizeof(*req), 0 );
1001
1002         req->pid     = (void *)id;
1003         req->access  = access;
1004         req->inherit = inherit;
1005         if (!server_call( REQ_OPEN_PROCESS )) ret = req->handle;
1006     }
1007     SERVER_END_REQ;
1008     return ret;
1009 }
1010
1011 /*********************************************************************
1012  *           MapProcessHandle   (KERNEL.483)
1013  */
1014 DWORD WINAPI MapProcessHandle( HANDLE handle )
1015 {
1016     DWORD ret = 0;
1017     SERVER_START_REQ
1018     {
1019         struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1020         req->handle = handle;
1021         if (!server_call( REQ_GET_PROCESS_INFO )) ret = (DWORD)req->pid;
1022     }
1023     SERVER_END_REQ;
1024     return ret;
1025 }
1026
1027 /***********************************************************************
1028  *           SetPriorityClass   (KERNEL32.503)
1029  */
1030 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1031 {
1032     BOOL ret;
1033     SERVER_START_REQ
1034     {
1035         struct set_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1036         req->handle   = hprocess;
1037         req->priority = priorityclass;
1038         req->mask     = SET_PROCESS_INFO_PRIORITY;
1039         ret = !server_call( REQ_SET_PROCESS_INFO );
1040     }
1041     SERVER_END_REQ;
1042     return ret;
1043 }
1044
1045
1046 /***********************************************************************
1047  *           GetPriorityClass   (KERNEL32.250)
1048  */
1049 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1050 {
1051     DWORD ret = 0;
1052     SERVER_START_REQ
1053     {
1054         struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1055         req->handle = hprocess;
1056         if (!server_call( REQ_GET_PROCESS_INFO )) ret = req->priority;
1057     }
1058     SERVER_END_REQ;
1059     return ret;
1060 }
1061
1062
1063 /***********************************************************************
1064  *          SetProcessAffinityMask   (KERNEL32.662)
1065  */
1066 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1067 {
1068     BOOL ret;
1069     SERVER_START_REQ
1070     {
1071         struct set_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1072         req->handle   = hProcess;
1073         req->affinity = affmask;
1074         req->mask     = SET_PROCESS_INFO_AFFINITY;
1075         ret = !server_call( REQ_SET_PROCESS_INFO );
1076     }
1077     SERVER_END_REQ;
1078     return ret;
1079 }
1080
1081 /**********************************************************************
1082  *          GetProcessAffinityMask    (KERNEL32.373)
1083  */
1084 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1085                                       LPDWORD lpProcessAffinityMask,
1086                                       LPDWORD lpSystemAffinityMask )
1087 {
1088     BOOL ret = FALSE;
1089     SERVER_START_REQ
1090     {
1091         struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1092         req->handle = hProcess;
1093         if (!server_call( REQ_GET_PROCESS_INFO ))
1094         {
1095             if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1096             if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1097             ret = TRUE;
1098         }
1099     }
1100     SERVER_END_REQ;
1101     return ret;
1102 }
1103
1104
1105 /***********************************************************************
1106  *           GetProcessVersion    (KERNEL32)
1107  */
1108 DWORD WINAPI GetProcessVersion( DWORD processid )
1109 {
1110     IMAGE_NT_HEADERS *nt;
1111
1112     if (processid && processid != GetCurrentProcessId())
1113         return 0;  /* FIXME: should use ReadProcessMemory */
1114     if ((nt = RtlImageNtHeader( current_process.module )))
1115         return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1116                 nt->OptionalHeader.MinorSubsystemVersion);
1117     return 0;
1118 }
1119
1120 /***********************************************************************
1121  *           GetProcessFlags    (KERNEL32)
1122  */
1123 DWORD WINAPI GetProcessFlags( DWORD processid )
1124 {
1125     if (processid && processid != GetCurrentProcessId()) return 0;
1126     return current_process.flags;
1127 }
1128
1129
1130 /***********************************************************************
1131  *              SetProcessWorkingSetSize        [KERNEL32.662]
1132  * Sets the min/max working set sizes for a specified process.
1133  *
1134  * PARAMS
1135  *    hProcess [I] Handle to the process of interest
1136  *    minset   [I] Specifies minimum working set size
1137  *    maxset   [I] Specifies maximum working set size
1138  *
1139  * RETURNS  STD
1140  */
1141 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1142                                        DWORD maxset)
1143 {
1144     FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1145     if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1146         /* Trim the working set to zero */
1147         /* Swap the process out of physical RAM */
1148     }
1149     return TRUE;
1150 }
1151
1152 /***********************************************************************
1153  *           GetProcessWorkingSetSize    (KERNEL32)
1154  */
1155 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1156                                        LPDWORD maxset)
1157 {
1158         FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1159         /* 32 MB working set size */
1160         if (minset) *minset = 32*1024*1024;
1161         if (maxset) *maxset = 32*1024*1024;
1162         return TRUE;
1163 }
1164
1165 /***********************************************************************
1166  *           SetProcessShutdownParameters    (KERNEL32)
1167  *
1168  * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1169  * Now tracks changes made (but does not act on these changes)
1170  */
1171 static DWORD shutdown_flags = 0;
1172 static DWORD shutdown_priority = 0x280;
1173
1174 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1175 {
1176     FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1177     shutdown_flags = flags;
1178     shutdown_priority = level;
1179     return TRUE;
1180 }
1181
1182
1183 /***********************************************************************
1184  * GetProcessShutdownParameters                 (KERNEL32)
1185  *
1186  */
1187 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1188 {
1189     *lpdwLevel = shutdown_priority;
1190     *lpdwFlags = shutdown_flags;
1191     return TRUE;
1192 }
1193
1194
1195 /***********************************************************************
1196  *           SetProcessPriorityBoost    (KERNEL32)
1197  */
1198 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1199 {
1200     FIXME("(%d,%d): stub\n",hprocess,disableboost);
1201     /* Say we can do it. I doubt the program will notice that we don't. */
1202     return TRUE;
1203 }
1204
1205
1206 /***********************************************************************
1207  *           ReadProcessMemory                  (KERNEL32)
1208  */
1209 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1210                                LPDWORD bytes_read )
1211 {
1212     unsigned int offset = (unsigned int)addr % sizeof(int);
1213     unsigned int pos = 0, len, max;
1214     int res;
1215
1216     if (bytes_read) *bytes_read = size;
1217
1218     /* first time, read total length to check for permissions */
1219     len = (size + offset + sizeof(int) - 1) / sizeof(int);
1220     max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1221
1222     for (;;)
1223     {
1224         SERVER_START_REQ
1225         {
1226             struct read_process_memory_request *req = server_alloc_req( sizeof(*req), max );
1227             req->handle = process;
1228             req->addr   = (char *)addr + pos - offset;
1229             req->len    = len;
1230             if (!(res = server_call( REQ_READ_PROCESS_MEMORY )))
1231             {
1232                 size_t result = server_data_size( req );
1233                 if (result > size + offset) result = size + offset;
1234                 memcpy( (char *)buffer + pos, server_data_ptr(req) + offset, result - offset );
1235                 size -= result - offset;
1236                 pos += result - offset;
1237             }
1238         }
1239         SERVER_END_REQ;
1240         if (res)
1241         {
1242             if (bytes_read) *bytes_read = 0;
1243             return FALSE;
1244         }
1245         if (!size) return TRUE;
1246         max = min( REQUEST_MAX_VAR_SIZE, size );
1247         len = (max + sizeof(int) - 1) / sizeof(int);
1248         offset = 0;
1249     }
1250 }
1251
1252
1253 /***********************************************************************
1254  *           WriteProcessMemory                 (KERNEL32)
1255  */
1256 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1257                                 LPDWORD bytes_written )
1258 {
1259     unsigned int first_offset, last_offset;
1260     unsigned int pos = 0, len, max, first_mask, last_mask;
1261     int res;
1262
1263     if (!size)
1264     {
1265         SetLastError( ERROR_INVALID_PARAMETER );
1266         return FALSE;
1267     }
1268     if (bytes_written) *bytes_written = size;
1269
1270     /* compute the mask for the first int */
1271     first_mask = ~0;
1272     first_offset = (unsigned int)addr % sizeof(int);
1273     memset( &first_mask, 0, first_offset );
1274
1275     /* compute the mask for the last int */
1276     last_offset = (size + first_offset) % sizeof(int);
1277     last_mask = 0;
1278     memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1279
1280     /* for the first request, use the total length */
1281     len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1282     max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1283
1284     for (;;)
1285     {
1286         SERVER_START_REQ
1287         {
1288             struct write_process_memory_request *req = server_alloc_req( sizeof(*req), max );
1289             req->handle = process;
1290             req->addr = (char *)addr - first_offset + pos;
1291             req->len = len;
1292             req->first_mask = (!pos) ? first_mask : ~0;
1293             if (size + first_offset <= max)  /* last round */
1294             {
1295                 req->last_mask = last_mask;
1296                 max = size + first_offset;
1297             }
1298             else req->last_mask = ~0;
1299
1300             memcpy( (char *)server_data_ptr(req) + first_offset, (char *)buffer + pos,
1301                     max - first_offset );
1302             if (!(res = server_call( REQ_WRITE_PROCESS_MEMORY )))
1303             {
1304                 pos += max - first_offset;
1305                 size -= max - first_offset;
1306             }
1307         }
1308         SERVER_END_REQ;
1309         if (res)
1310         {
1311             if (bytes_written) *bytes_written = 0;
1312             return FALSE;
1313         }
1314         if (!size) return TRUE;
1315         first_offset = 0;
1316         len = min( size + sizeof(int) - 1, REQUEST_MAX_VAR_SIZE ) / sizeof(int);
1317         max = len * sizeof(int);
1318     }
1319 }
1320
1321
1322 /***********************************************************************
1323  *           RegisterServiceProcess             (KERNEL, KERNEL32)
1324  *
1325  * A service process calls this function to ensure that it continues to run
1326  * even after a user logged off.
1327  */
1328 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1329 {
1330         /* I don't think that Wine needs to do anything in that function */
1331         return 1; /* success */
1332 }
1333
1334 /***********************************************************************
1335  * GetExitCodeProcess [KERNEL32.325]
1336  *
1337  * Gets termination status of specified process
1338  * 
1339  * RETURNS
1340  *   Success: TRUE
1341  *   Failure: FALSE
1342  */
1343 BOOL WINAPI GetExitCodeProcess(
1344     HANDLE hProcess,    /* [in] handle to the process */
1345     LPDWORD lpExitCode) /* [out] address to receive termination status */
1346 {
1347     BOOL ret;
1348     SERVER_START_REQ
1349     {
1350         struct get_process_info_request *req = server_alloc_req( sizeof(*req), 0 );
1351         req->handle = hProcess;
1352         ret = !server_call( REQ_GET_PROCESS_INFO );
1353         if (ret && lpExitCode) *lpExitCode = req->exit_code;
1354     }
1355     SERVER_END_REQ;
1356     return ret;
1357 }
1358
1359
1360 /***********************************************************************
1361  *           SetErrorMode   (KERNEL32.486)
1362  */
1363 UINT WINAPI SetErrorMode( UINT mode )
1364 {
1365     UINT old = current_process.error_mode;
1366     current_process.error_mode = mode;
1367     return old;
1368 }
1369
1370 /***********************************************************************
1371  *           GetCurrentProcess   (KERNEL32.198)
1372  */
1373 #undef GetCurrentProcess
1374 HANDLE WINAPI GetCurrentProcess(void)
1375 {
1376     return 0xffffffff;
1377 }