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