Add a missing return.
[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, 0, 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 (extra_env && p[0]=='=' && 'A'<=p[1] && p[1]<='Z' && p[2]==':' && p[3]=='=')
1071                 continue; /* skipped */
1072             if (!memcmp( p, "PATH=", 5 ))  /* store PATH as WINEPATH */
1073                 *envptr++ = alloc_env_string( "WINEPATH=", p + 5 );
1074             else if (memcmp( p, "HOME=", 5 ) &&
1075                      memcmp( p, "WINEPATH=", 9 ) &&
1076                      memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
1077         }
1078         *envptr = 0;
1079     }
1080     return envp;
1081 }
1082
1083
1084 /***********************************************************************
1085  *           fork_and_exec
1086  *
1087  * Fork and exec a new Unix binary, checking for errors.
1088  */
1089 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1090                           const WCHAR *env, const char *newdir )
1091 {
1092     int fd[2];
1093     int pid, err;
1094
1095     if (!env) env = GetEnvironmentStringsW();
1096
1097     if (pipe(fd) == -1)
1098     {
1099         FILE_SetDosError();
1100         return -1;
1101     }
1102     fcntl( fd[1], F_SETFD, 1 );  /* set close on exec */
1103     if (!(pid = fork()))  /* child */
1104     {
1105         char **argv = build_argv( cmdline, 0 );
1106         char **envp = build_envp( env, NULL );
1107         close( fd[0] );
1108
1109         /* Reset signals that we previously set to SIG_IGN */
1110         signal( SIGPIPE, SIG_DFL );
1111         signal( SIGCHLD, SIG_DFL );
1112
1113         if (newdir) chdir(newdir);
1114
1115         if (argv && envp) execve( filename, argv, envp );
1116         err = errno;
1117         write( fd[1], &err, sizeof(err) );
1118         _exit(1);
1119     }
1120     close( fd[1] );
1121     if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
1122     {
1123         errno = err;
1124         pid = -1;
1125     }
1126     if (pid == -1) FILE_SetDosError();
1127     close( fd[0] );
1128     return pid;
1129 }
1130
1131
1132 /***********************************************************************
1133  *           create_user_params
1134  */
1135 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1136                                                         const STARTUPINFOW *startup )
1137 {
1138     RTL_USER_PROCESS_PARAMETERS *params;
1139     UNICODE_STRING image_str, cmdline_str, desktop, title;
1140     NTSTATUS status;
1141     WCHAR buffer[MAX_PATH];
1142
1143     if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1144         lstrcpynW( buffer, filename, MAX_PATH );
1145     if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1146         lstrcpynW( buffer, filename, MAX_PATH );
1147     RtlInitUnicodeString( &image_str, buffer );
1148
1149     RtlInitUnicodeString( &cmdline_str, cmdline );
1150     if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1151     if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1152
1153     status = RtlCreateProcessParameters( &params, &image_str, NULL, NULL, &cmdline_str, NULL,
1154                                          startup->lpTitle ? &title : NULL,
1155                                          startup->lpDesktop ? &desktop : NULL,
1156                                          NULL, NULL );
1157     if (status != STATUS_SUCCESS)
1158     {
1159         SetLastError( RtlNtStatusToDosError(status) );
1160         return NULL;
1161     }
1162
1163     params->Environment     = NULL;  /* we pass it through the Unix environment */
1164     params->hStdInput       = startup->hStdInput;
1165     params->hStdOutput      = startup->hStdOutput;
1166     params->hStdError       = startup->hStdError;
1167     params->dwX             = startup->dwX;
1168     params->dwY             = startup->dwY;
1169     params->dwXSize         = startup->dwXSize;
1170     params->dwYSize         = startup->dwYSize;
1171     params->dwXCountChars   = startup->dwXCountChars;
1172     params->dwYCountChars   = startup->dwYCountChars;
1173     params->dwFillAttribute = startup->dwFillAttribute;
1174     params->dwFlags         = startup->dwFlags;
1175     params->wShowWindow     = startup->wShowWindow;
1176     return params;
1177 }
1178
1179
1180 /***********************************************************************
1181  *           create_process
1182  *
1183  * Create a new process. If hFile is a valid handle we have an exe
1184  * file, otherwise it is a Winelib app.
1185  */
1186 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1187                             LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1188                             BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1189                             LPPROCESS_INFORMATION info, LPCSTR unixdir )
1190 {
1191     BOOL ret, success = FALSE;
1192     HANDLE process_info;
1193     RTL_USER_PROCESS_PARAMETERS *params;
1194     WCHAR *extra_env = NULL;
1195     int startfd[2];
1196     int execfd[2];
1197     pid_t pid;
1198     int err;
1199     char dummy = 0;
1200
1201     if (!env)
1202     {
1203         env = GetEnvironmentStringsW();
1204         extra_env = DRIVE_BuildEnv();
1205     }
1206
1207     if (!(params = create_user_params( filename, cmd_line, startup )))
1208     {
1209         if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1210         return FALSE;
1211     }
1212
1213     /* create the synchronization pipes */
1214
1215     if (pipe( startfd ) == -1)
1216     {
1217         FILE_SetDosError();
1218         RtlDestroyProcessParameters( params );
1219         if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1220         return FALSE;
1221     }
1222     if (pipe( execfd ) == -1)
1223     {
1224         FILE_SetDosError();
1225         close( startfd[0] );
1226         close( startfd[1] );
1227         RtlDestroyProcessParameters( params );
1228         if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1229         return FALSE;
1230     }
1231     fcntl( execfd[1], F_SETFD, 1 );  /* set close on exec */
1232
1233     /* create the child process */
1234
1235     if (!(pid = fork()))  /* child */
1236     {
1237         char **argv = build_argv( cmd_line, 1 );
1238         char **envp = build_envp( env, extra_env );
1239
1240         close( startfd[1] );
1241         close( execfd[0] );
1242
1243         /* wait for parent to tell us to start */
1244         if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1245
1246         close( startfd[0] );
1247         /* Reset signals that we previously set to SIG_IGN */
1248         signal( SIGPIPE, SIG_DFL );
1249         signal( SIGCHLD, SIG_DFL );
1250
1251         if (unixdir) chdir(unixdir);
1252
1253         if (argv && envp)
1254         {
1255             /* first, try for a WINELOADER environment variable */
1256             argv[0] = getenv("WINELOADER");
1257             if (argv[0]) execve( argv[0], argv, envp );
1258             /* now use the standard search strategy */
1259             wine_exec_wine_binary( NULL, argv, envp );
1260         }
1261         err = errno;
1262         write( execfd[1], &err, sizeof(err) );
1263         _exit(1);
1264     }
1265
1266     /* this is the parent */
1267
1268     close( startfd[0] );
1269     close( execfd[1] );
1270     if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1271     if (pid == -1)
1272     {
1273         close( startfd[1] );
1274         close( execfd[0] );
1275         FILE_SetDosError();
1276         RtlDestroyProcessParameters( params );
1277         return FALSE;
1278     }
1279
1280     /* create the process on the server side */
1281
1282     SERVER_START_REQ( new_process )
1283     {
1284         req->inherit_all  = inherit;
1285         req->create_flags = flags;
1286         req->unix_pid     = pid;
1287         req->exe_file     = hFile;
1288         if (startup->dwFlags & STARTF_USESTDHANDLES)
1289         {
1290             req->hstdin  = startup->hStdInput;
1291             req->hstdout = startup->hStdOutput;
1292             req->hstderr = startup->hStdError;
1293         }
1294         else
1295         {
1296             req->hstdin  = GetStdHandle( STD_INPUT_HANDLE );
1297             req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1298             req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1299         }
1300
1301         if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1302         {
1303             /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1304             if (is_console_handle(req->hstdin))  req->hstdin  = INVALID_HANDLE_VALUE;
1305             if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1306             if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1307         }
1308         else
1309         {
1310             if (is_console_handle(req->hstdin))  req->hstdin  = console_handle_unmap(req->hstdin);
1311             if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1312             if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1313         }
1314
1315         wine_server_add_data( req, params, params->Size );
1316         ret = !wine_server_call_err( req );
1317         process_info = reply->info;
1318     }
1319     SERVER_END_REQ;
1320
1321     RtlDestroyProcessParameters( params );
1322     if (!ret)
1323     {
1324         close( startfd[1] );
1325         close( execfd[0] );
1326         return FALSE;
1327     }
1328
1329     /* tell child to start and wait for it to exec */
1330
1331     write( startfd[1], &dummy, 1 );
1332     close( startfd[1] );
1333
1334     if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1335     {
1336         errno = err;
1337         FILE_SetDosError();
1338         close( execfd[0] );
1339         CloseHandle( process_info );
1340         return FALSE;
1341     }
1342     close( execfd[0] );
1343
1344     /* wait for the new process info to be ready */
1345
1346     WaitForSingleObject( process_info, INFINITE );
1347     SERVER_START_REQ( get_new_process_info )
1348     {
1349         req->info     = process_info;
1350         req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1351         req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1352         if ((ret = !wine_server_call_err( req )))
1353         {
1354             info->dwProcessId = (DWORD)reply->pid;
1355             info->dwThreadId  = (DWORD)reply->tid;
1356             info->hProcess    = reply->phandle;
1357             info->hThread     = reply->thandle;
1358             success           = reply->success;
1359         }
1360     }
1361     SERVER_END_REQ;
1362
1363     if (ret && !success)  /* new process failed to start */
1364     {
1365         DWORD exitcode;
1366         if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1367         CloseHandle( info->hThread );
1368         CloseHandle( info->hProcess );
1369         ret = FALSE;
1370     }
1371     CloseHandle( process_info );
1372     return ret;
1373 }
1374
1375
1376 /***********************************************************************
1377  *           create_vdm_process
1378  *
1379  * Create a new VDM process for a 16-bit or DOS application.
1380  */
1381 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1382                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1383                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1384                                 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1385 {
1386     static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1387
1388     BOOL ret;
1389     LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1390                                      (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1391
1392     if (!new_cmd_line)
1393     {
1394         SetLastError( ERROR_OUTOFMEMORY );
1395         return FALSE;
1396     }
1397     sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1398     ret = create_process( 0, winevdmW, new_cmd_line, env, psa, tsa, inherit,
1399                           flags, startup, info, unixdir );
1400     HeapFree( GetProcessHeap(), 0, new_cmd_line );
1401     return ret;
1402 }
1403
1404
1405 /***********************************************************************
1406  *           create_cmd_process
1407  *
1408  * Create a new cmd shell process for a .BAT file.
1409  */
1410 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env,
1411                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1412                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1413                                 LPPROCESS_INFORMATION info, LPCWSTR cur_dir )
1414
1415 {
1416     static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1417     static const WCHAR slashcW[] = {' ','/','c',' ',0};
1418     WCHAR comspec[MAX_PATH];
1419     WCHAR *newcmdline;
1420     BOOL ret;
1421
1422     if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1423         return FALSE;
1424     if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1425                                   (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1426         return FALSE;
1427
1428     strcpyW( newcmdline, comspec );
1429     strcatW( newcmdline, slashcW );
1430     strcatW( newcmdline, cmd_line );
1431     ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1432                           flags, env, cur_dir, startup, info );
1433     HeapFree( GetProcessHeap(), 0, newcmdline );
1434     return ret;
1435 }
1436
1437
1438 /*************************************************************************
1439  *               get_file_name
1440  *
1441  * Helper for CreateProcess: retrieve the file name to load from the
1442  * app name and command line. Store the file name in buffer, and
1443  * return a possibly modified command line.
1444  * Also returns a handle to the opened file if it's a Windows binary.
1445  */
1446 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1447                              int buflen, HANDLE *handle )
1448 {
1449     static const WCHAR quotesW[] = {'"','%','s','"',0};
1450
1451     WCHAR *name, *pos, *ret = NULL;
1452     const WCHAR *p;
1453
1454     /* if we have an app name, everything is easy */
1455
1456     if (appname)
1457     {
1458         /* use the unmodified app name as file name */
1459         lstrcpynW( buffer, appname, buflen );
1460         *handle = open_exe_file( buffer );
1461         if (!(ret = cmdline) || !cmdline[0])
1462         {
1463             /* no command-line, create one */
1464             if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1465                 sprintfW( ret, quotesW, appname );
1466         }
1467         return ret;
1468     }
1469
1470     if (!cmdline)
1471     {
1472         SetLastError( ERROR_INVALID_PARAMETER );
1473         return NULL;
1474     }
1475
1476     /* first check for a quoted file name */
1477
1478     if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1479     {
1480         int len = p - cmdline - 1;
1481         /* extract the quoted portion as file name */
1482         if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1483         memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1484         name[len] = 0;
1485
1486         if (find_exe_file( name, buffer, buflen, handle ))
1487             ret = cmdline;  /* no change necessary */
1488         goto done;
1489     }
1490
1491     /* now try the command-line word by word */
1492
1493     if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1494         return NULL;
1495     pos = name;
1496     p = cmdline;
1497
1498     while (*p)
1499     {
1500         do *pos++ = *p++; while (*p && *p != ' ');
1501         *pos = 0;
1502         if (find_exe_file( name, buffer, buflen, handle ))
1503         {
1504             ret = cmdline;
1505             break;
1506         }
1507     }
1508
1509     if (!ret || !strchrW( name, ' ' )) goto done;  /* no change necessary */
1510
1511     /* now build a new command-line with quotes */
1512
1513     if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1514         goto done;
1515     sprintfW( ret, quotesW, name );
1516     strcatW( ret, p );
1517
1518  done:
1519     HeapFree( GetProcessHeap(), 0, name );
1520     return ret;
1521 }
1522
1523
1524 /**********************************************************************
1525  *       CreateProcessA          (KERNEL32.@)
1526  */
1527 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1528                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1529                             DWORD flags, LPVOID env, LPCSTR cur_dir,
1530                             LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1531 {
1532     BOOL ret;
1533     UNICODE_STRING app_nameW, cmd_lineW, cur_dirW, desktopW, titleW;
1534     STARTUPINFOW infoW;
1535
1536     if (app_name) RtlCreateUnicodeStringFromAsciiz( &app_nameW, app_name );
1537     else app_nameW.Buffer = NULL;
1538     if (cmd_line) RtlCreateUnicodeStringFromAsciiz( &cmd_lineW, cmd_line );
1539     else cmd_lineW.Buffer = NULL;
1540     if (cur_dir) RtlCreateUnicodeStringFromAsciiz( &cur_dirW, cur_dir );
1541     else cur_dirW.Buffer = NULL;
1542     if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1543     else desktopW.Buffer = NULL;
1544     if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1545     else titleW.Buffer = NULL;
1546
1547     memcpy( &infoW, startup_info, sizeof(infoW) );
1548     infoW.lpDesktop = desktopW.Buffer;
1549     infoW.lpTitle = titleW.Buffer;
1550
1551     if (startup_info->lpReserved)
1552       FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1553             debugstr_a(startup_info->lpReserved));
1554
1555     ret = CreateProcessW( app_nameW.Buffer,  cmd_lineW.Buffer, process_attr, thread_attr,
1556                           inherit, flags, env, cur_dirW.Buffer, &infoW, info );
1557
1558     RtlFreeUnicodeString( &app_nameW );
1559     RtlFreeUnicodeString( &cmd_lineW );
1560     RtlFreeUnicodeString( &cur_dirW );
1561     RtlFreeUnicodeString( &desktopW );
1562     RtlFreeUnicodeString( &titleW );
1563     return ret;
1564 }
1565
1566
1567 /**********************************************************************
1568  *       CreateProcessW          (KERNEL32.@)
1569  */
1570 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1571                             LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1572                             LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1573                             LPPROCESS_INFORMATION info )
1574 {
1575     BOOL retv = FALSE;
1576     HANDLE hFile = 0;
1577     const char *unixdir = NULL;
1578     DOS_FULL_NAME full_dir;
1579     WCHAR name[MAX_PATH];
1580     WCHAR *tidy_cmdline, *p, *envW = env;
1581
1582     /* Process the AppName and/or CmdLine to get module name and path */
1583
1584     TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1585
1586     if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1587         return FALSE;
1588     if (hFile == INVALID_HANDLE_VALUE) goto done;
1589
1590     /* Warn if unsupported features are used */
1591
1592     if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1593                  CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1594                  CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1595                  PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1596         WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1597
1598     if (cur_dir)
1599     {
1600         if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir )) unixdir = full_dir.long_name;
1601     }
1602     else
1603     {
1604         WCHAR buf[MAX_PATH];
1605         if (GetCurrentDirectoryW(MAX_PATH, buf))
1606         {
1607             if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1608         }
1609     }
1610
1611     if (env && !(flags & CREATE_UNICODE_ENVIRONMENT))  /* convert environment to unicode */
1612     {
1613         char *p = env;
1614         DWORD lenW;
1615
1616         while (*p) p += strlen(p) + 1;
1617         p++;  /* final null */
1618         lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1619         envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1620         MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1621         flags |= CREATE_UNICODE_ENVIRONMENT;
1622     }
1623
1624     info->hThread = info->hProcess = 0;
1625     info->dwProcessId = info->dwThreadId = 0;
1626
1627     /* Determine executable type */
1628
1629     if (!hFile)  /* builtin exe */
1630     {
1631         TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1632         retv = create_process( 0, name, tidy_cmdline, envW, process_attr, thread_attr,
1633                                inherit, flags, startup_info, info, unixdir );
1634         goto done;
1635     }
1636
1637     switch( MODULE_GetBinaryType( hFile ))
1638     {
1639     case BINARY_PE_EXE:
1640         TRACE( "starting %s as Win32 binary\n", debugstr_w(name) );
1641         retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1642                                inherit, flags, startup_info, info, unixdir );
1643         break;
1644     case BINARY_WIN16:
1645     case BINARY_DOS:
1646         TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1647         retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1648                                    inherit, flags, startup_info, info, unixdir );
1649         break;
1650     case BINARY_OS216:
1651         FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1652         SetLastError( ERROR_BAD_EXE_FORMAT );
1653         break;
1654     case BINARY_PE_DLL:
1655         TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1656         SetLastError( ERROR_BAD_EXE_FORMAT );
1657         break;
1658     case BINARY_UNIX_LIB:
1659         TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1660         retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1661                                inherit, flags, startup_info, info, unixdir );
1662         break;
1663     case BINARY_UNKNOWN:
1664         /* check for .com or .bat extension */
1665         if ((p = strrchrW( name, '.' )))
1666         {
1667             if (!strcmpiW( p, comW ))
1668             {
1669                 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1670                 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1671                                            inherit, flags, startup_info, info, unixdir );
1672                 break;
1673             }
1674             if (!strcmpiW( p, batW ))
1675             {
1676                 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1677                 retv = create_cmd_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1678                                            inherit, flags, startup_info, info, cur_dir );
1679                 break;
1680             }
1681         }
1682         /* fall through */
1683     case BINARY_UNIX_EXE:
1684         {
1685             /* unknown file, try as unix executable */
1686             DOS_FULL_NAME full_name;
1687
1688             TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1689
1690             if (DOSFS_GetFullName( name, TRUE, &full_name ))
1691                 retv = (fork_and_exec( full_name.long_name, tidy_cmdline, envW, unixdir ) != -1);
1692         }
1693         break;
1694     }
1695     CloseHandle( hFile );
1696
1697  done:
1698     if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1699     if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1700     return retv;
1701 }
1702
1703
1704 /***********************************************************************
1705  *           wait_input_idle
1706  *
1707  * Wrapper to call WaitForInputIdle USER function
1708  */
1709 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1710
1711 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1712 {
1713     HMODULE mod = GetModuleHandleA( "user32.dll" );
1714     if (mod)
1715     {
1716         WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1717         if (ptr) return ptr( process, timeout );
1718     }
1719     return 0;
1720 }
1721
1722
1723 /***********************************************************************
1724  *           WinExec   (KERNEL32.@)
1725  */
1726 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1727 {
1728     PROCESS_INFORMATION info;
1729     STARTUPINFOA startup;
1730     char *cmdline;
1731     UINT ret;
1732
1733     memset( &startup, 0, sizeof(startup) );
1734     startup.cb = sizeof(startup);
1735     startup.dwFlags = STARTF_USESHOWWINDOW;
1736     startup.wShowWindow = nCmdShow;
1737
1738     /* cmdline needs to be writeable for CreateProcess */
1739     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1740     strcpy( cmdline, lpCmdLine );
1741
1742     if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1743                         0, NULL, NULL, &startup, &info ))
1744     {
1745         /* Give 30 seconds to the app to come up */
1746         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1747             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1748         ret = 33;
1749         /* Close off the handles */
1750         CloseHandle( info.hThread );
1751         CloseHandle( info.hProcess );
1752     }
1753     else if ((ret = GetLastError()) >= 32)
1754     {
1755         FIXME("Strange error set by CreateProcess: %d\n", ret );
1756         ret = 11;
1757     }
1758     HeapFree( GetProcessHeap(), 0, cmdline );
1759     return ret;
1760 }
1761
1762
1763 /**********************************************************************
1764  *          LoadModule    (KERNEL32.@)
1765  */
1766 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1767 {
1768     LOADPARMS32 *params = paramBlock;
1769     PROCESS_INFORMATION info;
1770     STARTUPINFOA startup;
1771     HINSTANCE hInstance;
1772     LPSTR cmdline, p;
1773     char filename[MAX_PATH];
1774     BYTE len;
1775
1776     if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1777
1778     if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1779         !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1780         return (HINSTANCE)GetLastError();
1781
1782     len = (BYTE)params->lpCmdLine[0];
1783     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1784         return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1785
1786     strcpy( cmdline, filename );
1787     p = cmdline + strlen(cmdline);
1788     *p++ = ' ';
1789     memcpy( p, params->lpCmdLine + 1, len );
1790     p[len] = 0;
1791
1792     memset( &startup, 0, sizeof(startup) );
1793     startup.cb = sizeof(startup);
1794     if (params->lpCmdShow)
1795     {
1796         startup.dwFlags = STARTF_USESHOWWINDOW;
1797         startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1798     }
1799
1800     if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1801                         params->lpEnvAddress, NULL, &startup, &info ))
1802     {
1803         /* Give 30 seconds to the app to come up */
1804         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1805             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1806         hInstance = (HINSTANCE)33;
1807         /* Close off the handles */
1808         CloseHandle( info.hThread );
1809         CloseHandle( info.hProcess );
1810     }
1811     else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1812     {
1813         FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1814         hInstance = (HINSTANCE)11;
1815     }
1816
1817     HeapFree( GetProcessHeap(), 0, cmdline );
1818     return hInstance;
1819 }
1820
1821
1822 /******************************************************************************
1823  *           TerminateProcess   (KERNEL32.@)
1824  */
1825 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1826 {
1827     NTSTATUS status = NtTerminateProcess( handle, exit_code );
1828     if (status) SetLastError( RtlNtStatusToDosError(status) );
1829     return !status;
1830 }
1831
1832
1833 /***********************************************************************
1834  *           ExitProcess   (KERNEL32.@)
1835  */
1836 void WINAPI ExitProcess( DWORD status )
1837 {
1838     LdrShutdownProcess();
1839     SERVER_START_REQ( terminate_process )
1840     {
1841         /* send the exit code to the server */
1842         req->handle    = GetCurrentProcess();
1843         req->exit_code = status;
1844         wine_server_call( req );
1845     }
1846     SERVER_END_REQ;
1847     exit( status );
1848 }
1849
1850
1851 /***********************************************************************
1852  * GetExitCodeProcess [KERNEL32.@]
1853  *
1854  * Gets termination status of specified process
1855  *
1856  * RETURNS
1857  *   Success: TRUE
1858  *   Failure: FALSE
1859  */
1860 BOOL WINAPI GetExitCodeProcess(
1861     HANDLE hProcess,    /* [in] handle to the process */
1862     LPDWORD lpExitCode) /* [out] address to receive termination status */
1863 {
1864     BOOL ret;
1865     SERVER_START_REQ( get_process_info )
1866     {
1867         req->handle = hProcess;
1868         ret = !wine_server_call_err( req );
1869         if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1870     }
1871     SERVER_END_REQ;
1872     return ret;
1873 }
1874
1875
1876 /***********************************************************************
1877  *           SetErrorMode   (KERNEL32.@)
1878  */
1879 UINT WINAPI SetErrorMode( UINT mode )
1880 {
1881     UINT old = process_error_mode;
1882     process_error_mode = mode;
1883     return old;
1884 }
1885
1886
1887 /**********************************************************************
1888  * TlsAlloc [KERNEL32.@]  Allocates a TLS index.
1889  *
1890  * Allocates a thread local storage index
1891  *
1892  * RETURNS
1893  *    Success: TLS Index
1894  *    Failure: 0xFFFFFFFF
1895  */
1896 DWORD WINAPI TlsAlloc( void )
1897 {
1898     DWORD index;
1899
1900     RtlAcquirePebLock();
1901     index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
1902     if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
1903     else SetLastError( ERROR_NO_MORE_ITEMS );
1904     RtlReleasePebLock();
1905     return index;
1906 }
1907
1908
1909 /**********************************************************************
1910  * TlsFree [KERNEL32.@]  Releases a TLS index.
1911  *
1912  * Releases a thread local storage index, making it available for reuse
1913  *
1914  * RETURNS
1915  *    Success: TRUE
1916  *    Failure: FALSE
1917  */
1918 BOOL WINAPI TlsFree(
1919     DWORD index) /* [in] TLS Index to free */
1920 {
1921     BOOL ret;
1922
1923     RtlAcquirePebLock();
1924     ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1925     if (ret)
1926     {
1927         RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1928         NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1929     }
1930     else SetLastError( ERROR_INVALID_PARAMETER );
1931     RtlReleasePebLock();
1932     return TRUE;
1933 }
1934
1935
1936 /**********************************************************************
1937  * TlsGetValue [KERNEL32.@]  Gets value in a thread's TLS slot
1938  *
1939  * RETURNS
1940  *    Success: Value stored in calling thread's TLS slot for index
1941  *    Failure: 0 and GetLastError returns NO_ERROR
1942  */
1943 LPVOID WINAPI TlsGetValue(
1944     DWORD index) /* [in] TLS index to retrieve value for */
1945 {
1946     if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1947     {
1948         SetLastError( ERROR_INVALID_PARAMETER );
1949         return NULL;
1950     }
1951     SetLastError( ERROR_SUCCESS );
1952     return NtCurrentTeb()->TlsSlots[index];
1953 }
1954
1955
1956 /**********************************************************************
1957  * TlsSetValue [KERNEL32.@]  Stores a value in the thread's TLS slot.
1958  *
1959  * RETURNS
1960  *    Success: TRUE
1961  *    Failure: FALSE
1962  */
1963 BOOL WINAPI TlsSetValue(
1964     DWORD index,  /* [in] TLS index to set value for */
1965     LPVOID value) /* [in] Value to be stored */
1966 {
1967     if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1968     {
1969         SetLastError( ERROR_INVALID_PARAMETER );
1970         return FALSE;
1971     }
1972     NtCurrentTeb()->TlsSlots[index] = value;
1973     return TRUE;
1974 }
1975
1976
1977 /***********************************************************************
1978  *           GetProcessFlags    (KERNEL32.@)
1979  */
1980 DWORD WINAPI GetProcessFlags( DWORD processid )
1981 {
1982     IMAGE_NT_HEADERS *nt;
1983     DWORD flags = 0;
1984
1985     if (processid && processid != GetCurrentProcessId()) return 0;
1986
1987     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1988     {
1989         if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
1990             flags |= PDB32_CONSOLE_PROC;
1991     }
1992     if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
1993     if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
1994     return flags;
1995 }
1996
1997
1998 /***********************************************************************
1999  *           GetProcessDword    (KERNEL.485)
2000  *           GetProcessDword    (KERNEL32.18)
2001  * 'Of course you cannot directly access Windows internal structures'
2002  */
2003 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2004 {
2005     DWORD               x, y;
2006     STARTUPINFOW        siw;
2007
2008     TRACE("(%ld, %d)\n", dwProcessID, offset );
2009
2010     if (dwProcessID && dwProcessID != GetCurrentProcessId())
2011     {
2012         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2013         return 0;
2014     }
2015
2016     switch ( offset )
2017     {
2018     case GPD_APP_COMPAT_FLAGS:
2019         return GetAppCompatFlags16(0);
2020     case GPD_LOAD_DONE_EVENT:
2021         return 0;
2022     case GPD_HINSTANCE16:
2023         return GetTaskDS16();
2024     case GPD_WINDOWS_VERSION:
2025         return GetExeVersion16();
2026     case GPD_THDB:
2027         return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2028     case GPD_PDB:
2029         return (DWORD)NtCurrentTeb()->Peb;
2030     case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2031         GetStartupInfoW(&siw);
2032         return (DWORD)siw.hStdOutput;
2033     case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2034         GetStartupInfoW(&siw);
2035         return (DWORD)siw.hStdInput;
2036     case GPD_STARTF_SHOWWINDOW:
2037         GetStartupInfoW(&siw);
2038         return siw.wShowWindow;
2039     case GPD_STARTF_SIZE:
2040         GetStartupInfoW(&siw);
2041         x = siw.dwXSize;
2042         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2043         y = siw.dwYSize;
2044         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2045         return MAKELONG( x, y );
2046     case GPD_STARTF_POSITION:
2047         GetStartupInfoW(&siw);
2048         x = siw.dwX;
2049         if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2050         y = siw.dwY;
2051         if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2052         return MAKELONG( x, y );
2053     case GPD_STARTF_FLAGS:
2054         GetStartupInfoW(&siw);
2055         return siw.dwFlags;
2056     case GPD_PARENT:
2057         return 0;
2058     case GPD_FLAGS:
2059         return GetProcessFlags(0);
2060     case GPD_USERDATA:
2061         return process_dword;
2062     default:
2063         ERR("Unknown offset %d\n", offset );
2064         return 0;
2065     }
2066 }
2067
2068 /***********************************************************************
2069  *           SetProcessDword    (KERNEL.484)
2070  * 'Of course you cannot directly access Windows internal structures'
2071  */
2072 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2073 {
2074     TRACE("(%ld, %d)\n", dwProcessID, offset );
2075
2076     if (dwProcessID && dwProcessID != GetCurrentProcessId())
2077     {
2078         ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2079         return;
2080     }
2081
2082     switch ( offset )
2083     {
2084     case GPD_APP_COMPAT_FLAGS:
2085     case GPD_LOAD_DONE_EVENT:
2086     case GPD_HINSTANCE16:
2087     case GPD_WINDOWS_VERSION:
2088     case GPD_THDB:
2089     case GPD_PDB:
2090     case GPD_STARTF_SHELLDATA:
2091     case GPD_STARTF_HOTKEY:
2092     case GPD_STARTF_SHOWWINDOW:
2093     case GPD_STARTF_SIZE:
2094     case GPD_STARTF_POSITION:
2095     case GPD_STARTF_FLAGS:
2096     case GPD_PARENT:
2097     case GPD_FLAGS:
2098         ERR("Not allowed to modify offset %d\n", offset );
2099         break;
2100     case GPD_USERDATA:
2101         process_dword = value;
2102         break;
2103     default:
2104         ERR("Unknown offset %d\n", offset );
2105         break;
2106     }
2107 }
2108
2109
2110 /***********************************************************************
2111  *           ExitProcess   (KERNEL.466)
2112  */
2113 void WINAPI ExitProcess16( WORD status )
2114 {
2115     DWORD count;
2116     ReleaseThunkLock( &count );
2117     ExitProcess( status );
2118 }
2119
2120
2121 /*********************************************************************
2122  *           OpenProcess   (KERNEL32.@)
2123  */
2124 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2125 {
2126     HANDLE ret = 0;
2127     SERVER_START_REQ( open_process )
2128     {
2129         req->pid     = id;
2130         req->access  = access;
2131         req->inherit = inherit;
2132         if (!wine_server_call_err( req )) ret = reply->handle;
2133     }
2134     SERVER_END_REQ;
2135     return ret;
2136 }
2137
2138
2139 /*********************************************************************
2140  *           MapProcessHandle   (KERNEL.483)
2141  */
2142 DWORD WINAPI MapProcessHandle( HANDLE handle )
2143 {
2144     DWORD ret = 0;
2145     SERVER_START_REQ( get_process_info )
2146     {
2147         req->handle = handle;
2148         if (!wine_server_call_err( req )) ret = reply->pid;
2149     }
2150     SERVER_END_REQ;
2151     return ret;
2152 }
2153
2154
2155 /*********************************************************************
2156  *           CloseW32Handle (KERNEL.474)
2157  *           CloseHandle    (KERNEL32.@)
2158  */
2159 BOOL WINAPI CloseHandle( HANDLE handle )
2160 {
2161     NTSTATUS status;
2162
2163     /* stdio handles need special treatment */
2164     if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2165         (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2166         (handle == (HANDLE)STD_ERROR_HANDLE))
2167         handle = GetStdHandle( (DWORD)handle );
2168
2169     if (is_console_handle(handle))
2170         return CloseConsoleHandle(handle);
2171
2172     status = NtClose( handle );
2173     if (status) SetLastError( RtlNtStatusToDosError(status) );
2174     return !status;
2175 }
2176
2177
2178 /*********************************************************************
2179  *           GetHandleInformation   (KERNEL32.@)
2180  */
2181 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2182 {
2183     BOOL ret;
2184     SERVER_START_REQ( set_handle_info )
2185     {
2186         req->handle = handle;
2187         req->flags  = 0;
2188         req->mask   = 0;
2189         req->fd     = -1;
2190         ret = !wine_server_call_err( req );
2191         if (ret && flags) *flags = reply->old_flags;
2192     }
2193     SERVER_END_REQ;
2194     return ret;
2195 }
2196
2197
2198 /*********************************************************************
2199  *           SetHandleInformation   (KERNEL32.@)
2200  */
2201 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2202 {
2203     BOOL ret;
2204     SERVER_START_REQ( set_handle_info )
2205     {
2206         req->handle = handle;
2207         req->flags  = flags;
2208         req->mask   = mask;
2209         req->fd     = -1;
2210         ret = !wine_server_call_err( req );
2211     }
2212     SERVER_END_REQ;
2213     return ret;
2214 }
2215
2216
2217 /*********************************************************************
2218  *           DuplicateHandle   (KERNEL32.@)
2219  */
2220 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2221                              HANDLE dest_process, HANDLE *dest,
2222                              DWORD access, BOOL inherit, DWORD options )
2223 {
2224     NTSTATUS status;
2225
2226     if (is_console_handle(source))
2227     {
2228         /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2229         if (source_process != dest_process ||
2230             source_process != GetCurrentProcess())
2231         {
2232             SetLastError(ERROR_INVALID_PARAMETER);
2233             return FALSE;
2234         }
2235         *dest = DuplicateConsoleHandle( source, access, inherit, options );
2236         return (*dest != INVALID_HANDLE_VALUE);
2237     }
2238     status = NtDuplicateObject( source_process, source, dest_process, dest,
2239                                 access, inherit ? OBJ_INHERIT : 0, options );
2240     if (status) SetLastError( RtlNtStatusToDosError(status) );
2241     return !status;
2242 }
2243
2244
2245 /***********************************************************************
2246  *           ConvertToGlobalHandle   (KERNEL.476)
2247  *           ConvertToGlobalHandle  (KERNEL32.@)
2248  */
2249 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2250 {
2251     HANDLE ret = INVALID_HANDLE_VALUE;
2252     DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2253                      DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2254     return ret;
2255 }
2256
2257
2258 /***********************************************************************
2259  *           SetHandleContext   (KERNEL32.@)
2260  */
2261 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2262 {
2263     FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2264           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2265     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2266     return FALSE;
2267 }
2268
2269
2270 /***********************************************************************
2271  *           GetHandleContext   (KERNEL32.@)
2272  */
2273 DWORD WINAPI GetHandleContext(HANDLE hnd)
2274 {
2275     FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2276           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2277     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2278     return 0;
2279 }
2280
2281
2282 /***********************************************************************
2283  *           CreateSocketHandle   (KERNEL32.@)
2284  */
2285 HANDLE WINAPI CreateSocketHandle(void)
2286 {
2287     FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2288           "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2289     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2290     return INVALID_HANDLE_VALUE;
2291 }
2292
2293
2294 /***********************************************************************
2295  *           SetPriorityClass   (KERNEL32.@)
2296  */
2297 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2298 {
2299     BOOL ret;
2300     SERVER_START_REQ( set_process_info )
2301     {
2302         req->handle   = hprocess;
2303         req->priority = priorityclass;
2304         req->mask     = SET_PROCESS_INFO_PRIORITY;
2305         ret = !wine_server_call_err( req );
2306     }
2307     SERVER_END_REQ;
2308     return ret;
2309 }
2310
2311
2312 /***********************************************************************
2313  *           GetPriorityClass   (KERNEL32.@)
2314  */
2315 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2316 {
2317     DWORD ret = 0;
2318     SERVER_START_REQ( get_process_info )
2319     {
2320         req->handle = hprocess;
2321         if (!wine_server_call_err( req )) ret = reply->priority;
2322     }
2323     SERVER_END_REQ;
2324     return ret;
2325 }
2326
2327
2328 /***********************************************************************
2329  *          SetProcessAffinityMask   (KERNEL32.@)
2330  */
2331 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2332 {
2333     BOOL ret;
2334     SERVER_START_REQ( set_process_info )
2335     {
2336         req->handle   = hProcess;
2337         req->affinity = affmask;
2338         req->mask     = SET_PROCESS_INFO_AFFINITY;
2339         ret = !wine_server_call_err( req );
2340     }
2341     SERVER_END_REQ;
2342     return ret;
2343 }
2344
2345
2346 /**********************************************************************
2347  *          GetProcessAffinityMask    (KERNEL32.@)
2348  */
2349 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2350                                       LPDWORD lpProcessAffinityMask,
2351                                       LPDWORD lpSystemAffinityMask )
2352 {
2353     BOOL ret = FALSE;
2354     SERVER_START_REQ( get_process_info )
2355     {
2356         req->handle = hProcess;
2357         if (!wine_server_call_err( req ))
2358         {
2359             if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2360             if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2361             ret = TRUE;
2362         }
2363     }
2364     SERVER_END_REQ;
2365     return ret;
2366 }
2367
2368
2369 /***********************************************************************
2370  *           GetProcessVersion    (KERNEL32.@)
2371  */
2372 DWORD WINAPI GetProcessVersion( DWORD processid )
2373 {
2374     IMAGE_NT_HEADERS *nt;
2375
2376     if (processid && processid != GetCurrentProcessId())
2377     {
2378         FIXME("should use ReadProcessMemory\n");
2379         return 0;
2380     }
2381     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2382         return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2383                 nt->OptionalHeader.MinorSubsystemVersion);
2384     return 0;
2385 }
2386
2387
2388 /***********************************************************************
2389  *              SetProcessWorkingSetSize        [KERNEL32.@]
2390  * Sets the min/max working set sizes for a specified process.
2391  *
2392  * PARAMS
2393  *    hProcess [I] Handle to the process of interest
2394  *    minset   [I] Specifies minimum working set size
2395  *    maxset   [I] Specifies maximum working set size
2396  *
2397  * RETURNS  STD
2398  */
2399 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2400                                      SIZE_T maxset)
2401 {
2402     FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2403     if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2404         /* Trim the working set to zero */
2405         /* Swap the process out of physical RAM */
2406     }
2407     return TRUE;
2408 }
2409
2410 /***********************************************************************
2411  *           GetProcessWorkingSetSize    (KERNEL32.@)
2412  */
2413 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2414                                      PSIZE_T maxset)
2415 {
2416     FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2417     /* 32 MB working set size */
2418     if (minset) *minset = 32*1024*1024;
2419     if (maxset) *maxset = 32*1024*1024;
2420     return TRUE;
2421 }
2422
2423
2424 /***********************************************************************
2425  *           SetProcessShutdownParameters    (KERNEL32.@)
2426  */
2427 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2428 {
2429     FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2430     shutdown_flags = flags;
2431     shutdown_priority = level;
2432     return TRUE;
2433 }
2434
2435
2436 /***********************************************************************
2437  * GetProcessShutdownParameters                 (KERNEL32.@)
2438  *
2439  */
2440 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2441 {
2442     *lpdwLevel = shutdown_priority;
2443     *lpdwFlags = shutdown_flags;
2444     return TRUE;
2445 }
2446
2447
2448 /***********************************************************************
2449  *           GetProcessPriorityBoost    (KERNEL32.@)
2450  */
2451 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2452 {
2453     FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2454     
2455     /* Report that no boost is present.. */
2456     *pDisablePriorityBoost = FALSE;
2457     
2458     return TRUE;
2459 }
2460
2461 /***********************************************************************
2462  *           SetProcessPriorityBoost    (KERNEL32.@)
2463  */
2464 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2465 {
2466     FIXME("(%p,%d): stub\n",hprocess,disableboost);
2467     /* Say we can do it. I doubt the program will notice that we don't. */
2468     return TRUE;
2469 }
2470
2471
2472 /***********************************************************************
2473  *              ReadProcessMemory (KERNEL32.@)
2474  */
2475 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2476                                SIZE_T *bytes_read )
2477 {
2478     NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2479     if (status) SetLastError( RtlNtStatusToDosError(status) );
2480     return !status;
2481 }
2482
2483
2484 /***********************************************************************
2485  *           WriteProcessMemory                 (KERNEL32.@)
2486  */
2487 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2488                                 SIZE_T *bytes_written )
2489 {
2490     NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2491     if (status) SetLastError( RtlNtStatusToDosError(status) );
2492     return !status;
2493 }
2494
2495
2496 /****************************************************************************
2497  *              FlushInstructionCache (KERNEL32.@)
2498  */
2499 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2500 {
2501     if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2502     FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2503     return TRUE;
2504 }
2505
2506
2507 /******************************************************************
2508  *              GetProcessIoCounters (KERNEL32.@)
2509  */
2510 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2511 {
2512     NTSTATUS    status;
2513
2514     status = NtQueryInformationProcess(hProcess, ProcessIoCounters, 
2515                                        ioc, sizeof(*ioc), NULL);
2516     if (status) SetLastError( RtlNtStatusToDosError(status) );
2517     return !status;
2518 }
2519
2520 /***********************************************************************
2521  * ProcessIdToSessionId   (KERNEL32.@)
2522  * This function is available on Terminal Server 4SP4 and Windows 2000
2523  */
2524 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2525 {
2526     /* According to MSDN, if the calling process is not in a terminal
2527      * services environment, then the sessionid returned is zero.
2528      */
2529     *sessionid_ptr = 0;
2530     return TRUE;
2531 }
2532
2533
2534 /***********************************************************************
2535  *              RegisterServiceProcess (KERNEL.491)
2536  *              RegisterServiceProcess (KERNEL32.@)
2537  *
2538  * A service process calls this function to ensure that it continues to run
2539  * even after a user logged off.
2540  */
2541 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2542 {
2543     /* I don't think that Wine needs to do anything in that function */
2544     return 1; /* success */
2545 }
2546
2547
2548 /**************************************************************************
2549  *              SetFileApisToOEM   (KERNEL32.@)
2550  */
2551 VOID WINAPI SetFileApisToOEM(void)
2552 {
2553     oem_file_apis = TRUE;
2554 }
2555
2556
2557 /**************************************************************************
2558  *              SetFileApisToANSI   (KERNEL32.@)
2559  */
2560 VOID WINAPI SetFileApisToANSI(void)
2561 {
2562     oem_file_apis = FALSE;
2563 }
2564
2565
2566 /******************************************************************************
2567  * AreFileApisANSI [KERNEL32.@]  Determines if file functions are using ANSI
2568  *
2569  * RETURNS
2570  *    TRUE:  Set of file functions is using ANSI code page
2571  *    FALSE: Set of file functions is using OEM code page
2572  */
2573 BOOL WINAPI AreFileApisANSI(void)
2574 {
2575     return !oem_file_apis;
2576 }
2577
2578
2579 /***********************************************************************
2580  *           GetTickCount       (KERNEL32.@)
2581  *
2582  * Returns the number of milliseconds, modulo 2^32, since the start
2583  * of the wineserver.
2584  */
2585 DWORD WINAPI GetTickCount(void)
2586 {
2587     struct timeval t;
2588     gettimeofday( &t, NULL );
2589     return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2590 }
2591
2592
2593 /***********************************************************************
2594  *           GetCurrentProcess   (KERNEL32.@)
2595  */
2596 #undef GetCurrentProcess
2597 HANDLE WINAPI GetCurrentProcess(void)
2598 {
2599     return (HANDLE)0xffffffff;
2600 }