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