- Ensure we correctly add a backslash like Windows 98/XP do.
[wine] / dlls / kernel / 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 <locale.h>
28 #include <signal.h>
29 #include <stdio.h>
30
31 #include "wine/winbase16.h"
32 #include "wine/winuser16.h"
33 #include "ntstatus.h"
34 #include "thread.h"
35 #include "drive.h"
36 #include "file.h"
37 #include "module.h"
38 #include "options.h"
39 #include "kernel_private.h"
40 #include "wine/exception.h"
41 #include "wine/server.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(process);
46 WINE_DECLARE_DEBUG_CHANNEL(server);
47 WINE_DECLARE_DEBUG_CHANNEL(relay);
48
49 typedef struct
50 {
51     LPSTR lpEnvAddress;
52     LPSTR lpCmdLine;
53     LPSTR lpCmdShow;
54     DWORD dwReserved;
55 } LOADPARMS32;
56
57 static UINT process_error_mode;
58
59 static HANDLE main_exe_file;
60 static DWORD shutdown_flags = 0;
61 static DWORD shutdown_priority = 0x280;
62 static DWORD process_dword;
63 static BOOL oem_file_apis;
64
65 static unsigned int server_startticks;
66 int main_create_flags = 0;
67
68 /* Process flags */
69 #define PDB32_DEBUGGED      0x0001  /* Process is being debugged */
70 #define PDB32_WIN16_PROC    0x0008  /* Win16 process */
71 #define PDB32_DOS_PROC      0x0010  /* Dos process */
72 #define PDB32_CONSOLE_PROC  0x0020  /* Console process */
73 #define PDB32_FILE_APIS_OEM 0x0040  /* File APIs are OEM */
74 #define PDB32_WIN32S_PROC   0x8000  /* Win32s process */
75
76 static const WCHAR comW[] = {'.','c','o','m',0};
77 static const WCHAR batW[] = {'.','b','a','t',0};
78 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
79
80 extern void SHELL_LoadRegistry(void);
81 extern void VERSION_Init( const WCHAR *appname );
82 extern void MODULE_InitLoadPath(void);
83 extern void LOCALE_Init(void);
84
85 /***********************************************************************
86  *           contains_path
87  */
88 inline static int contains_path( LPCWSTR name )
89 {
90     return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
91 }
92
93
94 /***************************************************************************
95  *      get_builtin_path
96  *
97  * Get the path of a builtin module when the native file does not exist.
98  */
99 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
100 {
101     WCHAR *file_part;
102     WCHAR sysdir[MAX_PATH];
103     UINT len = GetSystemDirectoryW( sysdir, MAX_PATH );
104
105     if (contains_path( libname ))
106     {
107         if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
108                                   filename, &file_part ) > size * sizeof(WCHAR))
109             return FALSE;  /* too long */
110
111         if (strncmpiW( filename, sysdir, len ) || filename[len] != '\\')
112             return FALSE;
113         while (filename[len] == '\\') len++;
114         if (filename + len != file_part) return FALSE;
115     }
116     else
117     {
118         if (strlenW(libname) + len + 2 >= size) return FALSE;  /* too long */
119         memcpy( filename, sysdir, len * sizeof(WCHAR) );
120         file_part = filename + len;
121         if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
122         strcpyW( file_part, libname );
123     }
124     if (ext && !strchrW( file_part, '.' ))
125     {
126         if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
127             return FALSE;  /* too long */
128         strcatW( file_part, ext );
129     }
130     return TRUE;
131 }
132
133
134 /***********************************************************************
135  *           open_builtin_exe_file
136  *
137  * Open an exe file for a builtin exe.
138  */
139 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
140                                     int test_only, int *file_exists )
141 {
142     char exename[MAX_PATH];
143     WCHAR *p;
144     UINT i, len;
145
146     if ((p = strrchrW( name, '/' ))) name = p + 1;
147     if ((p = strrchrW( name, '\\' ))) name = p + 1;
148
149     /* we don't want to depend on the current codepage here */
150     len = strlenW( name ) + 1;
151     if (len >= sizeof(exename)) return NULL;
152     for (i = 0; i < len; i++)
153     {
154         if (name[i] > 127) return NULL;
155         exename[i] = (char)name[i];
156         if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
157     }
158     return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
159 }
160
161
162 /***********************************************************************
163  *           open_exe_file
164  *
165  * Open a specific exe file, taking load order into account.
166  * Returns the file handle or 0 for a builtin exe.
167  */
168 static HANDLE open_exe_file( const WCHAR *name )
169 {
170     enum loadorder_type loadorder[LOADORDER_NTYPES];
171     WCHAR buffer[MAX_PATH];
172     HANDLE handle;
173     int i, file_exists;
174
175     TRACE("looking for %s\n", debugstr_w(name) );
176
177     if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ,
178                                NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
179     {
180         /* file doesn't exist, check for builtin */
181         if (!contains_path( name )) goto error;
182         if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
183         name = buffer;
184     }
185
186     MODULE_GetLoadOrderW( loadorder, NULL, name );
187
188     for(i = 0; i < LOADORDER_NTYPES; i++)
189     {
190         if (loadorder[i] == LOADORDER_INVALID) break;
191         switch(loadorder[i])
192         {
193         case LOADORDER_DLL:
194             TRACE( "Trying native exe %s\n", debugstr_w(name) );
195             if (handle != INVALID_HANDLE_VALUE) return handle;
196             break;
197         case LOADORDER_BI:
198             TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
199             open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
200             if (file_exists)
201             {
202                 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
203                 return 0;
204             }
205         default:
206             break;
207         }
208     }
209     if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
210
211  error:
212     SetLastError( ERROR_FILE_NOT_FOUND );
213     return INVALID_HANDLE_VALUE;
214 }
215
216
217 /***********************************************************************
218  *           find_exe_file
219  *
220  * Open an exe file, and return the full name and file handle.
221  * Returns FALSE if file could not be found.
222  * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
223  * If file is a builtin exe, returns TRUE and sets handle to 0.
224  */
225 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
226 {
227     static const WCHAR exeW[] = {'.','e','x','e',0};
228
229     enum loadorder_type loadorder[LOADORDER_NTYPES];
230     int i, file_exists;
231
232     TRACE("looking for %s\n", debugstr_w(name) );
233
234     if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
235         !get_builtin_path( name, exeW, buffer, buflen ))
236     {
237         /* no builtin found, try native without extension in case it is a Unix app */
238
239         if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
240         {
241             TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
242             if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
243                                         NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
244                 return TRUE;
245         }
246         return FALSE;
247     }
248
249     MODULE_GetLoadOrderW( loadorder, NULL, buffer );
250
251     for(i = 0; i < LOADORDER_NTYPES; i++)
252     {
253         if (loadorder[i] == LOADORDER_INVALID) break;
254         switch(loadorder[i])
255         {
256         case LOADORDER_DLL:
257             TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
258             if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
259                                         NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
260                 return TRUE;
261             if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
262             break;
263         case LOADORDER_BI:
264             TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
265             open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
266             if (file_exists)
267             {
268                 *handle = 0;
269                 return TRUE;
270             }
271             break;
272         default:
273             break;
274         }
275     }
276     SetLastError( ERROR_FILE_NOT_FOUND );
277     return FALSE;
278 }
279
280
281 /**********************************************************************
282  *           load_pe_exe
283  *
284  * Load a PE format EXE file.
285  */
286 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
287 {
288     IMAGE_NT_HEADERS *nt;
289     HANDLE mapping;
290     void *module;
291     OBJECT_ATTRIBUTES attr;
292     LARGE_INTEGER size;
293     DWORD len = 0;
294     UINT drive_type;
295
296     attr.Length                   = sizeof(attr);
297     attr.RootDirectory            = 0;
298     attr.ObjectName               = NULL;
299     attr.Attributes               = 0;
300     attr.SecurityDescriptor       = NULL;
301     attr.SecurityQualityOfService = NULL;
302     size.QuadPart = 0;
303
304     if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
305                          &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
306         return NULL;
307
308     module = NULL;
309     if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
310                             ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
311         return NULL;
312
313     NtClose( mapping );
314
315     /* virus check */
316     nt = RtlImageNtHeader( module );
317     if (nt->OptionalHeader.AddressOfEntryPoint)
318     {
319         if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
320             MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
321                     "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
322                     debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
323     }
324
325     drive_type = GetDriveTypeW( name );
326     /* don't keep the file handle open on removable media */
327     if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM)
328     {
329         CloseHandle( main_exe_file );
330         main_exe_file = 0;
331     }
332
333     return module;
334 }
335
336 /***********************************************************************
337  *           build_initial_environment
338  *
339  * Build the Win32 environment from the Unix environment
340  */
341 static BOOL build_initial_environment( char **environ )
342 {
343     ULONG size = 1;
344     char **e;
345     WCHAR *p, *endptr;
346     void *ptr;
347
348     /* Compute the total size of the Unix environment */
349     for (e = environ; *e; e++)
350     {
351         if (!memcmp(*e, "PATH=", 5)) continue;
352         size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
353     }
354     size *= sizeof(WCHAR);
355
356     /* Now allocate the environment */
357     if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
358                                 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
359         return FALSE;
360
361     NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
362     endptr = p + size / sizeof(WCHAR);
363
364     /* And fill it with the Unix environment */
365     for (e = environ; *e; e++)
366     {
367         char *str = *e;
368         /* skip Unix PATH and store WINEPATH as PATH */
369         if (!memcmp(str, "PATH=", 5)) continue;
370         if (!memcmp(str, "WINEPATH=", 9 )) str += 4;
371         MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
372         p += strlenW(p) + 1;
373     }
374     *p = 0;
375     return TRUE;
376 }
377
378
379 /***********************************************************************
380  *              set_library_wargv
381  *
382  * Set the Wine library Unicode argv global variables.
383  */
384 static void set_library_wargv( char **argv )
385 {
386     int argc;
387     WCHAR *p;
388     WCHAR **wargv;
389     DWORD total = 0;
390
391     for (argc = 0; argv[argc]; argc++)
392         total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
393
394     wargv = RtlAllocateHeap( GetProcessHeap(), 0,
395                              total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
396     p = (WCHAR *)(wargv + argc + 1);
397     for (argc = 0; argv[argc]; argc++)
398     {
399         DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
400         wargv[argc] = p;
401         p += reslen;
402         total -= reslen;
403     }
404     wargv[argc] = NULL;
405     __wine_main_wargv = wargv;
406 }
407
408
409 /***********************************************************************
410  *           build_command_line
411  *
412  * Build the command line of a process from the argv array.
413  *
414  * Note that it does NOT necessarily include the file name.
415  * Sometimes we don't even have any command line options at all.
416  *
417  * We must quote and escape characters so that the argv array can be rebuilt
418  * from the command line:
419  * - spaces and tabs must be quoted
420  *   'a b'   -> '"a b"'
421  * - quotes must be escaped
422  *   '"'     -> '\"'
423  * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
424  *   resulting in an odd number of '\' followed by a '"'
425  *   '\"'    -> '\\\"'
426  *   '\\"'   -> '\\\\\"'
427  * - '\'s that are not followed by a '"' can be left as is
428  *   'a\b'   == 'a\b'
429  *   'a\\b'  == 'a\\b'
430  */
431 static BOOL build_command_line( WCHAR **argv )
432 {
433     int len;
434     WCHAR **arg;
435     LPWSTR p;
436     RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
437
438     if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
439
440     len = 0;
441     for (arg = argv; *arg; arg++)
442     {
443         int has_space,bcount;
444         WCHAR* a;
445
446         has_space=0;
447         bcount=0;
448         a=*arg;
449         if( !*a ) has_space=1;
450         while (*a!='\0') {
451             if (*a=='\\') {
452                 bcount++;
453             } else {
454                 if (*a==' ' || *a=='\t') {
455                     has_space=1;
456                 } else if (*a=='"') {
457                     /* doubling of '\' preceeding a '"',
458                      * plus escaping of said '"'
459                      */
460                     len+=2*bcount+1;
461                 }
462                 bcount=0;
463             }
464             a++;
465         }
466         len+=(a-*arg)+1 /* for the separating space */;
467         if (has_space)
468             len+=2; /* for the quotes */
469     }
470
471     if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
472         return FALSE;
473
474     p = rupp->CommandLine.Buffer;
475     rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
476     rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
477     for (arg = argv; *arg; arg++)
478     {
479         int has_space,has_quote;
480         WCHAR* a;
481
482         /* Check for quotes and spaces in this argument */
483         has_space=has_quote=0;
484         a=*arg;
485         if( !*a ) has_space=1;
486         while (*a!='\0') {
487             if (*a==' ' || *a=='\t') {
488                 has_space=1;
489                 if (has_quote)
490                     break;
491             } else if (*a=='"') {
492                 has_quote=1;
493                 if (has_space)
494                     break;
495             }
496             a++;
497         }
498
499         /* Now transfer it to the command line */
500         if (has_space)
501             *p++='"';
502         if (has_quote) {
503             int bcount;
504             WCHAR* a;
505
506             bcount=0;
507             a=*arg;
508             while (*a!='\0') {
509                 if (*a=='\\') {
510                     *p++=*a;
511                     bcount++;
512                 } else {
513                     if (*a=='"') {
514                         int i;
515
516                         /* Double all the '\\' preceeding this '"', plus one */
517                         for (i=0;i<=bcount;i++)
518                             *p++='\\';
519                         *p++='"';
520                     } else {
521                         *p++=*a;
522                     }
523                     bcount=0;
524                 }
525                 a++;
526             }
527         } else {
528             WCHAR* x = *arg;
529             while ((*p=*x++)) p++;
530         }
531         if (has_space)
532             *p++='"';
533         *p++=' ';
534     }
535     if (p > rupp->CommandLine.Buffer)
536         p--;  /* remove last space */
537     *p = '\0';
538
539     return TRUE;
540 }
541
542
543 /* make sure the unicode string doesn't point beyond the end pointer */
544 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
545 {
546     if ((char *)str->Buffer >= end_ptr)
547     {
548         str->Length = str->MaximumLength = 0;
549         str->Buffer = NULL;
550         return;
551     }
552     if ((char *)str->Buffer + str->MaximumLength > end_ptr)
553     {
554         str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
555     }
556     if (str->Length >= str->MaximumLength)
557     {
558         if (str->MaximumLength >= sizeof(WCHAR))
559             str->Length = str->MaximumLength - sizeof(WCHAR);
560         else
561             str->Length = str->MaximumLength = 0;
562     }
563 }
564
565
566 /***********************************************************************
567  *           init_user_process_params
568  *
569  * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
570  */
571 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
572 {
573     void *ptr;
574     DWORD size;
575     NTSTATUS status;
576     RTL_USER_PROCESS_PARAMETERS *params;
577
578     size = info_size;
579     if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
580                                            MEM_COMMIT, PAGE_READWRITE )) != STATUS_SUCCESS)
581         return NULL;
582
583     SERVER_START_REQ( get_startup_info )
584     {
585         wine_server_set_reply( req, ptr, info_size );
586         wine_server_call( req );
587         info_size = wine_server_reply_size( reply );
588     }
589     SERVER_END_REQ;
590
591     params = ptr;
592     params->Size = info_size;
593     params->AllocationSize = size;
594
595     /* make sure the strings are valid */
596     fix_unicode_string( &params->CurrentDirectoryName, (char *)info_size );
597     fix_unicode_string( &params->DllPath, (char *)info_size );
598     fix_unicode_string( &params->ImagePathName, (char *)info_size );
599     fix_unicode_string( &params->CommandLine, (char *)info_size );
600     fix_unicode_string( &params->WindowTitle, (char *)info_size );
601     fix_unicode_string( &params->Desktop, (char *)info_size );
602     fix_unicode_string( &params->ShellInfo, (char *)info_size );
603     fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
604
605     return RtlNormalizeProcessParams( params );
606 }
607
608
609 /***********************************************************************
610  *           process_init
611  *
612  * Main process initialisation code
613  */
614 static BOOL process_init( char *argv[], char **environ )
615 {
616     BOOL ret;
617     size_t info_size = 0;
618     RTL_USER_PROCESS_PARAMETERS *params;
619     PEB *peb = NtCurrentTeb()->Peb;
620     HANDLE hstdin, hstdout, hstderr;
621     extern void __wine_dbg_kernel32_init(void);
622
623     PTHREAD_Init();
624
625     __wine_dbg_kernel32_init();  /* hack: register debug channels early */
626
627     setbuf(stdout,NULL);
628     setbuf(stderr,NULL);
629     setlocale(LC_CTYPE,"");
630
631     /* Retrieve startup info from the server */
632     SERVER_START_REQ( init_process )
633     {
634         req->peb      = peb;
635         req->ldt_copy = &wine_ldt_copy;
636         if ((ret = !wine_server_call_err( req )))
637         {
638             main_exe_file     = reply->exe_file;
639             main_create_flags = reply->create_flags;
640             info_size         = reply->info_size;
641             server_startticks = reply->server_start;
642             hstdin            = reply->hstdin;
643             hstdout           = reply->hstdout;
644             hstderr           = reply->hstderr;
645         }
646     }
647     SERVER_END_REQ;
648     if (!ret) return FALSE;
649
650     if (info_size == 0)
651     {
652         params = peb->ProcessParameters;
653
654         /* This is wine specific: we have no parent (we're started from unix)
655          * so, create a simple console with bare handles to unix stdio 
656          * input & output streams (aka simple console)
657          */
658         wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE,  TRUE, &params->hStdInput );
659         wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdOutput );
660         wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdError );
661
662         /* <hack: to be changed later on> */
663         params->CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
664         params->CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
665         params->CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectoryName.MaximumLength);
666         params->CurrentDirectoryName.Buffer[0] = 'C';
667         params->CurrentDirectoryName.Buffer[1] = ':';
668         params->CurrentDirectoryName.Buffer[2] = '\\';
669         params->CurrentDirectoryName.Buffer[3] = '\0';
670         /* </hack: to be changed later on> */
671     }
672     else
673     {
674         if (!(params = init_user_process_params( info_size ))) return FALSE;
675         peb->ProcessParameters = params;
676
677         /* convert value from server:
678          * + 0 => INVALID_HANDLE_VALUE
679          * + console handle need to be mapped
680          */
681         if (!hstdin)
682             hstdin = INVALID_HANDLE_VALUE;
683         else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
684             hstdin = console_handle_map(hstdin);
685
686         if (!hstdout)
687             hstdout = INVALID_HANDLE_VALUE;
688         else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
689             hstdout = console_handle_map(hstdout);
690
691         if (!hstderr)
692             hstderr = INVALID_HANDLE_VALUE;
693         else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
694             hstderr = console_handle_map(hstderr);
695
696         params->hStdInput  = hstdin;
697         params->hStdOutput = hstdout;
698         params->hStdError  = hstderr;
699     }
700
701     LOCALE_Init();
702
703     /* Copy the parent environment */
704     if (!build_initial_environment( environ )) return FALSE;
705
706     /* Parse command line arguments */
707     OPTIONS_ParseOptions( !info_size ? argv : NULL );
708
709     /* initialise DOS drives */
710     if (!DRIVE_Init()) return FALSE;
711
712     /* initialise DOS directories */
713     if (!DIR_Init()) return FALSE;
714
715     /* registry initialisation */
716     SHELL_LoadRegistry();
717
718     /* global boot finished, the rest is process-local */
719     SERVER_START_REQ( boot_done )
720     {
721         req->debug_level = TRACE_ON(server);
722         wine_server_call( req );
723     }
724     SERVER_END_REQ;
725
726     return TRUE;
727 }
728
729
730 /***********************************************************************
731  *           start_process
732  *
733  * Startup routine of a new process. Runs on the new process stack.
734  */
735 static void start_process( void *arg )
736 {
737     __TRY
738     {
739         PEB *peb = NtCurrentTeb()->Peb;
740         IMAGE_NT_HEADERS *nt;
741         LPTHREAD_START_ROUTINE entry;
742
743         LdrInitializeThunk( main_exe_file, CreateFileW, 0, 0 );
744
745         nt = RtlImageNtHeader( peb->ImageBaseAddress );
746         entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
747                                          nt->OptionalHeader.AddressOfEntryPoint);
748
749         if (TRACE_ON(relay))
750             DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
751                      debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
752
753         SetLastError( 0 );  /* clear error code */
754         if (peb->BeingDebugged) DbgBreakPoint();
755         ExitProcess( entry( peb ) );
756     }
757     __EXCEPT(UnhandledExceptionFilter)
758     {
759         TerminateThread( GetCurrentThread(), GetExceptionCode() );
760     }
761     __ENDTRY
762 }
763
764
765 /***********************************************************************
766  *           __wine_kernel_init
767  *
768  * Wine initialisation: load and start the main exe file.
769  */
770 void __wine_kernel_init(void)
771 {
772     WCHAR *main_exe_name, *p;
773     char error[1024];
774     DWORD stack_size = 0;
775     int file_exists;
776     PEB *peb = NtCurrentTeb()->Peb;
777
778     /* Initialize everything */
779     if (!process_init( __wine_main_argv, __wine_main_environ )) exit(1);
780     /* update argc in case options have been removed */
781     for (__wine_main_argc = 0; __wine_main_argv[__wine_main_argc]; __wine_main_argc++) /*nothing*/;
782
783     __wine_main_argv++;  /* remove argv[0] (wine itself) */
784     __wine_main_argc--;
785
786     if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
787     {
788         WCHAR buffer[MAX_PATH];
789         WCHAR exe_nameW[MAX_PATH];
790
791         if (!__wine_main_argv[0]) OPTIONS_Usage();
792
793         MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
794         if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
795         {
796             MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
797             ExitProcess(1);
798         }
799         if (main_exe_file == INVALID_HANDLE_VALUE)
800         {
801             MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
802             ExitProcess(1);
803         }
804         RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
805         main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
806     }
807
808     TRACE( "starting process name=%s file=%p argv[0]=%s\n",
809            debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
810
811     MODULE_InitLoadPath();
812     VERSION_Init( main_exe_name );
813
814     if (!main_exe_file)  /* no file handle -> Winelib app */
815     {
816         TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
817         if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
818             goto found;
819         MESSAGE( "wine: cannot open builtin library for %s: %s\n",
820                  debugstr_w(main_exe_name), error );
821         ExitProcess(1);
822     }
823
824     switch( MODULE_GetBinaryType( main_exe_file ))
825     {
826     case BINARY_PE_EXE:
827         TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
828         if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
829             goto found;
830         MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
831         ExitProcess(1);
832     case BINARY_PE_DLL:
833         MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
834         ExitProcess(1);
835     case BINARY_UNKNOWN:
836         /* check for .com extension */
837         if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
838         {
839             MESSAGE( "wine: cannot determine executable type for %s\n",
840                      debugstr_w(main_exe_name) );
841             ExitProcess(1);
842         }
843         /* fall through */
844     case BINARY_WIN16:
845     case BINARY_DOS:
846         TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
847         CloseHandle( main_exe_file );
848         main_exe_file = 0;
849         __wine_main_argv--;
850         __wine_main_argc++;
851         __wine_main_argv[0] = "winevdm.exe";
852         if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
853             goto found;
854         MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
855                  debugstr_w(main_exe_name), error );
856         ExitProcess(1);
857     case BINARY_OS216:
858         MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
859         ExitProcess(1);
860     case BINARY_UNIX_EXE:
861         MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
862         ExitProcess(1);
863     case BINARY_UNIX_LIB:
864         {
865             DOS_FULL_NAME full_name;
866
867             TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
868             CloseHandle( main_exe_file );
869             main_exe_file = 0;
870             if (DOSFS_GetFullName( main_exe_name, TRUE, &full_name ) &&
871                 wine_dlopen( full_name.long_name, RTLD_NOW, error, sizeof(error) ))
872             {
873                 static const WCHAR soW[] = {'.','s','o',0};
874                 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
875                 {
876                     *p = 0;
877                     /* update the unicode string */
878                     RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
879                 }
880                 goto found;
881             }
882             MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
883             ExitProcess(1);
884         }
885     }
886
887  found:
888     wine_free_pe_load_area();  /* the main binary is loaded, we don't need this anymore */
889
890     /* build command line */
891     set_library_wargv( __wine_main_argv );
892     if (!build_command_line( __wine_main_wargv )) goto error;
893
894     stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
895
896     /* allocate main thread stack */
897     if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
898
899     /* switch to the new stack */
900     wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
901
902  error:
903     ExitProcess( GetLastError() );
904 }
905
906
907 /***********************************************************************
908  *           build_argv
909  *
910  * Build an argv array from a command-line.
911  * 'reserved' is the number of args to reserve before the first one.
912  */
913 static char **build_argv( const WCHAR *cmdlineW, int reserved )
914 {
915     int argc;
916     char** argv;
917     char *arg,*s,*d,*cmdline;
918     int in_quotes,bcount,len;
919
920     len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
921     if (!(cmdline = malloc(len))) return NULL;
922     WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
923
924     argc=reserved+1;
925     bcount=0;
926     in_quotes=0;
927     s=cmdline;
928     while (1) {
929         if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
930             /* space */
931             argc++;
932             /* skip the remaining spaces */
933             while (*s==' ' || *s=='\t') {
934                 s++;
935             }
936             if (*s=='\0')
937                 break;
938             bcount=0;
939             continue;
940         } else if (*s=='\\') {
941             /* '\', count them */
942             bcount++;
943         } else if ((*s=='"') && ((bcount & 1)==0)) {
944             /* unescaped '"' */
945             in_quotes=!in_quotes;
946             bcount=0;
947         } else {
948             /* a regular character */
949             bcount=0;
950         }
951         s++;
952     }
953     argv=malloc(argc*sizeof(*argv));
954     if (!argv)
955         return NULL;
956
957     arg=d=s=cmdline;
958     bcount=0;
959     in_quotes=0;
960     argc=reserved;
961     while (*s) {
962         if ((*s==' ' || *s=='\t') && !in_quotes) {
963             /* Close the argument and copy it */
964             *d=0;
965             argv[argc++]=arg;
966
967             /* skip the remaining spaces */
968             do {
969                 s++;
970             } while (*s==' ' || *s=='\t');
971
972             /* Start with a new argument */
973             arg=d=s;
974             bcount=0;
975         } else if (*s=='\\') {
976             /* '\\' */
977             *d++=*s++;
978             bcount++;
979         } else if (*s=='"') {
980             /* '"' */
981             if ((bcount & 1)==0) {
982                 /* Preceeded by an even number of '\', this is half that
983                  * number of '\', plus a '"' which we discard.
984                  */
985                 d-=bcount/2;
986                 s++;
987                 in_quotes=!in_quotes;
988             } else {
989                 /* Preceeded by an odd number of '\', this is half that
990                  * number of '\' followed by a '"'
991                  */
992                 d=d-bcount/2-1;
993                 *d++='"';
994                 s++;
995             }
996             bcount=0;
997         } else {
998             /* a regular character */
999             *d++=*s++;
1000             bcount=0;
1001         }
1002     }
1003     if (*arg) {
1004         *d='\0';
1005         argv[argc++]=arg;
1006     }
1007     argv[argc]=NULL;
1008
1009     return argv;
1010 }
1011
1012
1013 /***********************************************************************
1014  *           alloc_env_string
1015  *
1016  * Allocate an environment string; helper for build_envp
1017  */
1018 static char *alloc_env_string( const char *name, const char *value )
1019 {
1020     char *ret = malloc( strlen(name) + strlen(value) + 1 );
1021     strcpy( ret, name );
1022     strcat( ret, value );
1023     return ret;
1024 }
1025
1026 /***********************************************************************
1027  *           build_envp
1028  *
1029  * Build the environment of a new child process.
1030  */
1031 static char **build_envp( const WCHAR *envW, const WCHAR *extra_envW )
1032 {
1033     const WCHAR *p;
1034     char **envp;
1035     char *env, *extra_env = NULL;
1036     int count = 0, length;
1037
1038     if (extra_envW)
1039     {
1040         for (p = extra_envW; *p; count++) p += strlenW(p) + 1;
1041         p++;
1042         length = WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
1043                                       NULL, 0, NULL, NULL );
1044         if ((extra_env = malloc( length )))
1045             WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
1046                                  extra_env, length, NULL, NULL );
1047     }
1048     for (p = envW; *p; count++) p += strlenW(p) + 1;
1049     p++;
1050     length = WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, NULL, 0, NULL, NULL );
1051     if (!(env = malloc( length ))) return NULL;
1052     WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, env, length, NULL, NULL );
1053
1054     count += 4;
1055
1056     if ((envp = malloc( count * sizeof(*envp) )))
1057     {
1058         char **envptr = envp;
1059         char *p;
1060
1061         /* first the extra strings */
1062         if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = p;
1063         /* then put PATH, HOME and WINEPREFIX from the unix env */
1064         if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1065         if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1066         if ((p = getenv("WINEPREFIX"))) *envptr++ = alloc_env_string( "WINEPREFIX=", p );
1067         /* now put the Windows environment strings */
1068         for (p = env; *p; p += strlen(p) + 1)
1069         {
1070             if (!memcmp( p, "PATH=", 5 ))  /* store PATH as WINEPATH */
1071                 *envptr++ = alloc_env_string( "WINEPATH=", p + 5 );
1072             else if (memcmp( p, "HOME=", 5 ) &&
1073                      memcmp( p, "WINEPATH=", 9 ) &&
1074                      memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
1075         }
1076         *envptr = 0;
1077     }
1078     return envp;
1079 }
1080
1081
1082 /***********************************************************************
1083  *           fork_and_exec
1084  *
1085  * Fork and exec a new Unix binary, checking for errors.
1086  */
1087 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1088                           const WCHAR *env, const char *newdir )
1089 {
1090     int fd[2];
1091     int pid, err;
1092
1093     if (!env) env = GetEnvironmentStringsW();
1094
1095     if (pipe(fd) == -1)
1096     {
1097         FILE_SetDosError();
1098         return -1;
1099     }
1100     fcntl( fd[1], F_SETFD, 1 );  /* set close on exec */
1101     if (!(pid = fork()))  /* child */
1102     {
1103         char **argv = build_argv( cmdline, 0 );
1104         char **envp = build_envp( env, NULL );
1105         close( fd[0] );
1106
1107         /* Reset signals that we previously set to SIG_IGN */
1108         signal( SIGPIPE, SIG_DFL );
1109         signal( SIGCHLD, SIG_DFL );
1110
1111         if (newdir) chdir(newdir);
1112
1113         if (argv && envp) execve( filename, argv, envp );
1114         err = errno;
1115         write( fd[1], &err, sizeof(err) );
1116         _exit(1);
1117     }
1118     close( fd[1] );
1119     if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
1120     {
1121         errno = err;
1122         pid = -1;
1123     }
1124     if (pid == -1) FILE_SetDosError();
1125     close( fd[0] );
1126     return pid;
1127 }
1128
1129
1130 /***********************************************************************
1131  *           create_user_params
1132  */
1133 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1134                                                         const STARTUPINFOW *startup )
1135 {
1136     RTL_USER_PROCESS_PARAMETERS *params;
1137     UNICODE_STRING image_str, cmdline_str, desktop, title;
1138     NTSTATUS status;
1139     WCHAR buffer[MAX_PATH];
1140
1141     if (GetLongPathNameW( filename, buffer, MAX_PATH ))
1142         RtlInitUnicodeString( &image_str, buffer );
1143     else
1144         RtlInitUnicodeString( &image_str, filename );
1145
1146     RtlInitUnicodeString( &cmdline_str, cmdline );
1147     if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1148     if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1149
1150     status = RtlCreateProcessParameters( &params, &image_str, NULL, NULL, &cmdline_str, NULL,
1151                                          startup->lpTitle ? &title : NULL,
1152                                          startup->lpDesktop ? &desktop : NULL,
1153                                          NULL, NULL );
1154     if (status != STATUS_SUCCESS)
1155     {
1156         SetLastError( RtlNtStatusToDosError(status) );
1157         return NULL;
1158     }
1159
1160     params->Environment     = NULL;  /* we pass it through the Unix environment */
1161     params->hStdInput       = startup->hStdInput;
1162     params->hStdOutput      = startup->hStdOutput;
1163     params->hStdError       = startup->hStdError;
1164     params->dwX             = startup->dwX;
1165     params->dwY             = startup->dwY;
1166     params->dwXSize         = startup->dwXSize;
1167     params->dwYSize         = startup->dwYSize;
1168     params->dwXCountChars   = startup->dwXCountChars;
1169     params->dwYCountChars   = startup->dwYCountChars;
1170     params->dwFillAttribute = startup->dwFillAttribute;
1171     params->dwFlags         = startup->dwFlags;
1172     params->wShowWindow     = startup->wShowWindow;
1173     return params;
1174 }
1175
1176
1177 /***********************************************************************
1178  *           create_process
1179  *
1180  * Create a new process. If hFile is a valid handle we have an exe
1181  * file, otherwise it is a Winelib app.
1182  */
1183 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1184                             LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1185                             BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1186                             LPPROCESS_INFORMATION info, LPCSTR unixdir )
1187 {
1188     BOOL ret, success = FALSE;
1189     HANDLE process_info;
1190     RTL_USER_PROCESS_PARAMETERS *params;
1191     WCHAR *extra_env = NULL;
1192     int startfd[2];
1193     int execfd[2];
1194     pid_t pid;
1195     int err;
1196     char dummy = 0;
1197
1198     if (!env)
1199     {
1200         env = GetEnvironmentStringsW();
1201         extra_env = DRIVE_BuildEnv();
1202     }
1203
1204     if (!(params = create_user_params( filename, cmd_line, startup )))
1205     {
1206         if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1207         return FALSE;
1208     }
1209
1210     /* create the synchronization pipes */
1211
1212     if (pipe( startfd ) == -1)
1213     {
1214         FILE_SetDosError();
1215         RtlDestroyProcessParameters( params );
1216         if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1217         return FALSE;
1218     }
1219     if (pipe( execfd ) == -1)
1220     {
1221         FILE_SetDosError();
1222         close( startfd[0] );
1223         close( startfd[1] );
1224         RtlDestroyProcessParameters( params );
1225         if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1226         return FALSE;
1227     }
1228     fcntl( execfd[1], F_SETFD, 1 );  /* set close on exec */
1229
1230     /* create the child process */
1231
1232     if (!(pid = fork()))  /* child */
1233     {
1234         char **argv = build_argv( cmd_line, 1 );
1235         char **envp = build_envp( env, extra_env );
1236
1237         close( startfd[1] );
1238         close( execfd[0] );
1239
1240         /* wait for parent to tell us to start */
1241         if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1242
1243         close( startfd[0] );
1244         /* Reset signals that we previously set to SIG_IGN */
1245         signal( SIGPIPE, SIG_DFL );
1246         signal( SIGCHLD, SIG_DFL );
1247
1248         if (unixdir) chdir(unixdir);
1249
1250         if (argv && envp)
1251         {
1252             /* first, try for a WINELOADER environment variable */
1253             argv[0] = getenv("WINELOADER");
1254             if (argv[0]) execve( argv[0], argv, envp );
1255             /* now use the standard search strategy */
1256             wine_exec_wine_binary( NULL, argv, envp );
1257         }
1258         err = errno;
1259         write( execfd[1], &err, sizeof(err) );
1260         _exit(1);
1261     }
1262
1263     /* this is the parent */
1264
1265     close( startfd[0] );
1266     close( execfd[1] );
1267     if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1268     if (pid == -1)
1269     {
1270         close( startfd[1] );
1271         close( execfd[0] );
1272         FILE_SetDosError();
1273         RtlDestroyProcessParameters( params );
1274         return FALSE;
1275     }
1276
1277     /* create the process on the server side */
1278
1279     SERVER_START_REQ( new_process )
1280     {
1281         req->inherit_all  = inherit;
1282         req->create_flags = flags;
1283         req->unix_pid     = pid;
1284         req->exe_file     = hFile;
1285         if (startup->dwFlags & STARTF_USESTDHANDLES)
1286         {
1287             req->hstdin  = startup->hStdInput;
1288             req->hstdout = startup->hStdOutput;
1289             req->hstderr = startup->hStdError;
1290         }
1291         else
1292         {
1293             req->hstdin  = GetStdHandle( STD_INPUT_HANDLE );
1294             req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1295             req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1296         }
1297
1298         if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1299         {
1300             /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1301             if (is_console_handle(req->hstdin))  req->hstdin  = INVALID_HANDLE_VALUE;
1302             if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1303             if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1304         }
1305         else
1306         {
1307             if (is_console_handle(req->hstdin))  req->hstdin  = console_handle_unmap(req->hstdin);
1308             if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1309             if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1310         }
1311
1312         wine_server_add_data( req, params, params->Size );
1313         ret = !wine_server_call_err( req );
1314         process_info = reply->info;
1315     }
1316     SERVER_END_REQ;
1317
1318     RtlDestroyProcessParameters( params );
1319     if (!ret)
1320     {
1321         close( startfd[1] );
1322         close( execfd[0] );
1323         return FALSE;
1324     }
1325
1326     /* tell child to start and wait for it to exec */
1327
1328     write( startfd[1], &dummy, 1 );
1329     close( startfd[1] );
1330
1331     if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1332     {
1333         errno = err;
1334         FILE_SetDosError();
1335         close( execfd[0] );
1336         CloseHandle( process_info );
1337         return FALSE;
1338     }
1339
1340     /* wait for the new process info to be ready */
1341
1342     WaitForSingleObject( process_info, INFINITE );
1343     SERVER_START_REQ( get_new_process_info )
1344     {
1345         req->info     = process_info;
1346         req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1347         req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1348         if ((ret = !wine_server_call_err( req )))
1349         {
1350             info->dwProcessId = (DWORD)reply->pid;
1351             info->dwThreadId  = (DWORD)reply->tid;
1352             info->hProcess    = reply->phandle;
1353             info->hThread     = reply->thandle;
1354             success           = reply->success;
1355         }
1356     }
1357     SERVER_END_REQ;
1358
1359     if (ret && !success)  /* new process failed to start */
1360     {
1361         DWORD exitcode;
1362         if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1363         CloseHandle( info->hThread );
1364         CloseHandle( info->hProcess );
1365         ret = FALSE;
1366     }
1367     CloseHandle( process_info );
1368     return ret;
1369 }
1370
1371
1372 /***********************************************************************
1373  *           create_vdm_process
1374  *
1375  * Create a new VDM process for a 16-bit or DOS application.
1376  */
1377 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1378                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1379                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1380                                 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1381 {
1382     static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1383
1384     BOOL ret;
1385     LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1386                                      (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1387
1388     if (!new_cmd_line)
1389     {
1390         SetLastError( ERROR_OUTOFMEMORY );
1391         return FALSE;
1392     }
1393     sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1394     ret = create_process( 0, winevdmW, new_cmd_line, env, psa, tsa, inherit,
1395                           flags, startup, info, unixdir );
1396     HeapFree( GetProcessHeap(), 0, new_cmd_line );
1397     return ret;
1398 }
1399
1400
1401 /***********************************************************************
1402  *           create_cmd_process
1403  *
1404  * Create a new cmd shell process for a .BAT file.
1405  */
1406 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env,
1407                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1408                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1409                                 LPPROCESS_INFORMATION info, LPCWSTR cur_dir )
1410
1411 {
1412     static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1413     static const WCHAR slashcW[] = {' ','/','c',' ',0};
1414     WCHAR comspec[MAX_PATH];
1415     WCHAR *newcmdline;
1416     BOOL ret;
1417
1418     if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1419         return FALSE;
1420     if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1421                                   (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1422         return FALSE;
1423
1424     strcpyW( newcmdline, comspec );
1425     strcatW( newcmdline, slashcW );
1426     strcatW( newcmdline, cmd_line );
1427     ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1428                           flags, env, cur_dir, startup, info );
1429     HeapFree( GetProcessHeap(), 0, newcmdline );
1430     return ret;
1431 }
1432
1433
1434 /*************************************************************************
1435  *               get_file_name
1436  *
1437  * Helper for CreateProcess: retrieve the file name to load from the
1438  * app name and command line. Store the file name in buffer, and
1439  * return a possibly modified command line.
1440  * Also returns a handle to the opened file if it's a Windows binary.
1441  */
1442 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1443                              int buflen, HANDLE *handle )
1444 {
1445     static const WCHAR quotesW[] = {'"','%','s','"',0};
1446
1447     WCHAR *name, *pos, *ret = NULL;
1448     const WCHAR *p;
1449
1450     /* if we have an app name, everything is easy */
1451
1452     if (appname)
1453     {
1454         /* use the unmodified app name as file name */
1455         lstrcpynW( buffer, appname, buflen );
1456         *handle = open_exe_file( buffer );
1457         if (!(ret = cmdline) || !cmdline[0])
1458         {
1459             /* no command-line, create one */
1460             if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1461                 sprintfW( ret, quotesW, appname );
1462         }
1463         return ret;
1464     }
1465
1466     if (!cmdline)
1467     {
1468         SetLastError( ERROR_INVALID_PARAMETER );
1469         return NULL;
1470     }
1471
1472     /* first check for a quoted file name */
1473
1474     if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1475     {
1476         int len = p - cmdline - 1;
1477         /* extract the quoted portion as file name */
1478         if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1479         memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1480         name[len] = 0;
1481
1482         if (find_exe_file( name, buffer, buflen, handle ))
1483             ret = cmdline;  /* no change necessary */
1484         goto done;
1485     }
1486
1487     /* now try the command-line word by word */
1488
1489     if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1490         return NULL;
1491     pos = name;
1492     p = cmdline;
1493
1494     while (*p)
1495     {
1496         do *pos++ = *p++; while (*p && *p != ' ');
1497         *pos = 0;
1498         if (find_exe_file( name, buffer, buflen, handle ))
1499         {
1500             ret = cmdline;
1501             break;
1502         }
1503     }
1504
1505     if (!ret || !strchrW( name, ' ' )) goto done;  /* no change necessary */
1506
1507     /* now build a new command-line with quotes */
1508
1509     if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1510         goto done;
1511     sprintfW( ret, quotesW, name );
1512     strcatW( ret, p );
1513
1514  done:
1515     HeapFree( GetProcessHeap(), 0, name );
1516     return ret;
1517 }
1518
1519
1520 /**********************************************************************
1521  *       CreateProcessA          (KERNEL32.@)
1522  */
1523 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1524                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1525                             DWORD flags, LPVOID env, LPCSTR cur_dir,
1526                             LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1527 {
1528     BOOL ret;
1529     UNICODE_STRING app_nameW, cmd_lineW, cur_dirW, desktopW, titleW;
1530     STARTUPINFOW infoW;
1531
1532     if (app_name) RtlCreateUnicodeStringFromAsciiz( &app_nameW, app_name );
1533     else app_nameW.Buffer = NULL;
1534     if (cmd_line) RtlCreateUnicodeStringFromAsciiz( &cmd_lineW, cmd_line );
1535     else cmd_lineW.Buffer = NULL;
1536     if (cur_dir) RtlCreateUnicodeStringFromAsciiz( &cur_dirW, cur_dir );
1537     else cur_dirW.Buffer = NULL;
1538     if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1539     else desktopW.Buffer = NULL;
1540     if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1541     else titleW.Buffer = NULL;
1542
1543     memcpy( &infoW, startup_info, sizeof(infoW) );
1544     infoW.lpDesktop = desktopW.Buffer;
1545     infoW.lpTitle = titleW.Buffer;
1546
1547     if (startup_info->lpReserved)
1548       FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1549             debugstr_a(startup_info->lpReserved));
1550
1551     ret = CreateProcessW( app_nameW.Buffer,  cmd_lineW.Buffer, process_attr, thread_attr,
1552                           inherit, flags, env, cur_dirW.Buffer, &infoW, info );
1553
1554     RtlFreeUnicodeString( &app_nameW );
1555     RtlFreeUnicodeString( &cmd_lineW );
1556     RtlFreeUnicodeString( &cur_dirW );
1557     RtlFreeUnicodeString( &desktopW );
1558     RtlFreeUnicodeString( &titleW );
1559     return ret;
1560 }
1561
1562
1563 /**********************************************************************
1564  *       CreateProcessW          (KERNEL32.@)
1565  */
1566 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1567                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1568                             LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1569                             LPPROCESS_INFORMATION info )
1570 {
1571     BOOL retv = FALSE;
1572     HANDLE hFile = 0;
1573     const char *unixdir = NULL;
1574     DOS_FULL_NAME full_dir;
1575     WCHAR name[MAX_PATH];
1576     WCHAR *tidy_cmdline, *p, *envW = env;
1577
1578     /* Process the AppName and/or CmdLine to get module name and path */
1579
1580     TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1581
1582     if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1583         return FALSE;
1584     if (hFile == INVALID_HANDLE_VALUE) goto done;
1585
1586     /* Warn if unsupported features are used */
1587
1588     if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1589                  CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1590                  CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1591                  PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1592         WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1593
1594     if (cur_dir)
1595     {
1596         if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir )) unixdir = full_dir.long_name;
1597     }
1598     else
1599     {
1600         WCHAR buf[MAX_PATH];
1601         if (GetCurrentDirectoryW(MAX_PATH, buf))
1602         {
1603             if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1604         }
1605     }
1606
1607     if (env && !(flags & CREATE_UNICODE_ENVIRONMENT))  /* convert environment to unicode */
1608     {
1609         char *p = env;
1610         DWORD lenW;
1611
1612         while (*p) p += strlen(p) + 1;
1613         p++;  /* final null */
1614         lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1615         envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1616         MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1617         flags |= CREATE_UNICODE_ENVIRONMENT;
1618     }
1619
1620     info->hThread = info->hProcess = 0;
1621     info->dwProcessId = info->dwThreadId = 0;
1622
1623     /* Determine executable type */
1624
1625     if (!hFile)  /* builtin exe */
1626     {
1627         TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1628         retv = create_process( 0, name, tidy_cmdline, envW, process_attr, thread_attr,
1629                                inherit, flags, startup_info, info, unixdir );
1630         goto done;
1631     }
1632
1633     switch( MODULE_GetBinaryType( hFile ))
1634     {
1635     case BINARY_PE_EXE:
1636         TRACE( "starting %s as Win32 binary\n", debugstr_w(name) );
1637         retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1638                                inherit, flags, startup_info, info, unixdir );
1639         break;
1640     case BINARY_WIN16:
1641     case BINARY_DOS:
1642         TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1643         retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1644                                    inherit, flags, startup_info, info, unixdir );
1645         break;
1646     case BINARY_OS216:
1647         FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1648         SetLastError( ERROR_BAD_EXE_FORMAT );
1649         break;
1650     case BINARY_PE_DLL:
1651         TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1652         SetLastError( ERROR_BAD_EXE_FORMAT );
1653         break;
1654     case BINARY_UNIX_LIB:
1655         TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1656         retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1657                                inherit, flags, startup_info, info, unixdir );
1658         break;
1659     case BINARY_UNKNOWN:
1660         /* check for .com or .bat extension */
1661         if ((p = strrchrW( name, '.' )))
1662         {
1663             if (!strcmpiW( p, comW ))
1664             {
1665                 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1666                 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1667                                            inherit, flags, startup_info, info, unixdir );
1668                 break;
1669             }
1670             if (!strcmpiW( p, batW ))
1671             {
1672                 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1673                 retv = create_cmd_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1674                                            inherit, flags, startup_info, info, cur_dir );
1675                 break;
1676             }
1677         }
1678         /* fall through */
1679     case BINARY_UNIX_EXE:
1680         {
1681             /* unknown file, try as unix executable */
1682             DOS_FULL_NAME full_name;
1683
1684             TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1685
1686             if (DOSFS_GetFullName( name, TRUE, &full_name ))
1687                 retv = (fork_and_exec( full_name.long_name, tidy_cmdline, envW, unixdir ) != -1);
1688         }
1689         break;
1690     }
1691     CloseHandle( hFile );
1692
1693  done:
1694     if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1695     if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1696     return retv;
1697 }
1698
1699
1700 /***********************************************************************
1701  *           wait_input_idle
1702  *
1703  * Wrapper to call WaitForInputIdle USER function
1704  */
1705 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1706
1707 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1708 {
1709     HMODULE mod = GetModuleHandleA( "user32.dll" );
1710     if (mod)
1711     {
1712         WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1713         if (ptr) return ptr( process, timeout );
1714     }
1715     return 0;
1716 }
1717
1718
1719 /***********************************************************************
1720  *           WinExec   (KERNEL32.@)
1721  */
1722 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1723 {
1724     PROCESS_INFORMATION info;
1725     STARTUPINFOA startup;
1726     char *cmdline;
1727     UINT ret;
1728
1729     memset( &startup, 0, sizeof(startup) );
1730     startup.cb = sizeof(startup);
1731     startup.dwFlags = STARTF_USESHOWWINDOW;
1732     startup.wShowWindow = nCmdShow;
1733
1734     /* cmdline needs to be writeable for CreateProcess */
1735     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1736     strcpy( cmdline, lpCmdLine );
1737
1738     if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1739                         0, NULL, NULL, &startup, &info ))
1740     {
1741         /* Give 30 seconds to the app to come up */
1742         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1743             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1744         ret = 33;
1745         /* Close off the handles */
1746         CloseHandle( info.hThread );
1747         CloseHandle( info.hProcess );
1748     }
1749     else if ((ret = GetLastError()) >= 32)
1750     {
1751         FIXME("Strange error set by CreateProcess: %d\n", ret );
1752         ret = 11;
1753     }
1754     HeapFree( GetProcessHeap(), 0, cmdline );
1755     return ret;
1756 }
1757
1758
1759 /**********************************************************************
1760  *          LoadModule    (KERNEL32.@)
1761  */
1762 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1763 {
1764     LOADPARMS32 *params = paramBlock;
1765     PROCESS_INFORMATION info;
1766     STARTUPINFOA startup;
1767     HINSTANCE hInstance;
1768     LPSTR cmdline, p;
1769     char filename[MAX_PATH];
1770     BYTE len;
1771
1772     if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1773
1774     if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1775         !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1776         return (HINSTANCE)GetLastError();
1777
1778     len = (BYTE)params->lpCmdLine[0];
1779     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1780         return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1781
1782     strcpy( cmdline, filename );
1783     p = cmdline + strlen(cmdline);
1784     *p++ = ' ';
1785     memcpy( p, params->lpCmdLine + 1, len );
1786     p[len] = 0;
1787
1788     memset( &startup, 0, sizeof(startup) );
1789     startup.cb = sizeof(startup);
1790     if (params->lpCmdShow)
1791     {
1792         startup.dwFlags = STARTF_USESHOWWINDOW;
1793         startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1794     }
1795
1796     if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1797                         params->lpEnvAddress, NULL, &startup, &info ))
1798     {
1799         /* Give 30 seconds to the app to come up */
1800         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1801             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1802         hInstance = (HINSTANCE)33;
1803         /* Close off the handles */
1804         CloseHandle( info.hThread );
1805         CloseHandle( info.hProcess );
1806     }
1807     else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1808     {
1809         FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1810         hInstance = (HINSTANCE)11;
1811     }
1812
1813     HeapFree( GetProcessHeap(), 0, cmdline );
1814     return hInstance;
1815 }
1816
1817
1818 /******************************************************************************
1819  *           TerminateProcess   (KERNEL32.@)
1820  */
1821 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1822 {
1823     NTSTATUS status = NtTerminateProcess( handle, exit_code );
1824     if (status) SetLastError( RtlNtStatusToDosError(status) );
1825     return !status;
1826 }
1827
1828
1829 /***********************************************************************
1830  *           ExitProcess   (KERNEL32.@)
1831  */
1832 void WINAPI ExitProcess( DWORD status )
1833 {
1834     LdrShutdownProcess();
1835     SERVER_START_REQ( terminate_process )
1836     {
1837         /* send the exit code to the server */
1838         req->handle    = GetCurrentProcess();
1839         req->exit_code = status;
1840         wine_server_call( req );
1841     }
1842     SERVER_END_REQ;
1843     exit( status );
1844 }
1845
1846
1847 /***********************************************************************
1848  * GetExitCodeProcess [KERNEL32.@]
1849  *
1850  * Gets termination status of specified process
1851  *
1852  * RETURNS
1853  *   Success: TRUE
1854  *   Failure: FALSE
1855  */
1856 BOOL WINAPI GetExitCodeProcess(
1857     HANDLE hProcess,    /* [in] handle to the process */
1858     LPDWORD lpExitCode) /* [out] address to receive termination status */
1859 {
1860     BOOL ret;
1861     SERVER_START_REQ( get_process_info )
1862     {
1863         req->handle = hProcess;
1864         ret = !wine_server_call_err( req );
1865         if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1866     }
1867     SERVER_END_REQ;
1868     return ret;
1869 }
1870
1871
1872 /***********************************************************************
1873  *           SetErrorMode   (KERNEL32.@)
1874  */
1875 UINT WINAPI SetErrorMode( UINT mode )
1876 {
1877     UINT old = process_error_mode;
1878     process_error_mode = mode;
1879     return old;
1880 }
1881
1882
1883 /**********************************************************************
1884  * TlsAlloc [KERNEL32.@]  Allocates a TLS index.
1885  *
1886  * Allocates a thread local storage index
1887  *
1888  * RETURNS
1889  *    Success: TLS Index
1890  *    Failure: 0xFFFFFFFF
1891  */
1892 DWORD WINAPI TlsAlloc( void )
1893 {
1894     DWORD index;
1895
1896     RtlAcquirePebLock();
1897     index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
1898     if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
1899     else SetLastError( ERROR_NO_MORE_ITEMS );
1900     RtlReleasePebLock();
1901     return index;
1902 }
1903
1904
1905 /**********************************************************************
1906  * TlsFree [KERNEL32.@]  Releases a TLS index.
1907  *
1908  * Releases a thread local storage index, making it available for reuse
1909  *
1910  * RETURNS
1911  *    Success: TRUE
1912  *    Failure: FALSE
1913  */
1914 BOOL WINAPI TlsFree(
1915     DWORD index) /* [in] TLS Index to free */
1916 {
1917     BOOL ret;
1918
1919     RtlAcquirePebLock();
1920     ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1921     if (ret)
1922     {
1923         RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1924         NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1925     }
1926     else SetLastError( ERROR_INVALID_PARAMETER );
1927     RtlReleasePebLock();
1928     return TRUE;
1929 }
1930
1931
1932 /**********************************************************************
1933  * TlsGetValue [KERNEL32.@]  Gets value in a thread's TLS slot
1934  *
1935  * RETURNS
1936  *    Success: Value stored in calling thread's TLS slot for index
1937  *    Failure: 0 and GetLastError returns NO_ERROR
1938  */
1939 LPVOID WINAPI TlsGetValue(
1940     DWORD index) /* [in] TLS index to retrieve value for */
1941 {
1942     if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1943     {
1944         SetLastError( ERROR_INVALID_PARAMETER );
1945         return NULL;
1946     }
1947     SetLastError( ERROR_SUCCESS );
1948     return NtCurrentTeb()->TlsSlots[index];
1949 }
1950
1951
1952 /**********************************************************************
1953  * TlsSetValue [KERNEL32.@]  Stores a value in the thread's TLS slot.
1954  *
1955  * RETURNS
1956  *    Success: TRUE
1957  *    Failure: FALSE
1958  */
1959 BOOL WINAPI TlsSetValue(
1960     DWORD index,  /* [in] TLS index to set value for */
1961     LPVOID value) /* [in] Value to be stored */
1962 {
1963     if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1964     {
1965         SetLastError( ERROR_INVALID_PARAMETER );
1966         return FALSE;
1967     }
1968     NtCurrentTeb()->TlsSlots[index] = value;
1969     return TRUE;
1970 }
1971
1972
1973 /***********************************************************************
1974  *           GetProcessFlags    (KERNEL32.@)
1975  */
1976 DWORD WINAPI GetProcessFlags( DWORD processid )
1977 {
1978     IMAGE_NT_HEADERS *nt;
1979     DWORD flags = 0;
1980
1981     if (processid && processid != GetCurrentProcessId()) return 0;
1982
1983     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1984     {
1985         if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
1986             flags |= PDB32_CONSOLE_PROC;
1987     }
1988     if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
1989     if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
1990     return flags;
1991 }
1992
1993
1994 /***********************************************************************
1995  *           GetProcessDword    (KERNEL.485)
1996  *           GetProcessDword    (KERNEL32.18)
1997  * 'Of course you cannot directly access Windows internal structures'
1998  */
1999 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2000 {
2001     DWORD               x, y;
2002     STARTUPINFOW        siw;
2003
2004     TRACE("(%ld, %d)\n", dwProcessID, offset );
2005
2006     if (dwProcessID && dwProcessID != GetCurrentProcessId())
2007     {
2008         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2009         return 0;
2010     }
2011
2012     switch ( offset )
2013     {
2014     case GPD_APP_COMPAT_FLAGS:
2015         return GetAppCompatFlags16(0);
2016     case GPD_LOAD_DONE_EVENT:
2017         return 0;
2018     case GPD_HINSTANCE16:
2019         return GetTaskDS16();
2020     case GPD_WINDOWS_VERSION:
2021         return GetExeVersion16();
2022     case GPD_THDB:
2023         return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2024     case GPD_PDB:
2025         return (DWORD)NtCurrentTeb()->Peb;
2026     case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2027         GetStartupInfoW(&siw);
2028         return (DWORD)siw.hStdOutput;
2029     case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2030         GetStartupInfoW(&siw);
2031         return (DWORD)siw.hStdInput;
2032     case GPD_STARTF_SHOWWINDOW:
2033         GetStartupInfoW(&siw);
2034         return siw.wShowWindow;
2035     case GPD_STARTF_SIZE:
2036         GetStartupInfoW(&siw);
2037         x = siw.dwXSize;
2038         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2039         y = siw.dwYSize;
2040         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2041         return MAKELONG( x, y );
2042     case GPD_STARTF_POSITION:
2043         GetStartupInfoW(&siw);
2044         x = siw.dwX;
2045         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2046         y = siw.dwY;
2047         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2048         return MAKELONG( x, y );
2049     case GPD_STARTF_FLAGS:
2050         GetStartupInfoW(&siw);
2051         return siw.dwFlags;
2052     case GPD_PARENT:
2053         return 0;
2054     case GPD_FLAGS:
2055         return GetProcessFlags(0);
2056     case GPD_USERDATA:
2057         return process_dword;
2058     default:
2059         ERR("Unknown offset %d\n", offset );
2060         return 0;
2061     }
2062 }
2063
2064 /***********************************************************************
2065  *           SetProcessDword    (KERNEL.484)
2066  * 'Of course you cannot directly access Windows internal structures'
2067  */
2068 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2069 {
2070     TRACE("(%ld, %d)\n", dwProcessID, offset );
2071
2072     if (dwProcessID && dwProcessID != GetCurrentProcessId())
2073     {
2074         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2075         return;
2076     }
2077
2078     switch ( offset )
2079     {
2080     case GPD_APP_COMPAT_FLAGS:
2081     case GPD_LOAD_DONE_EVENT:
2082     case GPD_HINSTANCE16:
2083     case GPD_WINDOWS_VERSION:
2084     case GPD_THDB:
2085     case GPD_PDB:
2086     case GPD_STARTF_SHELLDATA:
2087     case GPD_STARTF_HOTKEY:
2088     case GPD_STARTF_SHOWWINDOW:
2089     case GPD_STARTF_SIZE:
2090     case GPD_STARTF_POSITION:
2091     case GPD_STARTF_FLAGS:
2092     case GPD_PARENT:
2093     case GPD_FLAGS:
2094         ERR("Not allowed to modify offset %d\n", offset );
2095         break;
2096     case GPD_USERDATA:
2097         process_dword = value;
2098         break;
2099     default:
2100         ERR("Unknown offset %d\n", offset );
2101         break;
2102     }
2103 }
2104
2105
2106 /***********************************************************************
2107  *           ExitProcess   (KERNEL.466)
2108  */
2109 void WINAPI ExitProcess16( WORD status )
2110 {
2111     DWORD count;
2112     ReleaseThunkLock( &count );
2113     ExitProcess( status );
2114 }
2115
2116
2117 /*********************************************************************
2118  *           OpenProcess   (KERNEL32.@)
2119  */
2120 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2121 {
2122     HANDLE ret = 0;
2123     SERVER_START_REQ( open_process )
2124     {
2125         req->pid     = id;
2126         req->access  = access;
2127         req->inherit = inherit;
2128         if (!wine_server_call_err( req )) ret = reply->handle;
2129     }
2130     SERVER_END_REQ;
2131     return ret;
2132 }
2133
2134
2135 /*********************************************************************
2136  *           MapProcessHandle   (KERNEL.483)
2137  */
2138 DWORD WINAPI MapProcessHandle( HANDLE handle )
2139 {
2140     DWORD ret = 0;
2141     SERVER_START_REQ( get_process_info )
2142     {
2143         req->handle = handle;
2144         if (!wine_server_call_err( req )) ret = reply->pid;
2145     }
2146     SERVER_END_REQ;
2147     return ret;
2148 }
2149
2150
2151 /*********************************************************************
2152  *           CloseW32Handle (KERNEL.474)
2153  *           CloseHandle    (KERNEL32.@)
2154  */
2155 BOOL WINAPI CloseHandle( HANDLE handle )
2156 {
2157     NTSTATUS status;
2158
2159     /* stdio handles need special treatment */
2160     if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2161         (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2162         (handle == (HANDLE)STD_ERROR_HANDLE))
2163         handle = GetStdHandle( (DWORD)handle );
2164
2165     if (is_console_handle(handle))
2166         return CloseConsoleHandle(handle);
2167
2168     status = NtClose( handle );
2169     if (status) SetLastError( RtlNtStatusToDosError(status) );
2170     return !status;
2171 }
2172
2173
2174 /*********************************************************************
2175  *           GetHandleInformation   (KERNEL32.@)
2176  */
2177 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2178 {
2179     BOOL ret;
2180     SERVER_START_REQ( set_handle_info )
2181     {
2182         req->handle = handle;
2183         req->flags  = 0;
2184         req->mask   = 0;
2185         req->fd     = -1;
2186         ret = !wine_server_call_err( req );
2187         if (ret && flags) *flags = reply->old_flags;
2188     }
2189     SERVER_END_REQ;
2190     return ret;
2191 }
2192
2193
2194 /*********************************************************************
2195  *           SetHandleInformation   (KERNEL32.@)
2196  */
2197 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2198 {
2199     BOOL ret;
2200     SERVER_START_REQ( set_handle_info )
2201     {
2202         req->handle = handle;
2203         req->flags  = flags;
2204         req->mask   = mask;
2205         req->fd     = -1;
2206         ret = !wine_server_call_err( req );
2207     }
2208     SERVER_END_REQ;
2209     return ret;
2210 }
2211
2212
2213 /*********************************************************************
2214  *           DuplicateHandle   (KERNEL32.@)
2215  */
2216 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2217                              HANDLE dest_process, HANDLE *dest,
2218                              DWORD access, BOOL inherit, DWORD options )
2219 {
2220     NTSTATUS status;
2221
2222     if (is_console_handle(source))
2223     {
2224         /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2225         if (source_process != dest_process ||
2226             source_process != GetCurrentProcess())
2227         {
2228             SetLastError(ERROR_INVALID_PARAMETER);
2229             return FALSE;
2230         }
2231         *dest = DuplicateConsoleHandle( source, access, inherit, options );
2232         return (*dest != INVALID_HANDLE_VALUE);
2233     }
2234     status = NtDuplicateObject( source_process, source, dest_process, dest,
2235                                 access, inherit ? OBJ_INHERIT : 0, options );
2236     if (status) SetLastError( RtlNtStatusToDosError(status) );
2237     return !status;
2238 }
2239
2240
2241 /***********************************************************************
2242  *           ConvertToGlobalHandle   (KERNEL.476)
2243  *           ConvertToGlobalHandle  (KERNEL32.@)
2244  */
2245 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2246 {
2247     HANDLE ret = INVALID_HANDLE_VALUE;
2248     DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2249                      DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2250     return ret;
2251 }
2252
2253
2254 /***********************************************************************
2255  *           SetHandleContext   (KERNEL32.@)
2256  */
2257 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2258 {
2259     FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2260           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2261     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2262     return FALSE;
2263 }
2264
2265
2266 /***********************************************************************
2267  *           GetHandleContext   (KERNEL32.@)
2268  */
2269 DWORD WINAPI GetHandleContext(HANDLE hnd)
2270 {
2271     FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2272           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2273     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2274     return 0;
2275 }
2276
2277
2278 /***********************************************************************
2279  *           CreateSocketHandle   (KERNEL32.@)
2280  */
2281 HANDLE WINAPI CreateSocketHandle(void)
2282 {
2283     FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2284           "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2285     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2286     return INVALID_HANDLE_VALUE;
2287 }
2288
2289
2290 /***********************************************************************
2291  *           SetPriorityClass   (KERNEL32.@)
2292  */
2293 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2294 {
2295     BOOL ret;
2296     SERVER_START_REQ( set_process_info )
2297     {
2298         req->handle   = hprocess;
2299         req->priority = priorityclass;
2300         req->mask     = SET_PROCESS_INFO_PRIORITY;
2301         ret = !wine_server_call_err( req );
2302     }
2303     SERVER_END_REQ;
2304     return ret;
2305 }
2306
2307
2308 /***********************************************************************
2309  *           GetPriorityClass   (KERNEL32.@)
2310  */
2311 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2312 {
2313     DWORD ret = 0;
2314     SERVER_START_REQ( get_process_info )
2315     {
2316         req->handle = hprocess;
2317         if (!wine_server_call_err( req )) ret = reply->priority;
2318     }
2319     SERVER_END_REQ;
2320     return ret;
2321 }
2322
2323
2324 /***********************************************************************
2325  *          SetProcessAffinityMask   (KERNEL32.@)
2326  */
2327 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2328 {
2329     BOOL ret;
2330     SERVER_START_REQ( set_process_info )
2331     {
2332         req->handle   = hProcess;
2333         req->affinity = affmask;
2334         req->mask     = SET_PROCESS_INFO_AFFINITY;
2335         ret = !wine_server_call_err( req );
2336     }
2337     SERVER_END_REQ;
2338     return ret;
2339 }
2340
2341
2342 /**********************************************************************
2343  *          GetProcessAffinityMask    (KERNEL32.@)
2344  */
2345 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2346                                       LPDWORD lpProcessAffinityMask,
2347                                       LPDWORD lpSystemAffinityMask )
2348 {
2349     BOOL ret = FALSE;
2350     SERVER_START_REQ( get_process_info )
2351     {
2352         req->handle = hProcess;
2353         if (!wine_server_call_err( req ))
2354         {
2355             if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2356             if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2357             ret = TRUE;
2358         }
2359     }
2360     SERVER_END_REQ;
2361     return ret;
2362 }
2363
2364
2365 /***********************************************************************
2366  *           GetProcessVersion    (KERNEL32.@)
2367  */
2368 DWORD WINAPI GetProcessVersion( DWORD processid )
2369 {
2370     IMAGE_NT_HEADERS *nt;
2371
2372     if (processid && processid != GetCurrentProcessId())
2373     {
2374         FIXME("should use ReadProcessMemory\n");
2375         return 0;
2376     }
2377     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2378         return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2379                 nt->OptionalHeader.MinorSubsystemVersion);
2380     return 0;
2381 }
2382
2383
2384 /***********************************************************************
2385  *              SetProcessWorkingSetSize        [KERNEL32.@]
2386  * Sets the min/max working set sizes for a specified process.
2387  *
2388  * PARAMS
2389  *    hProcess [I] Handle to the process of interest
2390  *    minset   [I] Specifies minimum working set size
2391  *    maxset   [I] Specifies maximum working set size
2392  *
2393  * RETURNS  STD
2394  */
2395 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2396                                      SIZE_T maxset)
2397 {
2398     FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2399     if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2400         /* Trim the working set to zero */
2401         /* Swap the process out of physical RAM */
2402     }
2403     return TRUE;
2404 }
2405
2406 /***********************************************************************
2407  *           GetProcessWorkingSetSize    (KERNEL32.@)
2408  */
2409 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2410                                      PSIZE_T maxset)
2411 {
2412     FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2413     /* 32 MB working set size */
2414     if (minset) *minset = 32*1024*1024;
2415     if (maxset) *maxset = 32*1024*1024;
2416     return TRUE;
2417 }
2418
2419
2420 /***********************************************************************
2421  *           SetProcessShutdownParameters    (KERNEL32.@)
2422  */
2423 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2424 {
2425     FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2426     shutdown_flags = flags;
2427     shutdown_priority = level;
2428     return TRUE;
2429 }
2430
2431
2432 /***********************************************************************
2433  * GetProcessShutdownParameters                 (KERNEL32.@)
2434  *
2435  */
2436 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2437 {
2438     *lpdwLevel = shutdown_priority;
2439     *lpdwFlags = shutdown_flags;
2440     return TRUE;
2441 }
2442
2443
2444 /***********************************************************************
2445  *           GetProcessPriorityBoost    (KERNEL32.@)
2446  */
2447 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2448 {
2449     FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2450     
2451     /* Report that no boost is present.. */
2452     *pDisablePriorityBoost = FALSE;
2453     
2454     return TRUE;
2455 }
2456
2457 /***********************************************************************
2458  *           SetProcessPriorityBoost    (KERNEL32.@)
2459  */
2460 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2461 {
2462     FIXME("(%p,%d): stub\n",hprocess,disableboost);
2463     /* Say we can do it. I doubt the program will notice that we don't. */
2464     return TRUE;
2465 }
2466
2467
2468 /***********************************************************************
2469  *              ReadProcessMemory (KERNEL32.@)
2470  */
2471 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2472                                SIZE_T *bytes_read )
2473 {
2474     NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2475     if (status) SetLastError( RtlNtStatusToDosError(status) );
2476     return !status;
2477 }
2478
2479
2480 /***********************************************************************
2481  *           WriteProcessMemory                 (KERNEL32.@)
2482  */
2483 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2484                                 SIZE_T *bytes_written )
2485 {
2486     NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2487     if (status) SetLastError( RtlNtStatusToDosError(status) );
2488     return !status;
2489 }
2490
2491
2492 /****************************************************************************
2493  *              FlushInstructionCache (KERNEL32.@)
2494  */
2495 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2496 {
2497     if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2498     FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2499     return TRUE;
2500 }
2501
2502
2503 /******************************************************************
2504  *              GetProcessIoCounters (KERNEL32.@)
2505  */
2506 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2507 {
2508     NTSTATUS    status;
2509
2510     status = NtQueryInformationProcess(hProcess, ProcessIoCounters, 
2511                                        ioc, sizeof(*ioc), NULL);
2512     if (status) SetLastError( RtlNtStatusToDosError(status) );
2513     return !status;
2514 }
2515
2516 /***********************************************************************
2517  * ProcessIdToSessionId   (KERNEL32.@)
2518  * This function is available on Terminal Server 4SP4 and Windows 2000
2519  */
2520 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2521 {
2522     /* According to MSDN, if the calling process is not in a terminal
2523      * services environment, then the sessionid returned is zero.
2524      */
2525     *sessionid_ptr = 0;
2526     return TRUE;
2527 }
2528
2529
2530 /***********************************************************************
2531  *              RegisterServiceProcess (KERNEL.491)
2532  *              RegisterServiceProcess (KERNEL32.@)
2533  *
2534  * A service process calls this function to ensure that it continues to run
2535  * even after a user logged off.
2536  */
2537 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2538 {
2539     /* I don't think that Wine needs to do anything in that function */
2540     return 1; /* success */
2541 }
2542
2543
2544 /**************************************************************************
2545  *              SetFileApisToOEM   (KERNEL32.@)
2546  */
2547 VOID WINAPI SetFileApisToOEM(void)
2548 {
2549     oem_file_apis = TRUE;
2550 }
2551
2552
2553 /**************************************************************************
2554  *              SetFileApisToANSI   (KERNEL32.@)
2555  */
2556 VOID WINAPI SetFileApisToANSI(void)
2557 {
2558     oem_file_apis = FALSE;
2559 }
2560
2561
2562 /******************************************************************************
2563  * AreFileApisANSI [KERNEL32.@]  Determines if file functions are using ANSI
2564  *
2565  * RETURNS
2566  *    TRUE:  Set of file functions is using ANSI code page
2567  *    FALSE: Set of file functions is using OEM code page
2568  */
2569 BOOL WINAPI AreFileApisANSI(void)
2570 {
2571     return !oem_file_apis;
2572 }
2573
2574
2575 /***********************************************************************
2576  *           GetTickCount       (KERNEL32.@)
2577  *
2578  * Returns the number of milliseconds, modulo 2^32, since the start
2579  * of the wineserver.
2580  */
2581 DWORD WINAPI GetTickCount(void)
2582 {
2583     struct timeval t;
2584     gettimeofday( &t, NULL );
2585     return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2586 }
2587
2588
2589 /***********************************************************************
2590  *           GetCurrentProcess   (KERNEL32.@)
2591  */
2592 #undef GetCurrentProcess
2593 HANDLE WINAPI GetCurrentProcess(void)
2594 {
2595     return (HANDLE)0xffffffff;
2596 }