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