Properly save/restore %gs register across 16-bit calls.
[wine] / scheduler / process.c
1 /*
2  * Win32 processes
3  *
4  * Copyright 1996, 1998 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35 #include "wine/winbase16.h"
36 #include "wine/winuser16.h"
37 #include "wine/exception.h"
38 #include "wine/library.h"
39 #include "drive.h"
40 #include "module.h"
41 #include "file.h"
42 #include "heap.h"
43 #include "thread.h"
44 #include "winerror.h"
45 #include "wincon.h"
46 #include "wine/server.h"
47 #include "options.h"
48 #include "wine/debug.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(process);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
52 WINE_DECLARE_DEBUG_CHANNEL(snoop);
53 WINE_DECLARE_DEBUG_CHANNEL(win32);
54
55 struct _ENVDB;
56
57 /* Win32 process database */
58 typedef struct _PDB
59 {
60     LONG             header[2];        /* 00 Kernel object header */
61     HMODULE          module;           /* 08 Main exe module (NT) */
62     void            *event;            /* 0c Pointer to an event object (unused) */
63     DWORD            exit_code;        /* 10 Process exit code */
64     DWORD            unknown2;         /* 14 Unknown */
65     HANDLE           heap;             /* 18 Default process heap */
66     HANDLE           mem_context;      /* 1c Process memory context */
67     DWORD            flags;            /* 20 Flags */
68     void            *pdb16;            /* 24 DOS PSP */
69     WORD             PSP_sel;          /* 28 Selector to DOS PSP */
70     WORD             imte;             /* 2a IMTE for the process module */
71     WORD             threads;          /* 2c Number of threads */
72     WORD             running_threads;  /* 2e Number of running threads */
73     WORD             free_lib_count;   /* 30 Recursion depth of FreeLibrary calls */
74     WORD             ring0_threads;    /* 32 Number of ring 0 threads */
75     HANDLE           system_heap;      /* 34 System heap to allocate handles */
76     HTASK            task;             /* 38 Win16 task */
77     void            *mem_map_files;    /* 3c Pointer to mem-mapped files */
78     struct _ENVDB   *env_db;           /* 40 Environment database */
79     void            *handle_table;     /* 44 Handle table */
80     struct _PDB     *parent;           /* 48 Parent process */
81     void            *modref_list;      /* 4c MODREF list */
82     void            *thread_list;      /* 50 List of threads */
83     void            *debuggee_CB;      /* 54 Debuggee context block */
84     void            *local_heap_free;  /* 58 Head of local heap free list */
85     DWORD            unknown4;         /* 5c Unknown */
86     CRITICAL_SECTION crit_section;     /* 60 Critical section */
87     DWORD            unknown5[3];      /* 78 Unknown */
88     void            *console;          /* 84 Console */
89     DWORD            tls_bits[2];      /* 88 TLS in-use bits */
90     DWORD            process_dword;    /* 90 Unknown */
91     struct _PDB     *group;            /* 94 Process group */
92     void            *exe_modref;       /* 98 MODREF for the process EXE */
93     void            *top_filter;       /* 9c Top exception filter */
94     DWORD            priority;         /* a0 Priority level */
95     HANDLE           heap_list;        /* a4 Head of process heap list */
96     void            *heap_handles;     /* a8 Head of heap handles list */
97     DWORD            unknown6;         /* ac Unknown */
98     void            *console_provider; /* b0 Console provider (??) */
99     WORD             env_selector;     /* b4 Selector to process environment */
100     WORD             error_mode;       /* b6 Error mode */
101     HANDLE           load_done_evt;    /* b8 Event for process loading done */
102     void            *UTState;          /* bc Head of Univeral Thunk list */
103     DWORD            unknown8;         /* c0 Unknown (NT) */
104     LCID             locale;           /* c4 Locale to be queried by GetThreadLocale (NT) */
105 } PDB;
106
107 PDB current_process;
108
109 /* Process flags */
110 #define PDB32_DEBUGGED      0x0001  /* Process is being debugged */
111 #define PDB32_WIN16_PROC    0x0008  /* Win16 process */
112 #define PDB32_DOS_PROC      0x0010  /* Dos process */
113 #define PDB32_CONSOLE_PROC  0x0020  /* Console process */
114 #define PDB32_FILE_APIS_OEM 0x0040  /* File APIs are OEM */
115 #define PDB32_WIN32S_PROC   0x8000  /* Win32s process */
116
117 static char main_exe_name[MAX_PATH];
118 static char *main_exe_name_ptr = main_exe_name;
119 static HANDLE main_exe_file;
120 static unsigned int server_startticks;
121
122 int main_create_flags = 0;
123
124 /* memory/environ.c */
125 extern struct _ENVDB *ENV_InitStartupInfo( size_t info_size, char *main_exe_name,
126                                            size_t main_exe_size );
127 extern BOOL ENV_BuildCommandLine( char **argv );
128 extern STARTUPINFOA current_startupinfo;
129
130 /* scheduler/pthread.c */
131 extern void PTHREAD_init_done(void);
132
133 extern void RELAY_InitDebugLists(void);
134 extern BOOL MAIN_MainInit(void);
135
136 typedef WORD (WINAPI *pUserSignalProc)( UINT, DWORD, DWORD, HMODULE16 );
137
138 /***********************************************************************
139  *           PROCESS_CallUserSignalProc
140  *
141  * FIXME:  Some of the signals aren't sent correctly!
142  *
143  * The exact meaning of the USER signals is undocumented, but this
144  * should cover the basic idea:
145  *
146  * USIG_DLL_UNLOAD_WIN16
147  *     This is sent when a 16-bit module is unloaded.
148  *
149  * USIG_DLL_UNLOAD_WIN32
150  *     This is sent when a 32-bit module is unloaded.
151  *
152  * USIG_DLL_UNLOAD_ORPHANS
153  *     This is sent after the last Win3.1 module is unloaded,
154  *     to allow removal of orphaned menus.
155  *
156  * USIG_FAULT_DIALOG_PUSH
157  * USIG_FAULT_DIALOG_POP
158  *     These are called to allow USER to prepare for displaying a
159  *     fault dialog, even though the fault might have happened while
160  *     inside a USER critical section.
161  *
162  * USIG_THREAD_INIT
163  *     This is called from the context of a new thread, as soon as it
164  *     has started to run.
165  *
166  * USIG_THREAD_EXIT
167  *     This is called, still in its context, just before a thread is
168  *     about to terminate.
169  *
170  * USIG_PROCESS_CREATE
171  *     This is called, in the parent process context, after a new process
172  *     has been created.
173  *
174  * USIG_PROCESS_INIT
175  *     This is called in the new process context, just after the main thread
176  *     has started execution (after the main thread's USIG_THREAD_INIT has
177  *     been sent).
178  *
179  * USIG_PROCESS_LOADED
180  *     This is called after the executable file has been loaded into the
181  *     new process context.
182  *
183  * USIG_PROCESS_RUNNING
184  *     This is called immediately before the main entry point is called.
185  *
186  * USIG_PROCESS_EXIT
187  *     This is called in the context of a process that is about to
188  *     terminate (but before the last thread's USIG_THREAD_EXIT has
189  *     been sent).
190  *
191  * USIG_PROCESS_DESTROY
192  *     This is called after a process has terminated.
193  *
194  *
195  * The meaning of the dwFlags bits is as follows:
196  *
197  * USIG_FLAGS_WIN32
198  *     Current process is 32-bit.
199  *
200  * USIG_FLAGS_GUI
201  *     Current process is a (Win32) GUI process.
202  *
203  * USIG_FLAGS_FEEDBACK
204  *     Current process needs 'feedback' (determined from the STARTUPINFO
205  *     flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
206  *
207  * USIG_FLAGS_FAULT
208  *     The signal is being sent due to a fault.
209  */
210 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
211 {
212     DWORD dwFlags = 0;
213     HMODULE user;
214     pUserSignalProc proc;
215
216     if (!(user = GetModuleHandleA( "user32.dll" ))) return;
217     if (!(proc = (pUserSignalProc)GetProcAddress( user, "UserSignalProc" ))) return;
218
219     /* Determine dwFlags */
220
221     if ( !(current_process.flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
222     if ( !(current_process.flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
223
224     if ( dwFlags & USIG_FLAGS_GUI )
225     {
226         /* Feedback defaults to ON */
227         if ( !(current_startupinfo.dwFlags & STARTF_FORCEOFFFEEDBACK) )
228             dwFlags |= USIG_FLAGS_FEEDBACK;
229     }
230     else
231     {
232         /* Feedback defaults to OFF */
233         if (current_startupinfo.dwFlags & STARTF_FORCEONFEEDBACK)
234             dwFlags |= USIG_FLAGS_FEEDBACK;
235     }
236
237     /* Call USER signal proc */
238
239     if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
240         proc( uCode, GetCurrentThreadId(), dwFlags, hModule );
241     else
242         proc( uCode, GetCurrentProcessId(), dwFlags, hModule );
243 }
244
245
246 /***********************************************************************
247  *           get_basename
248  */
249 inline static const char *get_basename( const char *name )
250 {
251     char *p;
252
253     if ((p = strrchr( name, '/' ))) name = p + 1;
254     if ((p = strrchr( name, '\\' ))) name = p + 1;
255     return name;
256 }
257
258
259 /***********************************************************************
260  *           open_builtin_exe_file
261  *
262  * Open an exe file for a builtin exe.
263  */
264 static void *open_builtin_exe_file( const char *name, char *error, int error_size, int test_only )
265 {
266     char exename[MAX_PATH], *p;
267     const char *basename = get_basename(name);
268
269     if (strlen(basename) >= sizeof(exename)) return NULL;
270     strcpy( exename, basename );
271     for (p = exename; *p; p++) *p = FILE_tolower(*p);
272     return wine_dll_load_main_exe( exename, error, error_size, test_only );
273 }
274
275
276 /***********************************************************************
277  *           open_exe_file
278  *
279  * Open a specific exe file, taking load order into account.
280  * Returns the file handle or 0 for a builtin exe.
281  */
282 static HANDLE open_exe_file( const char *name )
283 {
284     enum loadorder_type loadorder[LOADORDER_NTYPES];
285     char buffer[MAX_PATH];
286     HANDLE handle;
287     int i;
288
289     TRACE("looking for %s\n", debugstr_a(name) );
290
291     if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
292                                NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
293     {
294         /* file doesn't exist, check for builtin */
295         if (!FILE_contains_path( name )) goto error;
296         if (!MODULE_GetBuiltinPath( name, "", buffer, sizeof(buffer) )) goto error;
297         name = buffer;
298     }
299
300     MODULE_GetLoadOrder( loadorder, name, TRUE );
301
302     for(i = 0; i < LOADORDER_NTYPES; i++)
303     {
304         if (loadorder[i] == LOADORDER_INVALID) break;
305         switch(loadorder[i])
306         {
307         case LOADORDER_DLL:
308             TRACE( "Trying native exe %s\n", debugstr_a(name) );
309             if (handle != INVALID_HANDLE_VALUE) return handle;
310             break;
311         case LOADORDER_BI:
312             TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
313             if (open_builtin_exe_file( name, NULL, 0, 1 ))
314             {
315                 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
316                 return 0;
317             }
318         default:
319             break;
320         }
321     }
322     if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
323
324  error:
325     SetLastError( ERROR_FILE_NOT_FOUND );
326     return INVALID_HANDLE_VALUE;
327 }
328
329
330 /***********************************************************************
331  *           find_exe_file
332  *
333  * Open an exe file, and return the full name and file handle.
334  * Returns FALSE if file could not be found.
335  * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
336  * If file is a builtin exe, returns TRUE and sets handle to 0.
337  */
338 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
339 {
340     enum loadorder_type loadorder[LOADORDER_NTYPES];
341     int i;
342
343     TRACE("looking for %s\n", debugstr_a(name) );
344
345     if (!SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) &&
346         !MODULE_GetBuiltinPath( name, ".exe", buffer, buflen ))
347     {
348         /* no builtin found, try native without extension in case it is a Unix app */
349
350         if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
351         {
352             TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
353             if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
354                                         NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
355                 return TRUE;
356         }
357         return FALSE;
358     }
359
360     MODULE_GetLoadOrder( loadorder, buffer, TRUE );
361
362     for(i = 0; i < LOADORDER_NTYPES; i++)
363     {
364         if (loadorder[i] == LOADORDER_INVALID) break;
365         switch(loadorder[i])
366         {
367         case LOADORDER_DLL:
368             TRACE( "Trying native exe %s\n", debugstr_a(buffer) );
369             if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
370                                         NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
371                 return TRUE;
372             if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
373             break;
374         case LOADORDER_BI:
375             TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
376             if (open_builtin_exe_file( buffer, NULL, 0, 1 ))
377             {
378                 *handle = 0;
379                 return TRUE;
380             }
381             break;
382         default:
383             break;
384         }
385     }
386     SetLastError( ERROR_FILE_NOT_FOUND );
387     return FALSE;
388 }
389
390
391 /***********************************************************************
392  *           process_init
393  *
394  * Main process initialisation code
395  */
396 static BOOL process_init( char *argv[] )
397 {
398     BOOL ret;
399     size_t info_size = 0;
400
401     /* store the program name */
402     argv0 = argv[0];
403
404     /* Fill the initial process structure */
405     current_process.exit_code       = STILL_ACTIVE;
406     current_process.threads         = 1;
407     current_process.running_threads = 1;
408     current_process.ring0_threads   = 1;
409     current_process.group           = &current_process;
410     current_process.priority        = 8;  /* Normal */
411
412     /* Setup the server connection */
413     CLIENT_InitServer();
414
415     /* Retrieve startup info from the server */
416     SERVER_START_REQ( init_process )
417     {
418         req->ldt_copy  = &wine_ldt_copy;
419         if ((ret = !wine_server_call_err( req )))
420         {
421             main_exe_file     = reply->exe_file;
422             main_create_flags = reply->create_flags;
423             info_size         = reply->info_size;
424             server_startticks = reply->server_start;
425             current_startupinfo.hStdInput   = reply->hstdin;
426             current_startupinfo.hStdOutput  = reply->hstdout;
427             current_startupinfo.hStdError   = reply->hstderr;
428         }
429     }
430     SERVER_END_REQ;
431     if (!ret) return FALSE;
432
433     /* Create the process heap */
434     current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
435
436     if (main_create_flags == 0 &&
437         current_startupinfo.hStdInput  == 0 &&
438         current_startupinfo.hStdOutput == 0 &&
439         current_startupinfo.hStdError  == 0)
440     {
441         /* no parent, and no new console requested, create a simple console with bare handles to
442          * unix stdio input & output streams (aka simple console)
443          */
444         HANDLE handle;
445         wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &handle );
446         SetStdHandle( STD_INPUT_HANDLE, handle );
447         wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
448         SetStdHandle( STD_OUTPUT_HANDLE, handle );
449         wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
450         SetStdHandle( STD_ERROR_HANDLE, handle );
451     }
452     else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
453     {
454         SetStdHandle( STD_INPUT_HANDLE,  current_startupinfo.hStdInput  );
455         SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
456         SetStdHandle( STD_ERROR_HANDLE,  current_startupinfo.hStdError  );
457     }
458
459     /* Now we can use the pthreads routines */
460     PTHREAD_init_done();
461
462     /* Copy the parent environment */
463     if (!(current_process.env_db = ENV_InitStartupInfo( info_size, main_exe_name,
464                                                         sizeof(main_exe_name) )))
465         return FALSE;
466
467     /* Parse command line arguments */
468     OPTIONS_ParseOptions( !info_size ? argv : NULL );
469
470     ret = MAIN_MainInit();
471     if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
472
473     return ret;
474 }
475
476
477 /***********************************************************************
478  *           start_process
479  *
480  * Startup routine of a new process. Runs on the new process stack.
481  */
482 static void start_process(void)
483 {
484     int debugged, console_app;
485     LPTHREAD_START_ROUTINE entry;
486     WINE_MODREF *wm;
487     HANDLE main_file = main_exe_file;
488     IMAGE_NT_HEADERS *nt;
489
490     /* use original argv[0] as name for the main module */
491     if (!main_exe_name[0])
492     {
493         if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
494             lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
495     }
496
497     if (main_file)
498     {
499         UINT drive_type = GetDriveTypeA( main_exe_name );
500         /* don't keep the file handle open on removable media */
501         if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
502     }
503
504     /* Retrieve entry point address */
505     nt = RtlImageNtHeader( current_process.module );
506     entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
507                                      nt->OptionalHeader.AddressOfEntryPoint);
508     console_app = (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
509     if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
510
511     /* Signal the parent process to continue */
512     SERVER_START_REQ( init_process_done )
513     {
514         req->module      = (void *)current_process.module;
515         req->module_size = nt->OptionalHeader.SizeOfImage;
516         req->entry    = entry;
517         /* API requires a double indirection */
518         req->name     = &main_exe_name_ptr;
519         req->exe_file = main_file;
520         req->gui      = !console_app;
521         wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
522         wine_server_call( req );
523         debugged = reply->debugged;
524     }
525     SERVER_END_REQ;
526
527     /* Install signal handlers; this cannot be done before, since we cannot
528      * send exceptions to the debugger before the create process event that
529      * is sent by REQ_INIT_PROCESS_DONE */
530     if (!SIGNAL_Init()) goto error;
531
532     /* create the main modref and load dependencies */
533     if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
534         goto error;
535     wm->refCount++;
536
537     if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
538
539     MODULE_DllProcessAttach( NULL, (LPVOID)1 );
540
541     /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
542      *       context of the parent process.  Actually, the USER signal proc
543      *       doesn't really care about that, but it *does* require that the
544      *       startup parameters are correctly set up, so that GetProcessDword
545      *       works.  Furthermore, before calling the USER signal proc the
546      *       16-bit stack must be set up, which it is only after TASK_Create
547      *       in the case of a 16-bit process. Thus, we send the signal here.
548      */
549     PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
550     PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
551     PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
552     PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
553     /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
554     if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
555
556     if (TRACE_ON(relay))
557         DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n",
558                  GetCurrentThreadId(), main_exe_name, entry );
559     if (debugged) DbgBreakPoint();
560     /* FIXME: should use _PEB as parameter for NT 3.5 programs !
561      * Dunno about other OSs */
562     SetLastError(0);  /* clear error code */
563     ExitThread( entry(NULL) );
564
565  error:
566     ExitProcess( GetLastError() );
567 }
568
569
570 /***********************************************************************
571  *           PROCESS_InitWine
572  *
573  * Wine initialisation: load and start the main exe file.
574  */
575 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
576 {
577     char error[1024], *p;
578     DWORD stack_size = 0;
579
580     /* Initialize everything */
581     if (!process_init( argv )) exit(1);
582
583     argv++;  /* remove argv[0] (wine itself) */
584
585     TRACE( "starting process name=%s file=%p argv[0]=%s\n",
586            debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
587
588     if (!main_exe_name[0])
589     {
590         if (!argv[0]) OPTIONS_Usage();
591
592         if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
593         {
594             MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
595             ExitProcess(1);
596         }
597         if (main_exe_file == INVALID_HANDLE_VALUE)
598         {
599             MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
600             ExitProcess(1);
601         }
602     }
603
604     if (!main_exe_file)  /* no file handle -> Winelib app */
605     {
606         TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
607         if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0 ))
608             goto found;
609         MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
610         ExitProcess(1);
611     }
612
613     switch( MODULE_GetBinaryType( main_exe_file ))
614     {
615     case BINARY_PE_EXE:
616         TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
617         if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
618         MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
619         ExitProcess(1);
620     case BINARY_PE_DLL:
621         MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
622         ExitProcess(1);
623     case BINARY_UNKNOWN:
624         /* check for .com extension */
625         if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
626         {
627             MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
628             ExitProcess(1);
629         }
630         /* fall through */
631     case BINARY_WIN16:
632     case BINARY_DOS:
633         TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
634         NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
635         current_process.flags |= PDB32_WIN16_PROC;
636         strcpy( win16_exe_name, main_exe_name );
637         main_exe_name[0] = 0;
638         *win16_exe_file = main_exe_file;
639         main_exe_file = 0;
640         _EnterWin16Lock();
641         goto found;
642     case BINARY_OS216:
643         MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
644         ExitProcess(1);
645     case BINARY_UNIX_EXE:
646         MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
647         ExitProcess(1);
648     case BINARY_UNIX_LIB:
649         {
650             DOS_FULL_NAME full_name;
651             const char *name = main_exe_name;
652             UNICODE_STRING nameW;
653
654             TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
655             RtlCreateUnicodeStringFromAsciiz(&nameW, name);
656             if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
657             RtlFreeUnicodeString(&nameW);
658             CloseHandle( main_exe_file );
659             main_exe_file = 0;
660             if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
661             {
662                 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
663                 goto found;
664             }
665             MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
666             ExitProcess(1);
667         }
668     }
669
670  found:
671     /* build command line */
672     if (!ENV_BuildCommandLine( argv )) goto error;
673
674     /* create 32-bit module for main exe */
675     if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
676     stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
677
678     /* allocate main thread stack */
679     if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
680
681     /* switch to the new stack */
682     SYSDEPS_SwitchToThreadStack( start_process );
683
684  error:
685     ExitProcess( GetLastError() );
686 }
687
688
689 /***********************************************************************
690  *           build_argv
691  *
692  * Build an argv array from a command-line.
693  * The command-line is modified to insert nulls.
694  * 'reserved' is the number of args to reserve before the first one.
695  */
696 static char **build_argv( char *cmdline, int reserved )
697 {
698     int argc;
699     char** argv;
700     char *arg,*s,*d;
701     int in_quotes,bcount;
702
703     argc=reserved+1;
704     bcount=0;
705     in_quotes=0;
706     s=cmdline;
707     while (1) {
708         if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
709             /* space */
710             argc++;
711             /* skip the remaining spaces */
712             while (*s==' ' || *s=='\t') {
713                 s++;
714             }
715             if (*s=='\0')
716                 break;
717             bcount=0;
718             continue;
719         } else if (*s=='\\') {
720             /* '\', count them */
721             bcount++;
722         } else if ((*s=='"') && ((bcount & 1)==0)) {
723             /* unescaped '"' */
724             in_quotes=!in_quotes;
725             bcount=0;
726         } else {
727             /* a regular character */
728             bcount=0;
729         }
730         s++;
731     }
732     argv=malloc(argc*sizeof(*argv));
733     if (!argv)
734         return NULL;
735
736     arg=d=s=cmdline;
737     bcount=0;
738     in_quotes=0;
739     argc=reserved;
740     while (*s) {
741         if ((*s==' ' || *s=='\t') && !in_quotes) {
742             /* Close the argument and copy it */
743             *d=0;
744             argv[argc++]=arg;
745
746             /* skip the remaining spaces */
747             do {
748                 s++;
749             } while (*s==' ' || *s=='\t');
750
751             /* Start with a new argument */
752             arg=d=s;
753             bcount=0;
754         } else if (*s=='\\') {
755             /* '\\' */
756             *d++=*s++;
757             bcount++;
758         } else if (*s=='"') {
759             /* '"' */
760             if ((bcount & 1)==0) {
761                 /* Preceeded by an even number of '\', this is half that
762                  * number of '\', plus a '"' which we discard.
763                  */
764                 d-=bcount/2;
765                 s++;
766                 in_quotes=!in_quotes;
767             } else {
768                 /* Preceeded by an odd number of '\', this is half that
769                  * number of '\' followed by a '"'
770                  */
771                 d=d-bcount/2-1;
772                 *d++='"';
773                 s++;
774             }
775             bcount=0;
776         } else {
777             /* a regular character */
778             *d++=*s++;
779             bcount=0;
780         }
781     }
782     if (*arg) {
783         *d='\0';
784         argv[argc++]=arg;
785     }
786     argv[argc]=NULL;
787
788     return argv;
789 }
790
791
792 /***********************************************************************
793  *           build_envp
794  *
795  * Build the environment of a new child process.
796  */
797 static char **build_envp( const char *env, const char *extra_env )
798 {
799     const char *p;
800     char **envp;
801     int count = 0;
802
803     if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
804     for (p = env; *p; count++) p += strlen(p) + 1;
805     count += 3;
806
807     if ((envp = malloc( count * sizeof(*envp) )))
808     {
809         extern char **environ;
810         char **envptr = envp;
811         char **unixptr = environ;
812         /* first the extra strings */
813         if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
814         /* then put PATH, HOME and WINEPREFIX from the unix env */
815         for (unixptr = environ; unixptr && *unixptr; unixptr++)
816             if (!memcmp( *unixptr, "PATH=", 5 ) ||
817                 !memcmp( *unixptr, "HOME=", 5 ) ||
818                 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
819         /* now put the Windows environment strings */
820         for (p = env; *p; p += strlen(p) + 1)
821         {
822             if (!memcmp( p, "PATH=", 5 ))  /* store PATH as WINEPATH */
823             {
824                 char *winepath = malloc( strlen(p) + 5 );
825                 strcpy( winepath, "WINE" );
826                 strcpy( winepath + 4, p );
827                 *envptr++ = winepath;
828             }
829             else if (memcmp( p, "HOME=", 5 ) &&
830                      memcmp( p, "WINEPATH=", 9 ) &&
831                      memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
832         }
833         *envptr = 0;
834     }
835     return envp;
836 }
837
838
839 /***********************************************************************
840  *           exec_wine_binary
841  *
842  * Locate the Wine binary to exec for a new Win32 process.
843  */
844 static void exec_wine_binary( char **argv, char **envp )
845 {
846     const char *path, *pos, *ptr;
847
848     /* first, try for a WINELOADER environment variable */
849     argv[0] = getenv("WINELOADER");
850     if (argv[0])
851         execve( argv[0], argv, envp );
852
853     /* next, try bin directory */
854     argv[0] = BINDIR "/wine";
855     execve( argv[0], argv, envp );
856
857     /* now try the path of argv0 of the current binary */
858     if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
859     if ((ptr = strrchr( full_argv0, '/' )))
860     {
861         memcpy( argv[0], full_argv0, ptr - full_argv0 );
862         strcpy( argv[0] + (ptr - full_argv0), "/wine" );
863         execve( argv[0], argv, envp );
864     }
865     free( argv[0] );
866
867     /* now search in the Unix path */
868     if ((path = getenv( "PATH" )))
869     {
870         if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
871         pos = path;
872         for (;;)
873         {
874             while (*pos == ':') pos++;
875             if (!*pos) break;
876             if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
877             memcpy( argv[0], pos, ptr - pos );
878             strcpy( argv[0] + (ptr - pos), "/wine" );
879             execve( argv[0], argv, envp );
880             pos = ptr;
881         }
882     }
883     free( argv[0] );
884 }
885
886
887 /***********************************************************************
888  *           fork_and_exec
889  *
890  * Fork and exec a new Unix binary, checking for errors.
891  */
892 static int fork_and_exec( const char *filename, char *cmdline,
893                           const char *env, const char *newdir )
894 {
895     int fd[2];
896     int pid, err;
897
898     if (!env) env = GetEnvironmentStringsA();
899
900     if (pipe(fd) == -1)
901     {
902         FILE_SetDosError();
903         return -1;
904     }
905     fcntl( fd[1], F_SETFD, 1 );  /* set close on exec */
906     if (!(pid = fork()))  /* child */
907     {
908         char **argv = build_argv( cmdline, 0 );
909         char **envp = build_envp( env, NULL );
910         close( fd[0] );
911
912         /* Reset signals that we previously set to SIG_IGN */
913         signal( SIGPIPE, SIG_DFL );
914         signal( SIGCHLD, SIG_DFL );
915
916         if (newdir) chdir(newdir);
917
918         if (argv && envp) execve( filename, argv, envp );
919         err = errno;
920         write( fd[1], &err, sizeof(err) );
921         _exit(1);
922     }
923     close( fd[1] );
924     if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
925     {
926         errno = err;
927         pid = -1;
928     }
929     if (pid == -1) FILE_SetDosError();
930     close( fd[0] );
931     return pid;
932 }
933
934
935 /***********************************************************************
936  *           create_process
937  *
938  * Create a new process. If hFile is a valid handle we have an exe
939  * file, otherwise it is a Winelib app.
940  */
941 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
942                             LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
943                             BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
944                             LPPROCESS_INFORMATION info, LPCSTR unixdir )
945 {
946     BOOL ret, success = FALSE;
947     HANDLE process_info;
948     startup_info_t startup_info;
949     char *extra_env = NULL;
950     int startfd[2];
951     int execfd[2];
952     pid_t pid;
953     int err;
954     char dummy;
955
956     if (!env)
957     {
958         env = GetEnvironmentStringsA();
959         extra_env = DRIVE_BuildEnv();
960     }
961
962     /* create the synchronization pipes */
963
964     if (pipe( startfd ) == -1)
965     {
966         FILE_SetDosError();
967         return FALSE;
968     }
969     if (pipe( execfd ) == -1)
970     {
971         close( startfd[0] );
972         close( startfd[1] );
973         FILE_SetDosError();
974         return FALSE;
975     }
976     fcntl( execfd[1], F_SETFD, 1 );  /* set close on exec */
977
978     /* create the child process */
979
980     if (!(pid = fork()))  /* child */
981     {
982         char **argv = build_argv( cmd_line, 1 );
983         char **envp = build_envp( env, extra_env );
984
985         close( startfd[1] );
986         close( execfd[0] );
987
988         /* wait for parent to tell us to start */
989         if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
990
991         close( startfd[0] );
992         /* Reset signals that we previously set to SIG_IGN */
993         signal( SIGPIPE, SIG_DFL );
994         signal( SIGCHLD, SIG_DFL );
995
996         if (unixdir) chdir(unixdir);
997
998         if (argv && envp) exec_wine_binary( argv, envp );
999
1000         err = errno;
1001         write( execfd[1], &err, sizeof(err) );
1002         _exit(1);
1003     }
1004
1005     /* this is the parent */
1006
1007     close( startfd[0] );
1008     close( execfd[1] );
1009     if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1010     if (pid == -1)
1011     {
1012         close( startfd[1] );
1013         close( execfd[0] );
1014         FILE_SetDosError();
1015         return FALSE;
1016     }
1017
1018     /* fill the startup info structure */
1019
1020     startup_info.size        = sizeof(startup_info);
1021     /* startup_info.filename_len is set below */
1022     startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
1023     startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
1024     startup_info.title_len   = startup->lpTitle ? strlen(startup->lpTitle) : 0;
1025     startup_info.x           = startup->dwX;
1026     startup_info.y           = startup->dwY;
1027     startup_info.cx          = startup->dwXSize;
1028     startup_info.cy          = startup->dwYSize;
1029     startup_info.x_chars     = startup->dwXCountChars;
1030     startup_info.y_chars     = startup->dwYCountChars;
1031     startup_info.attribute   = startup->dwFillAttribute;
1032     startup_info.cmd_show    = startup->wShowWindow;
1033     startup_info.flags       = startup->dwFlags;
1034
1035     /* create the process on the server side */
1036
1037     SERVER_START_REQ( new_process )
1038     {
1039         char buf[MAX_PATH];
1040         LPCSTR nameptr;
1041
1042         req->inherit_all  = inherit;
1043         req->create_flags = flags;
1044         req->use_handles  = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
1045         req->unix_pid     = pid;
1046         req->exe_file     = hFile;
1047         if (startup->dwFlags & STARTF_USESTDHANDLES)
1048         {
1049             req->hstdin  = startup->hStdInput;
1050             req->hstdout = startup->hStdOutput;
1051             req->hstderr = startup->hStdError;
1052         }
1053         else
1054         {
1055             req->hstdin  = GetStdHandle( STD_INPUT_HANDLE );
1056             req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1057             req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1058         }
1059
1060         if (GetLongPathNameA( filename, buf, MAX_PATH ))
1061             nameptr = buf;
1062         else
1063             nameptr = filename;
1064
1065         startup_info.filename_len = strlen(nameptr);
1066         wine_server_add_data( req, &startup_info, sizeof(startup_info) );
1067         wine_server_add_data( req, nameptr, startup_info.filename_len );
1068         wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
1069         wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
1070         wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
1071
1072         ret = !wine_server_call_err( req );
1073         process_info = reply->info;
1074     }
1075     SERVER_END_REQ;
1076
1077     if (!ret)
1078     {
1079         close( startfd[1] );
1080         close( execfd[0] );
1081         return FALSE;
1082     }
1083
1084     /* tell child to start and wait for it to exec */
1085
1086     write( startfd[1], &dummy, 1 );
1087     close( startfd[1] );
1088
1089     if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1090     {
1091         errno = err;
1092         FILE_SetDosError();
1093         close( execfd[0] );
1094         CloseHandle( process_info );
1095         return FALSE;
1096     }
1097
1098     /* wait for the new process info to be ready */
1099
1100     WaitForSingleObject( process_info, INFINITE );
1101     SERVER_START_REQ( get_new_process_info )
1102     {
1103         req->info     = process_info;
1104         req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1105         req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1106         if ((ret = !wine_server_call_err( req )))
1107         {
1108             info->dwProcessId = (DWORD)reply->pid;
1109             info->dwThreadId  = (DWORD)reply->tid;
1110             info->hProcess    = reply->phandle;
1111             info->hThread     = reply->thandle;
1112             success           = reply->success;
1113         }
1114     }
1115     SERVER_END_REQ;
1116
1117     if (ret && !success)  /* new process failed to start */
1118     {
1119         DWORD exitcode;
1120         if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1121         CloseHandle( info->hThread );
1122         CloseHandle( info->hProcess );
1123         ret = FALSE;
1124     }
1125     CloseHandle( process_info );
1126     return ret;
1127 }
1128
1129
1130 /*************************************************************************
1131  *               get_file_name
1132  *
1133  * Helper for CreateProcess: retrieve the file name to load from the
1134  * app name and command line. Store the file name in buffer, and
1135  * return a possibly modified command line.
1136  * Also returns a handle to the opened file if it's a Windows binary.
1137  */
1138 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1139                             int buflen, HANDLE *handle )
1140 {
1141     char *name, *pos, *ret = NULL;
1142     const char *p;
1143
1144     /* if we have an app name, everything is easy */
1145
1146     if (appname)
1147     {
1148         /* use the unmodified app name as file name */
1149         lstrcpynA( buffer, appname, buflen );
1150         *handle = open_exe_file( buffer );
1151         if (!(ret = cmdline) || !cmdline[0])
1152         {
1153             /* no command-line, create one */
1154             if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1155                 sprintf( ret, "\"%s\"", appname );
1156         }
1157         return ret;
1158     }
1159
1160     if (!cmdline)
1161     {
1162         SetLastError( ERROR_INVALID_PARAMETER );
1163         return NULL;
1164     }
1165
1166     /* first check for a quoted file name */
1167
1168     if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1169     {
1170         int len = p - cmdline - 1;
1171         /* extract the quoted portion as file name */
1172         if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1173         memcpy( name, cmdline + 1, len );
1174         name[len] = 0;
1175
1176         if (find_exe_file( name, buffer, buflen, handle ))
1177             ret = cmdline;  /* no change necessary */
1178         goto done;
1179     }
1180
1181     /* now try the command-line word by word */
1182
1183     if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1184     pos = name;
1185     p = cmdline;
1186
1187     while (*p)
1188     {
1189         do *pos++ = *p++; while (*p && *p != ' ');
1190         *pos = 0;
1191         if (find_exe_file( name, buffer, buflen, handle ))
1192         {
1193             ret = cmdline;
1194             break;
1195         }
1196     }
1197
1198     if (!ret || !strchr( name, ' ' )) goto done;  /* no change necessary */
1199
1200     /* now build a new command-line with quotes */
1201
1202     if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1203     sprintf( ret, "\"%s\"%s", name, p );
1204
1205  done:
1206     HeapFree( GetProcessHeap(), 0, name );
1207     return ret;
1208 }
1209
1210
1211 /**********************************************************************
1212  *       CreateProcessA          (KERNEL32.@)
1213  */
1214 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1215                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1216                             DWORD flags, LPVOID env, LPCSTR cur_dir,
1217                             LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1218 {
1219     BOOL retv = FALSE;
1220     HANDLE hFile = 0;
1221     const char *unixdir = NULL;
1222     DOS_FULL_NAME full_dir;
1223     char name[MAX_PATH];
1224     LPSTR tidy_cmdline;
1225     char *p;
1226
1227     /* Process the AppName and/or CmdLine to get module name and path */
1228
1229     TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1230
1231     if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1232         return FALSE;
1233     if (hFile == INVALID_HANDLE_VALUE) goto done;
1234
1235     /* Warn if unsupported features are used */
1236
1237     if (flags & NORMAL_PRIORITY_CLASS)
1238         FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1239     if (flags & IDLE_PRIORITY_CLASS)
1240         FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1241     if (flags & HIGH_PRIORITY_CLASS)
1242         FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1243     if (flags & REALTIME_PRIORITY_CLASS)
1244         FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1245     if (flags & CREATE_NEW_PROCESS_GROUP)
1246         FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1247     if (flags & CREATE_UNICODE_ENVIRONMENT)
1248         FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1249     if (flags & CREATE_SEPARATE_WOW_VDM)
1250         FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1251     if (flags & CREATE_SHARED_WOW_VDM)
1252         FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1253     if (flags & CREATE_DEFAULT_ERROR_MODE)
1254         FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1255     if (flags & CREATE_NO_WINDOW)
1256         FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1257     if (flags & PROFILE_USER)
1258         FIXME("(%s,...): PROFILE_USER ignored\n", name);
1259     if (flags & PROFILE_KERNEL)
1260         FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1261     if (flags & PROFILE_SERVER)
1262         FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1263     if (startup_info->lpDesktop)
1264         FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1265               name, debugstr_a(startup_info->lpDesktop));
1266     if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1267         FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1268     if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1269         FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1270     if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1271         FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1272     if (startup_info->dwFlags & STARTF_USEHOTKEY)
1273         FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1274
1275     if (cur_dir)
1276     {
1277         UNICODE_STRING cur_dirW;
1278         RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1279         if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1280             unixdir = full_dir.long_name;
1281         RtlFreeUnicodeString(&cur_dirW);
1282     }
1283     else
1284     {
1285         WCHAR buf[MAX_PATH];
1286         if (GetCurrentDirectoryW(MAX_PATH, buf))
1287         {
1288             if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1289         }
1290     }
1291
1292     info->hThread = info->hProcess = 0;
1293     info->dwProcessId = info->dwThreadId = 0;
1294
1295     /* Determine executable type */
1296
1297     if (!hFile)  /* builtin exe */
1298     {
1299         TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1300         retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1301                                inherit, flags, startup_info, info, unixdir );
1302         goto done;
1303     }
1304
1305     switch( MODULE_GetBinaryType( hFile ))
1306     {
1307     case BINARY_PE_EXE:
1308     case BINARY_WIN16:
1309     case BINARY_DOS:
1310         TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1311         retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1312                                inherit, flags, startup_info, info, unixdir );
1313         break;
1314     case BINARY_OS216:
1315         FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1316         SetLastError( ERROR_BAD_EXE_FORMAT );
1317         break;
1318     case BINARY_PE_DLL:
1319         TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1320         SetLastError( ERROR_BAD_EXE_FORMAT );
1321         break;
1322     case BINARY_UNIX_LIB:
1323         TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1324         retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1325                                inherit, flags, startup_info, info, unixdir );
1326         break;
1327     case BINARY_UNKNOWN:
1328         /* check for .com or .bat extension */
1329         if ((p = strrchr( name, '.' )))
1330         {
1331             if (!FILE_strcasecmp( p, ".com" ))
1332             {
1333                 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1334                 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1335                                        inherit, flags, startup_info, info, unixdir );
1336                 break;
1337             }
1338             if (!FILE_strcasecmp( p, ".bat" ))
1339             {
1340                 char comspec[MAX_PATH];
1341                 if (GetEnvironmentVariableA("COMSPEC", comspec, sizeof(comspec)))
1342                 {
1343                     char *newcmdline, *q = strchr(cmd_line, ' ');
1344                     if (!q) q = "";
1345                     if ((newcmdline = HeapAlloc( GetProcessHeap(), 0,
1346                                                  strlen(comspec) + strlen(name) + strlen(q) + 8)))
1347                     {
1348                         sprintf( newcmdline, "%s /c %s%s", comspec, name, q );
1349                         TRACE( "starting %s as batch binary: %s\n",
1350                                debugstr_a(name), debugstr_a(newcmdline) );
1351                         retv = CreateProcessA( comspec, newcmdline, process_attr, thread_attr,
1352                                                inherit, flags, env, cur_dir, startup_info, info );
1353                         HeapFree( GetProcessHeap(), 0, newcmdline );
1354                         break;
1355                     }
1356                 }
1357             }
1358         }
1359         /* fall through */
1360     case BINARY_UNIX_EXE:
1361         {
1362             /* unknown file, try as unix executable */
1363             UNICODE_STRING nameW;
1364             DOS_FULL_NAME full_name;
1365             const char *unixfilename = name;
1366
1367             TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1368
1369             RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1370             if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1371             RtlFreeUnicodeString(&nameW);
1372             retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1373         }
1374         break;
1375     }
1376     CloseHandle( hFile );
1377
1378  done:
1379     if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1380     return retv;
1381 }
1382
1383
1384 /**********************************************************************
1385  *       CreateProcessW          (KERNEL32.@)
1386  * NOTES
1387  *  lpReserved is not converted
1388  */
1389 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1390                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1391                             LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1392                             LPPROCESS_INFORMATION info )
1393 {
1394     BOOL ret;
1395     STARTUPINFOA StartupInfoA;
1396
1397     LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1398     LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1399     LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1400
1401     memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1402     StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1403     StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1404
1405     TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1406
1407     if (startup_info->lpReserved)
1408       FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1409                     debugstr_w(startup_info->lpReserved));
1410
1411     ret = CreateProcessA( app_nameA,  cmd_lineA, process_attr, thread_attr,
1412                           inherit, flags, env, cur_dirA, &StartupInfoA, info );
1413
1414     HeapFree( GetProcessHeap(), 0, cur_dirA );
1415     HeapFree( GetProcessHeap(), 0, cmd_lineA );
1416     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1417     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1418
1419     return ret;
1420 }
1421
1422
1423 /***********************************************************************
1424  *           ExitProcess   (KERNEL32.@)
1425  */
1426 void WINAPI ExitProcess( DWORD status )
1427 {
1428     MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1429     SERVER_START_REQ( terminate_process )
1430     {
1431         /* send the exit code to the server */
1432         req->handle    = GetCurrentProcess();
1433         req->exit_code = status;
1434         wine_server_call( req );
1435     }
1436     SERVER_END_REQ;
1437     exit( status );
1438 }
1439
1440 /***********************************************************************
1441  *           ExitProcess   (KERNEL.466)
1442  */
1443 void WINAPI ExitProcess16( WORD status )
1444 {
1445     DWORD count;
1446     ReleaseThunkLock( &count );
1447     ExitProcess( status );
1448 }
1449
1450 /******************************************************************************
1451  *           TerminateProcess   (KERNEL32.@)
1452  */
1453 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1454 {
1455     NTSTATUS status = NtTerminateProcess( handle, exit_code );
1456     if (status) SetLastError( RtlNtStatusToDosError(status) );
1457     return !status;
1458 }
1459
1460
1461 /***********************************************************************
1462  *           GetProcessDword    (KERNEL.485)
1463  *           GetProcessDword    (KERNEL32.18)
1464  * 'Of course you cannot directly access Windows internal structures'
1465  */
1466 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1467 {
1468     DWORD x, y;
1469
1470     TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1471
1472     if (dwProcessID && dwProcessID != GetCurrentProcessId())
1473     {
1474         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1475         return 0;
1476     }
1477
1478     switch ( offset )
1479     {
1480     case GPD_APP_COMPAT_FLAGS:
1481         return GetAppCompatFlags16(0);
1482
1483     case GPD_LOAD_DONE_EVENT:
1484         return (DWORD)current_process.load_done_evt;
1485
1486     case GPD_HINSTANCE16:
1487         return GetTaskDS16();
1488
1489     case GPD_WINDOWS_VERSION:
1490         return GetExeVersion16();
1491
1492     case GPD_THDB:
1493         return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1494
1495     case GPD_PDB:
1496         return (DWORD)&current_process;
1497
1498     case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1499         return (DWORD)current_startupinfo.hStdOutput;
1500
1501     case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1502         return (DWORD)current_startupinfo.hStdInput;
1503
1504     case GPD_STARTF_SHOWWINDOW:
1505         return current_startupinfo.wShowWindow;
1506
1507     case GPD_STARTF_SIZE:
1508         x = current_startupinfo.dwXSize;
1509         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1510         y = current_startupinfo.dwYSize;
1511         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1512         return MAKELONG( x, y );
1513
1514     case GPD_STARTF_POSITION:
1515         x = current_startupinfo.dwX;
1516         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1517         y = current_startupinfo.dwY;
1518         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1519         return MAKELONG( x, y );
1520
1521     case GPD_STARTF_FLAGS:
1522         return current_startupinfo.dwFlags;
1523
1524     case GPD_PARENT:
1525         return 0;
1526
1527     case GPD_FLAGS:
1528         return current_process.flags;
1529
1530     case GPD_USERDATA:
1531         return current_process.process_dword;
1532
1533     default:
1534         ERR_(win32)("Unknown offset %d\n", offset );
1535         return 0;
1536     }
1537 }
1538
1539 /***********************************************************************
1540  *           SetProcessDword    (KERNEL.484)
1541  * 'Of course you cannot directly access Windows internal structures'
1542  */
1543 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1544 {
1545     TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1546
1547     if (dwProcessID && dwProcessID != GetCurrentProcessId())
1548     {
1549         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1550         return;
1551     }
1552
1553     switch ( offset )
1554     {
1555     case GPD_APP_COMPAT_FLAGS:
1556     case GPD_LOAD_DONE_EVENT:
1557     case GPD_HINSTANCE16:
1558     case GPD_WINDOWS_VERSION:
1559     case GPD_THDB:
1560     case GPD_PDB:
1561     case GPD_STARTF_SHELLDATA:
1562     case GPD_STARTF_HOTKEY:
1563     case GPD_STARTF_SHOWWINDOW:
1564     case GPD_STARTF_SIZE:
1565     case GPD_STARTF_POSITION:
1566     case GPD_STARTF_FLAGS:
1567     case GPD_PARENT:
1568     case GPD_FLAGS:
1569         ERR_(win32)("Not allowed to modify offset %d\n", offset );
1570         break;
1571
1572     case GPD_USERDATA:
1573         current_process.process_dword = value;
1574         break;
1575
1576     default:
1577         ERR_(win32)("Unknown offset %d\n", offset );
1578         break;
1579     }
1580 }
1581
1582
1583 /*********************************************************************
1584  *           OpenProcess   (KERNEL32.@)
1585  */
1586 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1587 {
1588     HANDLE ret = 0;
1589     SERVER_START_REQ( open_process )
1590     {
1591         req->pid     = id;
1592         req->access  = access;
1593         req->inherit = inherit;
1594         if (!wine_server_call_err( req )) ret = reply->handle;
1595     }
1596     SERVER_END_REQ;
1597     return ret;
1598 }
1599
1600 /*********************************************************************
1601  *           MapProcessHandle   (KERNEL.483)
1602  */
1603 DWORD WINAPI MapProcessHandle( HANDLE handle )
1604 {
1605     DWORD ret = 0;
1606     SERVER_START_REQ( get_process_info )
1607     {
1608         req->handle = handle;
1609         if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1610     }
1611     SERVER_END_REQ;
1612     return ret;
1613 }
1614
1615 /***********************************************************************
1616  *           SetPriorityClass   (KERNEL32.@)
1617  */
1618 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1619 {
1620     BOOL ret;
1621     SERVER_START_REQ( set_process_info )
1622     {
1623         req->handle   = hprocess;
1624         req->priority = priorityclass;
1625         req->mask     = SET_PROCESS_INFO_PRIORITY;
1626         ret = !wine_server_call_err( req );
1627     }
1628     SERVER_END_REQ;
1629     return ret;
1630 }
1631
1632
1633 /***********************************************************************
1634  *           GetPriorityClass   (KERNEL32.@)
1635  */
1636 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1637 {
1638     DWORD ret = 0;
1639     SERVER_START_REQ( get_process_info )
1640     {
1641         req->handle = hprocess;
1642         if (!wine_server_call_err( req )) ret = reply->priority;
1643     }
1644     SERVER_END_REQ;
1645     return ret;
1646 }
1647
1648
1649 /***********************************************************************
1650  *          SetProcessAffinityMask   (KERNEL32.@)
1651  */
1652 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1653 {
1654     BOOL ret;
1655     SERVER_START_REQ( set_process_info )
1656     {
1657         req->handle   = hProcess;
1658         req->affinity = affmask;
1659         req->mask     = SET_PROCESS_INFO_AFFINITY;
1660         ret = !wine_server_call_err( req );
1661     }
1662     SERVER_END_REQ;
1663     return ret;
1664 }
1665
1666 /**********************************************************************
1667  *          GetProcessAffinityMask    (KERNEL32.@)
1668  */
1669 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1670                                       LPDWORD lpProcessAffinityMask,
1671                                       LPDWORD lpSystemAffinityMask )
1672 {
1673     BOOL ret = FALSE;
1674     SERVER_START_REQ( get_process_info )
1675     {
1676         req->handle = hProcess;
1677         if (!wine_server_call_err( req ))
1678         {
1679             if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1680             if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1681             ret = TRUE;
1682         }
1683     }
1684     SERVER_END_REQ;
1685     return ret;
1686 }
1687
1688
1689 /***********************************************************************
1690  *           GetProcessVersion    (KERNEL32.@)
1691  */
1692 DWORD WINAPI GetProcessVersion( DWORD processid )
1693 {
1694     IMAGE_NT_HEADERS *nt;
1695
1696     if (processid && processid != GetCurrentProcessId())
1697     {
1698         FIXME("should use ReadProcessMemory\n");
1699         return 0;
1700     }
1701     if ((nt = RtlImageNtHeader( current_process.module )))
1702         return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1703                 nt->OptionalHeader.MinorSubsystemVersion);
1704     return 0;
1705 }
1706
1707 /***********************************************************************
1708  *           GetProcessFlags    (KERNEL32.@)
1709  */
1710 DWORD WINAPI GetProcessFlags( DWORD processid )
1711 {
1712     if (processid && processid != GetCurrentProcessId()) return 0;
1713     return current_process.flags;
1714 }
1715
1716
1717 /***********************************************************************
1718  *              SetProcessWorkingSetSize        [KERNEL32.@]
1719  * Sets the min/max working set sizes for a specified process.
1720  *
1721  * PARAMS
1722  *    hProcess [I] Handle to the process of interest
1723  *    minset   [I] Specifies minimum working set size
1724  *    maxset   [I] Specifies maximum working set size
1725  *
1726  * RETURNS  STD
1727  */
1728 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
1729                                      SIZE_T maxset)
1730 {
1731     FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1732     if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
1733         /* Trim the working set to zero */
1734         /* Swap the process out of physical RAM */
1735     }
1736     return TRUE;
1737 }
1738
1739 /***********************************************************************
1740  *           GetProcessWorkingSetSize    (KERNEL32.@)
1741  */
1742 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
1743                                      PSIZE_T maxset)
1744 {
1745         FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
1746         /* 32 MB working set size */
1747         if (minset) *minset = 32*1024*1024;
1748         if (maxset) *maxset = 32*1024*1024;
1749         return TRUE;
1750 }
1751
1752 /***********************************************************************
1753  *           SetProcessShutdownParameters    (KERNEL32.@)
1754  *
1755  * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1756  * Now tracks changes made (but does not act on these changes)
1757  */
1758 static DWORD shutdown_flags = 0;
1759 static DWORD shutdown_priority = 0x280;
1760
1761 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1762 {
1763     FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1764     shutdown_flags = flags;
1765     shutdown_priority = level;
1766     return TRUE;
1767 }
1768
1769
1770 /***********************************************************************
1771  * GetProcessShutdownParameters                 (KERNEL32.@)
1772  *
1773  */
1774 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1775 {
1776     *lpdwLevel = shutdown_priority;
1777     *lpdwFlags = shutdown_flags;
1778     return TRUE;
1779 }
1780
1781
1782 /***********************************************************************
1783  *           SetProcessPriorityBoost    (KERNEL32.@)
1784  */
1785 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1786 {
1787     FIXME("(%p,%d): stub\n",hprocess,disableboost);
1788     /* Say we can do it. I doubt the program will notice that we don't. */
1789     return TRUE;
1790 }
1791
1792
1793 /***********************************************************************
1794  *              ReadProcessMemory (KERNEL32.@)
1795  */
1796 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
1797                                SIZE_T *bytes_read )
1798 {
1799     DWORD res;
1800
1801     SERVER_START_REQ( read_process_memory )
1802     {
1803         req->handle = process;
1804         req->addr   = (void *)addr;
1805         wine_server_set_reply( req, buffer, size );
1806         if ((res = wine_server_call_err( req ))) size = 0;
1807     }
1808     SERVER_END_REQ;
1809     if (bytes_read) *bytes_read = size;
1810     return !res;
1811 }
1812
1813
1814 /***********************************************************************
1815  *           WriteProcessMemory                 (KERNEL32.@)
1816  */
1817 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
1818                                 SIZE_T *bytes_written )
1819 {
1820     static const int zero;
1821     unsigned int first_offset, last_offset, first_mask, last_mask;
1822     DWORD res;
1823
1824     if (!size)
1825     {
1826         SetLastError( ERROR_INVALID_PARAMETER );
1827         return FALSE;
1828     }
1829
1830     /* compute the mask for the first int */
1831     first_mask = ~0;
1832     first_offset = (unsigned int)addr % sizeof(int);
1833     memset( &first_mask, 0, first_offset );
1834
1835     /* compute the mask for the last int */
1836     last_offset = (size + first_offset) % sizeof(int);
1837     last_mask = 0;
1838     memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1839
1840     SERVER_START_REQ( write_process_memory )
1841     {
1842         req->handle     = process;
1843         req->addr       = (char *)addr - first_offset;
1844         req->first_mask = first_mask;
1845         req->last_mask  = last_mask;
1846         if (first_offset) wine_server_add_data( req, &zero, first_offset );
1847         wine_server_add_data( req, buffer, size );
1848         if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1849
1850         if ((res = wine_server_call_err( req ))) size = 0;
1851     }
1852     SERVER_END_REQ;
1853     if (bytes_written) *bytes_written = size;
1854     {
1855         char dummy[32];
1856         SIZE_T read;
1857         ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1858     }
1859     return !res;
1860 }
1861
1862
1863 /***********************************************************************
1864  *              RegisterServiceProcess (KERNEL.491)
1865  *              RegisterServiceProcess (KERNEL32.@)
1866  *
1867  * A service process calls this function to ensure that it continues to run
1868  * even after a user logged off.
1869  */
1870 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1871 {
1872         /* I don't think that Wine needs to do anything in that function */
1873         return 1; /* success */
1874 }
1875
1876 /***********************************************************************
1877  * GetExitCodeProcess [KERNEL32.@]
1878  *
1879  * Gets termination status of specified process
1880  *
1881  * RETURNS
1882  *   Success: TRUE
1883  *   Failure: FALSE
1884  */
1885 BOOL WINAPI GetExitCodeProcess(
1886     HANDLE hProcess,    /* [in] handle to the process */
1887     LPDWORD lpExitCode) /* [out] address to receive termination status */
1888 {
1889     BOOL ret;
1890     SERVER_START_REQ( get_process_info )
1891     {
1892         req->handle = hProcess;
1893         ret = !wine_server_call_err( req );
1894         if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1895     }
1896     SERVER_END_REQ;
1897     return ret;
1898 }
1899
1900
1901 /***********************************************************************
1902  *           SetErrorMode   (KERNEL32.@)
1903  */
1904 UINT WINAPI SetErrorMode( UINT mode )
1905 {
1906     UINT old = current_process.error_mode;
1907     current_process.error_mode = mode;
1908     return old;
1909 }
1910
1911
1912 /**************************************************************************
1913  *              SetFileApisToOEM   (KERNEL32.@)
1914  */
1915 VOID WINAPI SetFileApisToOEM(void)
1916 {
1917     current_process.flags |= PDB32_FILE_APIS_OEM;
1918 }
1919
1920
1921 /**************************************************************************
1922  *              SetFileApisToANSI   (KERNEL32.@)
1923  */
1924 VOID WINAPI SetFileApisToANSI(void)
1925 {
1926     current_process.flags &= ~PDB32_FILE_APIS_OEM;
1927 }
1928
1929
1930 /******************************************************************************
1931  * AreFileApisANSI [KERNEL32.@]  Determines if file functions are using ANSI
1932  *
1933  * RETURNS
1934  *    TRUE:  Set of file functions is using ANSI code page
1935  *    FALSE: Set of file functions is using OEM code page
1936  */
1937 BOOL WINAPI AreFileApisANSI(void)
1938 {
1939     return !(current_process.flags & PDB32_FILE_APIS_OEM);
1940 }
1941
1942
1943 /***********************************************************************
1944  *           GetTickCount       (KERNEL32.@)
1945  *
1946  * Returns the number of milliseconds, modulo 2^32, since the start
1947  * of the wineserver.
1948  */
1949 DWORD WINAPI GetTickCount(void)
1950 {
1951     struct timeval t;
1952     gettimeofday( &t, NULL );
1953     return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1954 }
1955
1956
1957 /**********************************************************************
1958  * TlsAlloc [KERNEL32.@]  Allocates a TLS index.
1959  *
1960  * Allocates a thread local storage index
1961  *
1962  * RETURNS
1963  *    Success: TLS Index
1964  *    Failure: 0xFFFFFFFF
1965  */
1966 DWORD WINAPI TlsAlloc( void )
1967 {
1968     DWORD i, mask, ret = 0;
1969     DWORD *bits = current_process.tls_bits;
1970     RtlAcquirePebLock();
1971     if (*bits == 0xffffffff)
1972     {
1973         bits++;
1974         ret = 32;
1975         if (*bits == 0xffffffff)
1976         {
1977             RtlReleasePebLock();
1978             SetLastError( ERROR_NO_MORE_ITEMS );
1979             return 0xffffffff;
1980         }
1981     }
1982     for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1983     *bits |= mask;
1984     RtlReleasePebLock();
1985     NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1986     return ret + i;
1987 }
1988
1989
1990 /**********************************************************************
1991  * TlsFree [KERNEL32.@]  Releases a TLS index.
1992  *
1993  * Releases a thread local storage index, making it available for reuse
1994  *
1995  * RETURNS
1996  *    Success: TRUE
1997  *    Failure: FALSE
1998  */
1999 BOOL WINAPI TlsFree(
2000     DWORD index) /* [in] TLS Index to free */
2001 {
2002     DWORD mask = (1 << (index & 31));
2003     DWORD *bits = current_process.tls_bits;
2004     if (index >= 64)
2005     {
2006         SetLastError( ERROR_INVALID_PARAMETER );
2007         return FALSE;
2008     }
2009     if (index >= 32) bits++;
2010     RtlAcquirePebLock();
2011     if (!(*bits & mask))  /* already free? */
2012     {
2013         RtlReleasePebLock();
2014         SetLastError( ERROR_INVALID_PARAMETER );
2015         return FALSE;
2016     }
2017     *bits &= ~mask;
2018     NtCurrentTeb()->tls_array[index] = 0;
2019     /* FIXME: should zero all other thread values */
2020     RtlReleasePebLock();
2021     return TRUE;
2022 }
2023
2024
2025 /**********************************************************************
2026  * TlsGetValue [KERNEL32.@]  Gets value in a thread's TLS slot
2027  *
2028  * RETURNS
2029  *    Success: Value stored in calling thread's TLS slot for index
2030  *    Failure: 0 and GetLastError returns NO_ERROR
2031  */
2032 LPVOID WINAPI TlsGetValue(
2033     DWORD index) /* [in] TLS index to retrieve value for */
2034 {
2035     if (index >= 64)
2036     {
2037         SetLastError( ERROR_INVALID_PARAMETER );
2038         return NULL;
2039     }
2040     SetLastError( ERROR_SUCCESS );
2041     return NtCurrentTeb()->tls_array[index];
2042 }
2043
2044
2045 /**********************************************************************
2046  * TlsSetValue [KERNEL32.@]  Stores a value in the thread's TLS slot.
2047  *
2048  * RETURNS
2049  *    Success: TRUE
2050  *    Failure: FALSE
2051  */
2052 BOOL WINAPI TlsSetValue(
2053     DWORD index,  /* [in] TLS index to set value for */
2054     LPVOID value) /* [in] Value to be stored */
2055 {
2056     if (index >= 64)
2057     {
2058         SetLastError( ERROR_INVALID_PARAMETER );
2059         return FALSE;
2060     }
2061     NtCurrentTeb()->tls_array[index] = value;
2062     return TRUE;
2063 }
2064
2065
2066 /***********************************************************************
2067  *           GetCurrentProcess   (KERNEL32.@)
2068  */
2069 #undef GetCurrentProcess
2070 HANDLE WINAPI GetCurrentProcess(void)
2071 {
2072     return (HANDLE)0xffffffff;
2073 }