msdaps: Add support for remoting IAccessor_CreateAccessor.
[wine] / dlls / kernel32 / 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 <signal.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
42 #endif
43 #include <sys/types.h>
44
45 #include "ntstatus.h"
46 #define WIN32_NO_STATUS
47 #include "winternl.h"
48 #include "kernel_private.h"
49 #include "wine/library.h"
50 #include "wine/server.h"
51 #include "wine/unicode.h"
52 #include "wine/debug.h"
53
54 WINE_DEFAULT_DEBUG_CHANNEL(process);
55 WINE_DECLARE_DEBUG_CHANNEL(file);
56 WINE_DECLARE_DEBUG_CHANNEL(relay);
57
58 #ifdef __APPLE__
59 extern char **__wine_get_main_environment(void);
60 #else
61 extern char **__wine_main_environ;
62 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
63 #endif
64
65 typedef struct
66 {
67     LPSTR lpEnvAddress;
68     LPSTR lpCmdLine;
69     LPSTR lpCmdShow;
70     DWORD dwReserved;
71 } LOADPARMS32;
72
73 static UINT process_error_mode;
74
75 static DWORD shutdown_flags = 0;
76 static DWORD shutdown_priority = 0x280;
77 static BOOL is_wow64;
78
79 HMODULE kernel32_handle = 0;
80
81 const WCHAR *DIR_Windows = NULL;
82 const WCHAR *DIR_System = NULL;
83 const WCHAR *DIR_SysWow64 = NULL;
84
85 /* Process flags */
86 #define PDB32_DEBUGGED      0x0001  /* Process is being debugged */
87 #define PDB32_WIN16_PROC    0x0008  /* Win16 process */
88 #define PDB32_DOS_PROC      0x0010  /* Dos process */
89 #define PDB32_CONSOLE_PROC  0x0020  /* Console process */
90 #define PDB32_FILE_APIS_OEM 0x0040  /* File APIs are OEM */
91 #define PDB32_WIN32S_PROC   0x8000  /* Win32s process */
92
93 static const WCHAR comW[] = {'.','c','o','m',0};
94 static const WCHAR batW[] = {'.','b','a','t',0};
95 static const WCHAR cmdW[] = {'.','c','m','d',0};
96 static const WCHAR pifW[] = {'.','p','i','f',0};
97 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
98
99 static void exec_process( LPCWSTR name );
100
101 extern void SHELL_LoadRegistry(void);
102
103
104 /***********************************************************************
105  *           contains_path
106  */
107 static inline int contains_path( LPCWSTR name )
108 {
109     return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
110 }
111
112
113 /***********************************************************************
114  *           is_special_env_var
115  *
116  * Check if an environment variable needs to be handled specially when
117  * passed through the Unix environment (i.e. prefixed with "WINE").
118  */
119 static inline int is_special_env_var( const char *var )
120 {
121     return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
122             !strncmp( var, "PWD=", sizeof("PWD=")-1 ) ||
123             !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
124             !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
125             !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
126 }
127
128
129 /***********************************************************************
130  *           is_path_prefix
131  */
132 static inline unsigned int is_path_prefix( const WCHAR *prefix, const WCHAR *filename )
133 {
134     unsigned int len = strlenW( prefix );
135
136     if (strncmpiW( filename, prefix, len ) || filename[len] != '\\') return 0;
137     while (filename[len] == '\\') len++;
138     return len;
139 }
140
141
142 /***************************************************************************
143  *      get_builtin_path
144  *
145  * Get the path of a builtin module when the native file does not exist.
146  */
147 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename,
148                               UINT size, struct binary_info *binary_info )
149 {
150     WCHAR *file_part;
151     UINT len;
152     void *redir_disabled = 0;
153     unsigned int flags = (sizeof(void*) > sizeof(int) ? BINARY_FLAG_64BIT : 0);
154
155     if (is_wow64 && Wow64DisableWow64FsRedirection( &redir_disabled ))
156         Wow64RevertWow64FsRedirection( redir_disabled );
157
158     if (contains_path( libname ))
159     {
160         if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
161                                   filename, &file_part ) > size * sizeof(WCHAR))
162             return FALSE;  /* too long */
163
164         if ((len = is_path_prefix( DIR_System, filename )))
165         {
166             if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
167         }
168         else if (DIR_SysWow64 && (len = is_path_prefix( DIR_SysWow64, filename )))
169         {
170             flags = 0;
171         }
172         else return FALSE;
173
174         if (filename + len != file_part) return FALSE;
175     }
176     else
177     {
178         len = strlenW( DIR_System );
179         if (strlenW(libname) + len + 2 >= size) return FALSE;  /* too long */
180         memcpy( filename, DIR_System, len * sizeof(WCHAR) );
181         file_part = filename + len;
182         if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
183         strcpyW( file_part, libname );
184         if (is_wow64 && redir_disabled) flags = BINARY_FLAG_64BIT;
185     }
186     if (ext && !strchrW( file_part, '.' ))
187     {
188         if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
189             return FALSE;  /* too long */
190         strcatW( file_part, ext );
191     }
192     binary_info->type = BINARY_UNIX_LIB;
193     binary_info->flags = flags;
194     binary_info->res_start = NULL;
195     binary_info->res_end = NULL;
196     return TRUE;
197 }
198
199
200 /***********************************************************************
201  *           open_builtin_exe_file
202  *
203  * Open an exe file for a builtin exe.
204  */
205 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
206                                     int test_only, int *file_exists )
207 {
208     char exename[MAX_PATH];
209     WCHAR *p;
210     UINT i, len;
211
212     *file_exists = 0;
213     if ((p = strrchrW( name, '/' ))) name = p + 1;
214     if ((p = strrchrW( name, '\\' ))) name = p + 1;
215
216     /* we don't want to depend on the current codepage here */
217     len = strlenW( name ) + 1;
218     if (len >= sizeof(exename)) return NULL;
219     for (i = 0; i < len; i++)
220     {
221         if (name[i] > 127) return NULL;
222         exename[i] = (char)name[i];
223         if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
224     }
225     return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
226 }
227
228
229 /***********************************************************************
230  *           open_exe_file
231  *
232  * Open a specific exe file, taking load order into account.
233  * Returns the file handle or 0 for a builtin exe.
234  */
235 static HANDLE open_exe_file( const WCHAR *name, struct binary_info *binary_info )
236 {
237     HANDLE handle;
238
239     TRACE("looking for %s\n", debugstr_w(name) );
240
241     if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
242                                NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
243     {
244         WCHAR buffer[MAX_PATH];
245         /* file doesn't exist, check for builtin */
246         if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer), binary_info ))
247             handle = 0;
248     }
249     else MODULE_get_binary_info( handle, binary_info );
250
251     return handle;
252 }
253
254
255 /***********************************************************************
256  *           find_exe_file
257  *
258  * Open an exe file, and return the full name and file handle.
259  * Returns FALSE if file could not be found.
260  * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
261  * If file is a builtin exe, returns TRUE and sets handle to 0.
262  */
263 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen,
264                            HANDLE *handle, struct binary_info *binary_info )
265 {
266     static const WCHAR exeW[] = {'.','e','x','e',0};
267     int file_exists;
268
269     TRACE("looking for %s\n", debugstr_w(name) );
270
271     if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ))
272     {
273         if (get_builtin_path( name, exeW, buffer, buflen, binary_info ))
274         {
275             TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
276             open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
277             if (file_exists)
278             {
279                 *handle = 0;
280                 return TRUE;
281             }
282             return FALSE;
283         }
284
285         /* no builtin found, try native without extension in case it is a Unix app */
286
287         if (!SearchPathW( NULL, name, NULL, buflen, buffer, NULL )) return FALSE;
288     }
289
290     TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
291     if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
292                                 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
293     {
294         MODULE_get_binary_info( *handle, binary_info );
295         return TRUE;
296     }
297     return FALSE;
298 }
299
300
301 /***********************************************************************
302  *           build_initial_environment
303  *
304  * Build the Win32 environment from the Unix environment
305  */
306 static BOOL build_initial_environment(void)
307 {
308     SIZE_T size = 1;
309     char **e;
310     WCHAR *p, *endptr;
311     void *ptr;
312     char **env = __wine_get_main_environment();
313
314     /* Compute the total size of the Unix environment */
315     for (e = env; *e; e++)
316     {
317         if (is_special_env_var( *e )) continue;
318         size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
319     }
320     size *= sizeof(WCHAR);
321
322     /* Now allocate the environment */
323     ptr = NULL;
324     if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
325                                 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
326         return FALSE;
327
328     NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
329     endptr = p + size / sizeof(WCHAR);
330
331     /* And fill it with the Unix environment */
332     for (e = env; *e; e++)
333     {
334         char *str = *e;
335
336         /* skip Unix special variables and use the Wine variants instead */
337         if (!strncmp( str, "WINE", 4 ))
338         {
339             if (is_special_env_var( str + 4 )) str += 4;
340             else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue;  /* skip it */
341         }
342         else if (is_special_env_var( str )) continue;  /* skip it */
343
344         MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
345         p += strlenW(p) + 1;
346     }
347     *p = 0;
348     return TRUE;
349 }
350
351
352 /***********************************************************************
353  *           set_registry_variables
354  *
355  * Set environment variables by enumerating the values of a key;
356  * helper for set_registry_environment().
357  * Note that Windows happily truncates the value if it's too big.
358  */
359 static void set_registry_variables( HANDLE hkey, ULONG type )
360 {
361     static const WCHAR pathW[] = {'P','A','T','H'};
362     static const WCHAR sep[] = {';',0};
363     UNICODE_STRING env_name, env_value;
364     NTSTATUS status;
365     DWORD size;
366     int index;
367     char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
368     WCHAR tmpbuf[1024];
369     UNICODE_STRING tmp;
370     KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
371
372     tmp.Buffer = tmpbuf;
373     tmp.MaximumLength = sizeof(tmpbuf);
374
375     for (index = 0; ; index++)
376     {
377         status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
378                                       buffer, sizeof(buffer), &size );
379         if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
380             break;
381         if (info->Type != type)
382             continue;
383         env_name.Buffer = info->Name;
384         env_name.Length = env_name.MaximumLength = info->NameLength;
385         env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
386         env_value.Length = info->DataLength;
387         env_value.MaximumLength = sizeof(buffer) - info->DataOffset;
388         if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
389             env_value.Length -= sizeof(WCHAR);  /* don't count terminating null if any */
390         if (!env_value.Length) continue;
391         if (info->Type == REG_EXPAND_SZ)
392         {
393             status = RtlExpandEnvironmentStrings_U( NULL, &env_value, &tmp, NULL );
394             if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW) continue;
395             RtlCopyUnicodeString( &env_value, &tmp );
396         }
397         /* PATH is magic */
398         if (env_name.Length == sizeof(pathW) &&
399             !memicmpW( env_name.Buffer, pathW, sizeof(pathW)/sizeof(WCHAR) ) &&
400             !RtlQueryEnvironmentVariable_U( NULL, &env_name, &tmp ))
401         {
402             RtlAppendUnicodeToString( &tmp, sep );
403             if (RtlAppendUnicodeStringToString( &tmp, &env_value )) continue;
404             RtlCopyUnicodeString( &env_value, &tmp );
405         }
406         RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
407     }
408 }
409
410
411 /***********************************************************************
412  *           set_registry_environment
413  *
414  * Set the environment variables specified in the registry.
415  *
416  * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
417  * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
418  * on the order in which the variables are processed. But on Windows it
419  * does not really matter since they only use %SystemDrive% and
420  * %SystemRoot% which are predefined. But Wine defines these in the
421  * registry, so we need two passes.
422  */
423 static BOOL set_registry_environment( BOOL volatile_only )
424 {
425     static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
426                                      'S','y','s','t','e','m','\\',
427                                      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
428                                      'C','o','n','t','r','o','l','\\',
429                                      'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
430                                      'E','n','v','i','r','o','n','m','e','n','t',0};
431     static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
432     static const WCHAR volatile_envW[] = {'V','o','l','a','t','i','l','e',' ','E','n','v','i','r','o','n','m','e','n','t',0};
433
434     OBJECT_ATTRIBUTES attr;
435     UNICODE_STRING nameW;
436     HANDLE hkey;
437     BOOL ret = FALSE;
438
439     attr.Length = sizeof(attr);
440     attr.RootDirectory = 0;
441     attr.ObjectName = &nameW;
442     attr.Attributes = 0;
443     attr.SecurityDescriptor = NULL;
444     attr.SecurityQualityOfService = NULL;
445
446     /* first the system environment variables */
447     RtlInitUnicodeString( &nameW, env_keyW );
448     if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
449     {
450         set_registry_variables( hkey, REG_SZ );
451         set_registry_variables( hkey, REG_EXPAND_SZ );
452         NtClose( hkey );
453         ret = TRUE;
454     }
455
456     /* then the ones for the current user */
457     if (RtlOpenCurrentUser( KEY_READ, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
458     RtlInitUnicodeString( &nameW, envW );
459     if (!volatile_only && NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
460     {
461         set_registry_variables( hkey, REG_SZ );
462         set_registry_variables( hkey, REG_EXPAND_SZ );
463         NtClose( hkey );
464     }
465
466     RtlInitUnicodeString( &nameW, volatile_envW );
467     if (NtOpenKey( &hkey, KEY_READ, &attr ) == STATUS_SUCCESS)
468     {
469         set_registry_variables( hkey, REG_SZ );
470         set_registry_variables( hkey, REG_EXPAND_SZ );
471         NtClose( hkey );
472     }
473
474     NtClose( attr.RootDirectory );
475     return ret;
476 }
477
478
479 /***********************************************************************
480  *           get_reg_value
481  */
482 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
483 {
484     char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
485     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
486     DWORD len, size = sizeof(buffer);
487     WCHAR *ret = NULL;
488     UNICODE_STRING nameW;
489
490     RtlInitUnicodeString( &nameW, name );
491     if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
492         return NULL;
493
494     if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
495     len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
496
497     if (info->Type == REG_EXPAND_SZ)
498     {
499         UNICODE_STRING value, expanded;
500
501         value.MaximumLength = len * sizeof(WCHAR);
502         value.Buffer = (WCHAR *)info->Data;
503         if (!value.Buffer[len - 1]) len--;  /* don't count terminating null if any */
504         value.Length = len * sizeof(WCHAR);
505         expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
506         if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
507         if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
508         else RtlFreeUnicodeString( &expanded );
509     }
510     else if (info->Type == REG_SZ)
511     {
512         if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
513         {
514             memcpy( ret, info->Data, len * sizeof(WCHAR) );
515             ret[len] = 0;
516         }
517     }
518     return ret;
519 }
520
521
522 /***********************************************************************
523  *           set_additional_environment
524  *
525  * Set some additional environment variables not specified in the registry.
526  */
527 static void set_additional_environment(void)
528 {
529     static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
530                                          'S','o','f','t','w','a','r','e','\\',
531                                          'M','i','c','r','o','s','o','f','t','\\',
532                                          'W','i','n','d','o','w','s',' ','N','T','\\',
533                                          'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
534                                          'P','r','o','f','i','l','e','L','i','s','t',0};
535     static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
536     static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
537     static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
538     OBJECT_ATTRIBUTES attr;
539     UNICODE_STRING nameW;
540     WCHAR *profile_dir = NULL, *all_users_dir = NULL;
541     HANDLE hkey;
542     DWORD len;
543
544     /* set the ALLUSERSPROFILE variables */
545
546     attr.Length = sizeof(attr);
547     attr.RootDirectory = 0;
548     attr.ObjectName = &nameW;
549     attr.Attributes = 0;
550     attr.SecurityDescriptor = NULL;
551     attr.SecurityQualityOfService = NULL;
552     RtlInitUnicodeString( &nameW, profile_keyW );
553     if (!NtOpenKey( &hkey, KEY_READ, &attr ))
554     {
555         profile_dir = get_reg_value( hkey, profiles_valueW );
556         all_users_dir = get_reg_value( hkey, all_users_valueW );
557         NtClose( hkey );
558     }
559
560     if (profile_dir && all_users_dir)
561     {
562         WCHAR *value, *p;
563
564         len = strlenW(profile_dir) + strlenW(all_users_dir) + 2;
565         value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
566         strcpyW( value, profile_dir );
567         p = value + strlenW(value);
568         if (p > value && p[-1] != '\\') *p++ = '\\';
569         strcpyW( p, all_users_dir );
570         SetEnvironmentVariableW( allusersW, value );
571         HeapFree( GetProcessHeap(), 0, value );
572     }
573
574     HeapFree( GetProcessHeap(), 0, all_users_dir );
575     HeapFree( GetProcessHeap(), 0, profile_dir );
576 }
577
578 /***********************************************************************
579  *              set_library_wargv
580  *
581  * Set the Wine library Unicode argv global variables.
582  */
583 static void set_library_wargv( char **argv )
584 {
585     int argc;
586     char *q;
587     WCHAR *p;
588     WCHAR **wargv;
589     DWORD total = 0;
590
591     for (argc = 0; argv[argc]; argc++)
592         total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
593
594     wargv = RtlAllocateHeap( GetProcessHeap(), 0,
595                              total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
596     p = (WCHAR *)(wargv + argc + 1);
597     for (argc = 0; argv[argc]; argc++)
598     {
599         DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
600         wargv[argc] = p;
601         p += reslen;
602         total -= reslen;
603     }
604     wargv[argc] = NULL;
605
606     /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
607
608     for (argc = 0; wargv[argc]; argc++)
609         total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
610
611     argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
612     q = (char *)(argv + argc + 1);
613     for (argc = 0; wargv[argc]; argc++)
614     {
615         DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
616         argv[argc] = q;
617         q += reslen;
618         total -= reslen;
619     }
620     argv[argc] = NULL;
621
622     __wine_main_argc = argc;
623     __wine_main_argv = argv;
624     __wine_main_wargv = wargv;
625 }
626
627
628 /***********************************************************************
629  *              update_library_argv0
630  *
631  * Update the argv[0] global variable with the binary we have found.
632  */
633 static void update_library_argv0( const WCHAR *argv0 )
634 {
635     DWORD len = strlenW( argv0 );
636
637     if (len > strlenW( __wine_main_wargv[0] ))
638     {
639         __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
640     }
641     strcpyW( __wine_main_wargv[0], argv0 );
642
643     len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
644     if (len > strlen( __wine_main_argv[0] ) + 1)
645     {
646         __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
647     }
648     WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
649 }
650
651
652 /***********************************************************************
653  *           build_command_line
654  *
655  * Build the command line of a process from the argv array.
656  *
657  * Note that it does NOT necessarily include the file name.
658  * Sometimes we don't even have any command line options at all.
659  *
660  * We must quote and escape characters so that the argv array can be rebuilt
661  * from the command line:
662  * - spaces and tabs must be quoted
663  *   'a b'   -> '"a b"'
664  * - quotes must be escaped
665  *   '"'     -> '\"'
666  * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
667  *   resulting in an odd number of '\' followed by a '"'
668  *   '\"'    -> '\\\"'
669  *   '\\"'   -> '\\\\\"'
670  * - '\'s that are not followed by a '"' can be left as is
671  *   'a\b'   == 'a\b'
672  *   'a\\b'  == 'a\\b'
673  */
674 static BOOL build_command_line( WCHAR **argv )
675 {
676     int len;
677     WCHAR **arg;
678     LPWSTR p;
679     RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
680
681     if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
682
683     len = 0;
684     for (arg = argv; *arg; arg++)
685     {
686         int has_space,bcount;
687         WCHAR* a;
688
689         has_space=0;
690         bcount=0;
691         a=*arg;
692         if( !*a ) has_space=1;
693         while (*a!='\0') {
694             if (*a=='\\') {
695                 bcount++;
696             } else {
697                 if (*a==' ' || *a=='\t') {
698                     has_space=1;
699                 } else if (*a=='"') {
700                     /* doubling of '\' preceding a '"',
701                      * plus escaping of said '"'
702                      */
703                     len+=2*bcount+1;
704                 }
705                 bcount=0;
706             }
707             a++;
708         }
709         len+=(a-*arg)+1 /* for the separating space */;
710         if (has_space)
711             len+=2; /* for the quotes */
712     }
713
714     if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
715         return FALSE;
716
717     p = rupp->CommandLine.Buffer;
718     rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
719     rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
720     for (arg = argv; *arg; arg++)
721     {
722         int has_space,has_quote;
723         WCHAR* a;
724
725         /* Check for quotes and spaces in this argument */
726         has_space=has_quote=0;
727         a=*arg;
728         if( !*a ) has_space=1;
729         while (*a!='\0') {
730             if (*a==' ' || *a=='\t') {
731                 has_space=1;
732                 if (has_quote)
733                     break;
734             } else if (*a=='"') {
735                 has_quote=1;
736                 if (has_space)
737                     break;
738             }
739             a++;
740         }
741
742         /* Now transfer it to the command line */
743         if (has_space)
744             *p++='"';
745         if (has_quote) {
746             int bcount;
747             WCHAR* a;
748
749             bcount=0;
750             a=*arg;
751             while (*a!='\0') {
752                 if (*a=='\\') {
753                     *p++=*a;
754                     bcount++;
755                 } else {
756                     if (*a=='"') {
757                         int i;
758
759                         /* Double all the '\\' preceding this '"', plus one */
760                         for (i=0;i<=bcount;i++)
761                             *p++='\\';
762                         *p++='"';
763                     } else {
764                         *p++=*a;
765                     }
766                     bcount=0;
767                 }
768                 a++;
769             }
770         } else {
771             WCHAR* x = *arg;
772             while ((*p=*x++)) p++;
773         }
774         if (has_space)
775             *p++='"';
776         *p++=' ';
777     }
778     if (p > rupp->CommandLine.Buffer)
779         p--;  /* remove last space */
780     *p = '\0';
781
782     return TRUE;
783 }
784
785
786 /***********************************************************************
787  *           init_current_directory
788  *
789  * Initialize the current directory from the Unix cwd or the parent info.
790  */
791 static void init_current_directory( CURDIR *cur_dir )
792 {
793     UNICODE_STRING dir_str;
794     const char *pwd;
795     char *cwd;
796     int size;
797
798     /* if we received a cur dir from the parent, try this first */
799
800     if (cur_dir->DosPath.Length)
801     {
802         if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
803     }
804
805     /* now try to get it from the Unix cwd */
806
807     for (size = 256; ; size *= 2)
808     {
809         if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
810         if (getcwd( cwd, size )) break;
811         HeapFree( GetProcessHeap(), 0, cwd );
812         if (errno == ERANGE) continue;
813         cwd = NULL;
814         break;
815     }
816
817     /* try to use PWD if it is valid, so that we don't resolve symlinks */
818
819     pwd = getenv( "PWD" );
820     if (cwd)
821     {
822         struct stat st1, st2;
823
824         if (!pwd || stat( pwd, &st1 ) == -1 ||
825             (!stat( cwd, &st2 ) && (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)))
826             pwd = cwd;
827     }
828
829     if (pwd)
830     {
831         ANSI_STRING unix_name;
832         UNICODE_STRING nt_name;
833         RtlInitAnsiString( &unix_name, pwd );
834         if (!wine_unix_to_nt_file_name( &unix_name, &nt_name ))
835         {
836             UNICODE_STRING dos_path;
837             /* skip the \??\ prefix, nt_name is 0 terminated */
838             RtlInitUnicodeString( &dos_path, nt_name.Buffer + 4 );
839             RtlSetCurrentDirectory_U( &dos_path );
840             RtlFreeUnicodeString( &nt_name );
841         }
842     }
843
844     if (!cur_dir->DosPath.Length)  /* still not initialized */
845     {
846         MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
847                 "starting in the Windows directory.\n", cwd ? cwd : "" );
848         RtlInitUnicodeString( &dir_str, DIR_Windows );
849         RtlSetCurrentDirectory_U( &dir_str );
850     }
851     HeapFree( GetProcessHeap(), 0, cwd );
852
853 done:
854     if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
855     TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
856 }
857
858
859 /***********************************************************************
860  *           init_windows_dirs
861  *
862  * Initialize the windows and system directories from the environment.
863  */
864 static void init_windows_dirs(void)
865 {
866     extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
867
868     static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
869     static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
870     static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
871     static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
872     static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
873
874     DWORD len;
875     WCHAR *buffer;
876
877     if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
878     {
879         buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
880         GetEnvironmentVariableW( windirW, buffer, len );
881         DIR_Windows = buffer;
882     }
883     else DIR_Windows = default_windirW;
884
885     if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
886     {
887         buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
888         GetEnvironmentVariableW( winsysdirW, buffer, len );
889         DIR_System = buffer;
890     }
891     else
892     {
893         len = strlenW( DIR_Windows );
894         buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
895         memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
896         memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
897         DIR_System = buffer;
898     }
899
900     if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
901         ERR( "directory %s could not be created, error %u\n",
902              debugstr_w(DIR_Windows), GetLastError() );
903     if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
904         ERR( "directory %s could not be created, error %u\n",
905              debugstr_w(DIR_System), GetLastError() );
906
907 #ifndef _WIN64  /* SysWow64 is always defined on 64-bit */
908     if (is_wow64)
909 #endif
910     {
911         len = strlenW( DIR_Windows );
912         buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
913         memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
914         memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
915         DIR_SysWow64 = buffer;
916         if (!CreateDirectoryW( DIR_SysWow64, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
917             ERR( "directory %s could not be created, error %u\n",
918                  debugstr_w(DIR_SysWow64), GetLastError() );
919     }
920
921     TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
922     TRACE_(file)( "SystemDir  = %s\n", debugstr_w(DIR_System) );
923
924     /* set the directories in ntdll too */
925     __wine_init_windows_dir( DIR_Windows, DIR_System );
926 }
927
928
929 /***********************************************************************
930  *           start_wineboot
931  *
932  * Start the wineboot process if necessary. Return the handles to wait on.
933  */
934 static void start_wineboot( HANDLE handles[2] )
935 {
936     static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
937
938     handles[1] = 0;
939     if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
940     {
941         ERR( "failed to create wineboot event, expect trouble\n" );
942         return;
943     }
944     if (GetLastError() != ERROR_ALREADY_EXISTS)  /* we created it */
945     {
946         static const WCHAR wineboot[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',0};
947         static const WCHAR args[] = {' ','-','-','i','n','i','t',0};
948         const DWORD expected_type = (sizeof(void*) > sizeof(int) || is_wow64) ?
949                                      SCS_64BIT_BINARY : SCS_32BIT_BINARY;
950         STARTUPINFOW si;
951         PROCESS_INFORMATION pi;
952         DWORD type;
953         void *redir;
954         WCHAR app[MAX_PATH];
955         WCHAR cmdline[MAX_PATH + (sizeof(wineboot) + sizeof(args)) / sizeof(WCHAR)];
956
957         memset( &si, 0, sizeof(si) );
958         si.cb = sizeof(si);
959         si.dwFlags = STARTF_USESTDHANDLES;
960         si.hStdInput  = 0;
961         si.hStdOutput = 0;
962         si.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
963
964         GetSystemDirectoryW( app, MAX_PATH - sizeof(wineboot)/sizeof(WCHAR) );
965         lstrcatW( app, wineboot );
966
967         Wow64DisableWow64FsRedirection( &redir );
968         if (GetBinaryTypeW( app, &type ) && type != expected_type)
969         {
970             if (type == SCS_64BIT_BINARY)
971                 MESSAGE( "wine: '%s' is a 64-bit prefix, it cannot be used with 32-bit Wine.\n",
972                      wine_get_config_dir() );
973             else
974                 MESSAGE( "wine: '%s' is a 32-bit prefix, it cannot be used with %s Wine.\n",
975                      wine_get_config_dir(), is_wow64 ? "wow64" : "64-bit" );
976             ExitProcess( 1 );
977         }
978
979         strcpyW( cmdline, app );
980         strcatW( cmdline, args );
981         if (CreateProcessW( app, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
982         {
983             TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
984             CloseHandle( pi.hThread );
985             handles[1] = pi.hProcess;
986         }
987         else
988         {
989             ERR( "failed to start wineboot, err %u\n", GetLastError() );
990             CloseHandle( handles[0] );
991             handles[0] = 0;
992         }
993         Wow64RevertWow64FsRedirection( redir );
994     }
995 }
996
997
998 /***********************************************************************
999  *           start_process
1000  *
1001  * Startup routine of a new process. Runs on the new process stack.
1002  */
1003 static DWORD WINAPI start_process( PEB *peb )
1004 {
1005     IMAGE_NT_HEADERS *nt;
1006     LPTHREAD_START_ROUTINE entry;
1007
1008     nt = RtlImageNtHeader( peb->ImageBaseAddress );
1009     entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1010                                      nt->OptionalHeader.AddressOfEntryPoint);
1011
1012     if (!nt->OptionalHeader.AddressOfEntryPoint)
1013     {
1014         ERR( "%s doesn't have an entry point, it cannot be executed\n",
1015              debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
1016         ExitThread( 1 );
1017     }
1018
1019     if (TRACE_ON(relay))
1020         DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1021                  debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1022
1023     SetLastError( 0 );  /* clear error code */
1024     if (peb->BeingDebugged) DbgBreakPoint();
1025     return entry( peb );
1026 }
1027
1028
1029 /***********************************************************************
1030  *           set_process_name
1031  *
1032  * Change the process name in the ps output.
1033  */
1034 static void set_process_name( int argc, char *argv[] )
1035 {
1036 #ifdef HAVE_SETPROCTITLE
1037     setproctitle("-%s", argv[1]);
1038 #endif
1039
1040 #ifdef HAVE_PRCTL
1041     int i, offset;
1042     char *p, *prctl_name = argv[1];
1043     char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
1044
1045 #ifndef PR_SET_NAME
1046 # define PR_SET_NAME 15
1047 #endif
1048
1049     if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
1050     if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
1051
1052     if (prctl( PR_SET_NAME, prctl_name ) != -1)
1053     {
1054         offset = argv[1] - argv[0];
1055         memmove( argv[1] - offset, argv[1], end - argv[1] );
1056         memset( end - offset, 0, offset );
1057         for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
1058         argv[i-1] = NULL;
1059     }
1060     else
1061 #endif  /* HAVE_PRCTL */
1062     {
1063         /* remove argv[0] */
1064         memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1065     }
1066 }
1067
1068
1069 /***********************************************************************
1070  *           __wine_kernel_init
1071  *
1072  * Wine initialisation: load and start the main exe file.
1073  */
1074 void CDECL __wine_kernel_init(void)
1075 {
1076     static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1077     static const WCHAR dotW[] = {'.',0};
1078     static const WCHAR exeW[] = {'.','e','x','e',0};
1079
1080     WCHAR *p, main_exe_name[MAX_PATH+1];
1081     PEB *peb = NtCurrentTeb()->Peb;
1082     RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1083     HANDLE boot_events[2];
1084     BOOL got_environment = TRUE;
1085
1086     /* Initialize everything */
1087
1088     setbuf(stdout,NULL);
1089     setbuf(stderr,NULL);
1090     kernel32_handle = GetModuleHandleW(kernel32W);
1091     IsWow64Process( GetCurrentProcess(), &is_wow64 );
1092
1093     LOCALE_Init();
1094
1095     if (!params->Environment)
1096     {
1097         /* Copy the parent environment */
1098         if (!build_initial_environment()) exit(1);
1099
1100         /* convert old configuration to new format */
1101         convert_old_config();
1102
1103         got_environment = set_registry_environment( FALSE );
1104         set_additional_environment();
1105     }
1106
1107     init_windows_dirs();
1108     init_current_directory( &params->CurrentDirectory );
1109
1110     set_process_name( __wine_main_argc, __wine_main_argv );
1111     set_library_wargv( __wine_main_argv );
1112     boot_events[0] = boot_events[1] = 0;
1113
1114     if (peb->ProcessParameters->ImagePathName.Buffer)
1115     {
1116         strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1117     }
1118     else
1119     {
1120         struct binary_info binary_info;
1121
1122         if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1123             !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH, &binary_info ))
1124         {
1125             MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1126             ExitProcess( GetLastError() );
1127         }
1128         update_library_argv0( main_exe_name );
1129         if (!build_command_line( __wine_main_wargv )) goto error;
1130         start_wineboot( boot_events );
1131     }
1132
1133     /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1134     p = strrchrW( main_exe_name, '.' );
1135     if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1136
1137     TRACE( "starting process name=%s argv[0]=%s\n",
1138            debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1139
1140     RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1141                           MODULE_get_dll_load_path(main_exe_name) );
1142
1143     if (boot_events[0])
1144     {
1145         DWORD timeout = 30000, count = 1;
1146
1147         if (boot_events[1]) count++;
1148         if (!got_environment) timeout = 300000;  /* initial prefix creation can take longer */
1149         if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1150             ERR( "boot event wait timed out\n" );
1151         CloseHandle( boot_events[0] );
1152         if (boot_events[1]) CloseHandle( boot_events[1] );
1153         /* reload environment now that wineboot has run */
1154         set_registry_environment( got_environment );
1155         set_additional_environment();
1156     }
1157
1158     if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1159     {
1160         DWORD_PTR args[1];
1161         WCHAR msgW[1024];
1162         char msg[1024];
1163         DWORD error = GetLastError();
1164
1165         /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1166         if (error == ERROR_BAD_EXE_FORMAT ||
1167             error == ERROR_INVALID_ADDRESS ||
1168             error == ERROR_NOT_ENOUGH_MEMORY)
1169         {
1170             if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1171             /* if we get back here, it failed */
1172         }
1173         else if (error == ERROR_MOD_NOT_FOUND)
1174         {
1175             if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1176             else p = main_exe_name;
1177             if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1178             {
1179                 /* args 1 and 2 are --app-name full_path */
1180                 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1181                          debugstr_w(__wine_main_wargv[3]) );
1182                 ExitProcess( ERROR_BAD_EXE_FORMAT );
1183             }
1184         }
1185         args[0] = (DWORD_PTR)main_exe_name;
1186         FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1187                         NULL, error, 0, msgW, sizeof(msgW)/sizeof(WCHAR), (__ms_va_list *)args );
1188         WideCharToMultiByte( CP_ACP, 0, msgW, -1, msg, sizeof(msg), NULL, NULL );
1189         MESSAGE( "wine: %s", msg );
1190         ExitProcess( error );
1191     }
1192
1193     LdrInitializeThunk( start_process, 0, 0, 0 );
1194
1195  error:
1196     ExitProcess( GetLastError() );
1197 }
1198
1199
1200 /***********************************************************************
1201  *           build_argv
1202  *
1203  * Build an argv array from a command-line.
1204  * 'reserved' is the number of args to reserve before the first one.
1205  */
1206 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1207 {
1208     int argc;
1209     char** argv;
1210     char *arg,*s,*d,*cmdline;
1211     int in_quotes,bcount,len;
1212
1213     len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1214     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1215     WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1216
1217     argc=reserved+1;
1218     bcount=0;
1219     in_quotes=0;
1220     s=cmdline;
1221     while (1) {
1222         if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1223             /* space */
1224             argc++;
1225             /* skip the remaining spaces */
1226             while (*s==' ' || *s=='\t') {
1227                 s++;
1228             }
1229             if (*s=='\0')
1230                 break;
1231             bcount=0;
1232             continue;
1233         } else if (*s=='\\') {
1234             /* '\', count them */
1235             bcount++;
1236         } else if ((*s=='"') && ((bcount & 1)==0)) {
1237             /* unescaped '"' */
1238             in_quotes=!in_quotes;
1239             bcount=0;
1240         } else {
1241             /* a regular character */
1242             bcount=0;
1243         }
1244         s++;
1245     }
1246     if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1247     {
1248         HeapFree( GetProcessHeap(), 0, cmdline );
1249         return NULL;
1250     }
1251
1252     arg = d = s = (char *)(argv + argc);
1253     memcpy( d, cmdline, len );
1254     bcount=0;
1255     in_quotes=0;
1256     argc=reserved;
1257     while (*s) {
1258         if ((*s==' ' || *s=='\t') && !in_quotes) {
1259             /* Close the argument and copy it */
1260             *d=0;
1261             argv[argc++]=arg;
1262
1263             /* skip the remaining spaces */
1264             do {
1265                 s++;
1266             } while (*s==' ' || *s=='\t');
1267
1268             /* Start with a new argument */
1269             arg=d=s;
1270             bcount=0;
1271         } else if (*s=='\\') {
1272             /* '\\' */
1273             *d++=*s++;
1274             bcount++;
1275         } else if (*s=='"') {
1276             /* '"' */
1277             if ((bcount & 1)==0) {
1278                 /* Preceded by an even number of '\', this is half that
1279                  * number of '\', plus a '"' which we discard.
1280                  */
1281                 d-=bcount/2;
1282                 s++;
1283                 in_quotes=!in_quotes;
1284             } else {
1285                 /* Preceded by an odd number of '\', this is half that
1286                  * number of '\' followed by a '"'
1287                  */
1288                 d=d-bcount/2-1;
1289                 *d++='"';
1290                 s++;
1291             }
1292             bcount=0;
1293         } else {
1294             /* a regular character */
1295             *d++=*s++;
1296             bcount=0;
1297         }
1298     }
1299     if (*arg) {
1300         *d='\0';
1301         argv[argc++]=arg;
1302     }
1303     argv[argc]=NULL;
1304
1305     HeapFree( GetProcessHeap(), 0, cmdline );
1306     return argv;
1307 }
1308
1309
1310 /***********************************************************************
1311  *           build_envp
1312  *
1313  * Build the environment of a new child process.
1314  */
1315 static char **build_envp( const WCHAR *envW )
1316 {
1317     static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1318
1319     const WCHAR *end;
1320     char **envp;
1321     char *env, *p;
1322     int count = 1, length;
1323     unsigned int i;
1324
1325     for (end = envW; *end; count++) end += strlenW(end) + 1;
1326     end++;
1327     length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1328     if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1329     WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1330
1331     for (p = env; *p; p += strlen(p) + 1)
1332         if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1333
1334     for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1335     {
1336         if (!(p = getenv(unix_vars[i]))) continue;
1337         length += strlen(unix_vars[i]) + strlen(p) + 2;
1338         count++;
1339     }
1340
1341     if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1342     {
1343         char **envptr = envp;
1344         char *dst = (char *)(envp + count);
1345
1346         /* some variables must not be modified, so we get them directly from the unix env */
1347         for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1348         {
1349             if (!(p = getenv(unix_vars[i]))) continue;
1350             *envptr++ = strcpy( dst, unix_vars[i] );
1351             strcat( dst, "=" );
1352             strcat( dst, p );
1353             dst += strlen(dst) + 1;
1354         }
1355
1356         /* now put the Windows environment strings */
1357         for (p = env; *p; p += strlen(p) + 1)
1358         {
1359             if (*p == '=') continue;  /* skip drive curdirs, this crashes some unix apps */
1360             if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1361             if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1362             if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1363             if (is_special_env_var( p ))  /* prefix it with "WINE" */
1364             {
1365                 *envptr++ = strcpy( dst, "WINE" );
1366                 strcat( dst, p );
1367             }
1368             else
1369             {
1370                 *envptr++ = strcpy( dst, p );
1371             }
1372             dst += strlen(dst) + 1;
1373         }
1374         *envptr = 0;
1375     }
1376     HeapFree( GetProcessHeap(), 0, env );
1377     return envp;
1378 }
1379
1380
1381 /***********************************************************************
1382  *           fork_and_exec
1383  *
1384  * Fork and exec a new Unix binary, checking for errors.
1385  */
1386 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1387                           const char *newdir, DWORD flags, STARTUPINFOW *startup )
1388 {
1389     int fd[2], stdin_fd = -1, stdout_fd = -1;
1390     int pid, err;
1391     char **argv, **envp;
1392
1393     if (!env) env = GetEnvironmentStringsW();
1394
1395 #ifdef HAVE_PIPE2
1396     if (pipe2( fd, O_CLOEXEC ) == -1)
1397 #endif
1398     {
1399         if (pipe(fd) == -1)
1400         {
1401             SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1402             return -1;
1403         }
1404         fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1405         fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1406     }
1407
1408     if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1409     {
1410         HANDLE hstdin, hstdout;
1411
1412         if (startup->dwFlags & STARTF_USESTDHANDLES)
1413         {
1414             hstdin = startup->hStdInput;
1415             hstdout = startup->hStdOutput;
1416         }
1417         else
1418         {
1419             hstdin = GetStdHandle(STD_INPUT_HANDLE);
1420             hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1421         }
1422
1423         if (is_console_handle( hstdin ))
1424             hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1425         if (is_console_handle( hstdout ))
1426             hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1427         wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1428         wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1429     }
1430
1431     argv = build_argv( cmdline, 0 );
1432     envp = build_envp( env );
1433
1434     if (!(pid = fork()))  /* child */
1435     {
1436         close( fd[0] );
1437
1438         if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1439         {
1440             int pid;
1441             if (!(pid = fork()))
1442             {
1443                 int fd = open( "/dev/null", O_RDWR );
1444                 setsid();
1445                 /* close stdin and stdout */
1446                 if (fd != -1)
1447                 {
1448                     dup2( fd, 0 );
1449                     dup2( fd, 1 );
1450                     close( fd );
1451                 }
1452             }
1453             else if (pid != -1) _exit(0);  /* parent */
1454         }
1455         else
1456         {
1457             if (stdin_fd != -1)
1458             {
1459                 dup2( stdin_fd, 0 );
1460                 close( stdin_fd );
1461             }
1462             if (stdout_fd != -1)
1463             {
1464                 dup2( stdout_fd, 1 );
1465                 close( stdout_fd );
1466             }
1467         }
1468
1469         /* Reset signals that we previously set to SIG_IGN */
1470         signal( SIGPIPE, SIG_DFL );
1471         signal( SIGCHLD, SIG_DFL );
1472
1473         if (newdir) chdir(newdir);
1474
1475         if (argv && envp) execve( filename, argv, envp );
1476         err = errno;
1477         write( fd[1], &err, sizeof(err) );
1478         _exit(1);
1479     }
1480     HeapFree( GetProcessHeap(), 0, argv );
1481     HeapFree( GetProcessHeap(), 0, envp );
1482     if (stdin_fd != -1) close( stdin_fd );
1483     if (stdout_fd != -1) close( stdout_fd );
1484     close( fd[1] );
1485     if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
1486     {
1487         errno = err;
1488         pid = -1;
1489     }
1490     if (pid == -1) FILE_SetDosError();
1491     close( fd[0] );
1492     return pid;
1493 }
1494
1495
1496 static inline DWORD append_string( void **ptr, const WCHAR *str )
1497 {
1498     DWORD len = strlenW( str );
1499     memcpy( *ptr, str, len * sizeof(WCHAR) );
1500     *ptr = (WCHAR *)*ptr + len;
1501     return len * sizeof(WCHAR);
1502 }
1503
1504 /***********************************************************************
1505  *           create_startup_info
1506  */
1507 static startup_info_t *create_startup_info( LPCWSTR filename, LPCWSTR cmdline,
1508                                             LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1509                                             const STARTUPINFOW *startup, DWORD *info_size )
1510 {
1511     const RTL_USER_PROCESS_PARAMETERS *cur_params;
1512     startup_info_t *info;
1513     DWORD size;
1514     void *ptr;
1515     UNICODE_STRING newdir;
1516     WCHAR imagepath[MAX_PATH];
1517     HANDLE hstdin, hstdout, hstderr;
1518
1519     if(!GetLongPathNameW( filename, imagepath, MAX_PATH ))
1520         lstrcpynW( imagepath, filename, MAX_PATH );
1521     if(!GetFullPathNameW( imagepath, MAX_PATH, imagepath, NULL ))
1522         lstrcpynW( imagepath, filename, MAX_PATH );
1523
1524     cur_params = NtCurrentTeb()->Peb->ProcessParameters;
1525
1526     newdir.Buffer = NULL;
1527     if (cur_dir)
1528     {
1529         if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1530             cur_dir = newdir.Buffer + 4;  /* skip \??\ prefix */
1531         else
1532             cur_dir = NULL;
1533     }
1534     if (!cur_dir)
1535     {
1536         if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
1537             cur_dir = ((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath.Buffer;
1538         else
1539             cur_dir = cur_params->CurrentDirectory.DosPath.Buffer;
1540     }
1541
1542     size = sizeof(*info);
1543     size += strlenW( cur_dir ) * sizeof(WCHAR);
1544     size += cur_params->DllPath.Length;
1545     size += strlenW( imagepath ) * sizeof(WCHAR);
1546     size += strlenW( cmdline ) * sizeof(WCHAR);
1547     if (startup->lpTitle) size += strlenW( startup->lpTitle ) * sizeof(WCHAR);
1548     if (startup->lpDesktop) size += strlenW( startup->lpDesktop ) * sizeof(WCHAR);
1549     /* FIXME: shellinfo */
1550     if (startup->lpReserved2 && startup->cbReserved2) size += startup->cbReserved2;
1551     size = (size + 1) & ~1;
1552     *info_size = size;
1553
1554     if (!(info = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1555
1556     info->console_flags = cur_params->ConsoleFlags;
1557     if (flags & CREATE_NEW_PROCESS_GROUP) info->console_flags = 1;
1558     if (flags & CREATE_NEW_CONSOLE) info->console = (obj_handle_t)1;  /* FIXME: cf. kernel_main.c */
1559
1560     if (startup->dwFlags & STARTF_USESTDHANDLES)
1561     {
1562         hstdin  = startup->hStdInput;
1563         hstdout = startup->hStdOutput;
1564         hstderr = startup->hStdError;
1565     }
1566     else
1567     {
1568         hstdin  = GetStdHandle( STD_INPUT_HANDLE );
1569         hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1570         hstderr = GetStdHandle( STD_ERROR_HANDLE );
1571     }
1572     info->hstdin  = wine_server_obj_handle( hstdin );
1573     info->hstdout = wine_server_obj_handle( hstdout );
1574     info->hstderr = wine_server_obj_handle( hstderr );
1575     if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1576     {
1577         /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1578         if (is_console_handle(hstdin))  info->hstdin  = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1579         if (is_console_handle(hstdout)) info->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1580         if (is_console_handle(hstderr)) info->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1581     }
1582     else
1583     {
1584         if (is_console_handle(hstdin))  info->hstdin  = console_handle_unmap(hstdin);
1585         if (is_console_handle(hstdout)) info->hstdout = console_handle_unmap(hstdout);
1586         if (is_console_handle(hstderr)) info->hstderr = console_handle_unmap(hstderr);
1587     }
1588
1589     info->x         = startup->dwX;
1590     info->y         = startup->dwY;
1591     info->xsize     = startup->dwXSize;
1592     info->ysize     = startup->dwYSize;
1593     info->xchars    = startup->dwXCountChars;
1594     info->ychars    = startup->dwYCountChars;
1595     info->attribute = startup->dwFillAttribute;
1596     info->flags     = startup->dwFlags;
1597     info->show      = startup->wShowWindow;
1598
1599     ptr = info + 1;
1600     info->curdir_len = append_string( &ptr, cur_dir );
1601     info->dllpath_len = cur_params->DllPath.Length;
1602     memcpy( ptr, cur_params->DllPath.Buffer, cur_params->DllPath.Length );
1603     ptr = (char *)ptr + cur_params->DllPath.Length;
1604     info->imagepath_len = append_string( &ptr, imagepath );
1605     info->cmdline_len = append_string( &ptr, cmdline );
1606     if (startup->lpTitle) info->title_len = append_string( &ptr, startup->lpTitle );
1607     if (startup->lpDesktop) info->desktop_len = append_string( &ptr, startup->lpDesktop );
1608     if (startup->lpReserved2 && startup->cbReserved2)
1609     {
1610         info->runtime_len = startup->cbReserved2;
1611         memcpy( ptr, startup->lpReserved2, startup->cbReserved2 );
1612     }
1613
1614 done:
1615     RtlFreeUnicodeString( &newdir );
1616     return info;
1617 }
1618
1619
1620 /***********************************************************************
1621  *           create_process
1622  *
1623  * Create a new process. If hFile is a valid handle we have an exe
1624  * file, otherwise it is a Winelib app.
1625  */
1626 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1627                             LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1628                             BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1629                             LPPROCESS_INFORMATION info, LPCSTR unixdir,
1630                             const struct binary_info *binary_info, int exec_only )
1631 {
1632     BOOL ret, success = FALSE;
1633     HANDLE process_info;
1634     WCHAR *env_end;
1635     char *winedebug = NULL;
1636     char **argv;
1637     startup_info_t *startup_info;
1638     DWORD startup_info_size;
1639     int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1640     pid_t pid;
1641     int err;
1642
1643     if (sizeof(void *) == sizeof(int) && !is_wow64 && (binary_info->flags & BINARY_FLAG_64BIT))
1644     {
1645         ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename) );
1646         SetLastError( ERROR_BAD_EXE_FORMAT );
1647         return FALSE;
1648     }
1649
1650     RtlAcquirePebLock();
1651
1652     if (!(startup_info = create_startup_info( filename, cmd_line, cur_dir, env, flags, startup,
1653                                               &startup_info_size )))
1654     {
1655         RtlReleasePebLock();
1656         return FALSE;
1657     }
1658     if (!env) env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
1659     env_end = env;
1660     while (*env_end)
1661     {
1662         static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1663         if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1664         {
1665             DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1666             if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1667                 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1668         }
1669         env_end += strlenW(env_end) + 1;
1670     }
1671     env_end++;
1672
1673     /* create the socket for the new process */
1674
1675     if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1676     {
1677         RtlReleasePebLock();
1678         HeapFree( GetProcessHeap(), 0, winedebug );
1679         HeapFree( GetProcessHeap(), 0, startup_info );
1680         SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1681         return FALSE;
1682     }
1683     wine_server_send_fd( socketfd[1] );
1684     close( socketfd[1] );
1685
1686     /* create the process on the server side */
1687
1688     SERVER_START_REQ( new_process )
1689     {
1690         req->inherit_all    = inherit;
1691         req->create_flags   = flags;
1692         req->socket_fd      = socketfd[1];
1693         req->exe_file       = wine_server_obj_handle( hFile );
1694         req->process_access = PROCESS_ALL_ACCESS;
1695         req->process_attr   = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1696         req->thread_access  = THREAD_ALL_ACCESS;
1697         req->thread_attr    = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1698         req->info_size      = startup_info_size;
1699
1700         wine_server_add_data( req, startup_info, startup_info_size );
1701         wine_server_add_data( req, env, (env_end - env) * sizeof(WCHAR) );
1702         if ((ret = !wine_server_call_err( req )))
1703         {
1704             info->dwProcessId = (DWORD)reply->pid;
1705             info->dwThreadId  = (DWORD)reply->tid;
1706             info->hProcess    = wine_server_ptr_handle( reply->phandle );
1707             info->hThread     = wine_server_ptr_handle( reply->thandle );
1708         }
1709         process_info = wine_server_ptr_handle( reply->info );
1710     }
1711     SERVER_END_REQ;
1712
1713     RtlReleasePebLock();
1714     if (!ret)
1715     {
1716         close( socketfd[0] );
1717         HeapFree( GetProcessHeap(), 0, startup_info );
1718         HeapFree( GetProcessHeap(), 0, winedebug );
1719         return FALSE;
1720     }
1721
1722     if (!(flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1723     {
1724         if (startup_info->hstdin)
1725             wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdin),
1726                                       FILE_READ_DATA, &stdin_fd, NULL );
1727         if (startup_info->hstdout)
1728             wine_server_handle_to_fd( wine_server_ptr_handle(startup_info->hstdout),
1729                                       FILE_WRITE_DATA, &stdout_fd, NULL );
1730     }
1731     HeapFree( GetProcessHeap(), 0, startup_info );
1732
1733     /* create the child process */
1734     argv = build_argv( cmd_line, 1 );
1735
1736     if (exec_only || !(pid = fork()))  /* child */
1737     {
1738         char preloader_reserve[64], socket_env[64];
1739
1740         if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1741         {
1742             if (!(pid = fork()))
1743             {
1744                 int fd = open( "/dev/null", O_RDWR );
1745                 setsid();
1746                 /* close stdin and stdout */
1747                 if (fd != -1)
1748                 {
1749                     dup2( fd, 0 );
1750                     dup2( fd, 1 );
1751                     close( fd );
1752                 }
1753             }
1754             else if (pid != -1) _exit(0);  /* parent */
1755         }
1756         else
1757         {
1758             if (stdin_fd != -1) dup2( stdin_fd, 0 );
1759             if (stdout_fd != -1) dup2( stdout_fd, 1 );
1760         }
1761
1762         if (stdin_fd != -1) close( stdin_fd );
1763         if (stdout_fd != -1) close( stdout_fd );
1764
1765         /* Reset signals that we previously set to SIG_IGN */
1766         signal( SIGPIPE, SIG_DFL );
1767         signal( SIGCHLD, SIG_DFL );
1768
1769         sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1770         sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1771                  (unsigned long)binary_info->res_start, (unsigned long)binary_info->res_end );
1772
1773         putenv( preloader_reserve );
1774         putenv( socket_env );
1775         if (winedebug) putenv( winedebug );
1776         if (unixdir) chdir(unixdir);
1777
1778         if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1779         _exit(1);
1780     }
1781
1782     /* this is the parent */
1783
1784     if (stdin_fd != -1) close( stdin_fd );
1785     if (stdout_fd != -1) close( stdout_fd );
1786     close( socketfd[0] );
1787     HeapFree( GetProcessHeap(), 0, argv );
1788     HeapFree( GetProcessHeap(), 0, winedebug );
1789     if (pid == -1)
1790     {
1791         FILE_SetDosError();
1792         goto error;
1793     }
1794
1795     /* wait for the new process info to be ready */
1796
1797     WaitForSingleObject( process_info, INFINITE );
1798     SERVER_START_REQ( get_new_process_info )
1799     {
1800         req->info = wine_server_obj_handle( process_info );
1801         wine_server_call( req );
1802         success = reply->success;
1803         err = reply->exit_code;
1804     }
1805     SERVER_END_REQ;
1806
1807     if (!success)
1808     {
1809         SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1810         goto error;
1811     }
1812     CloseHandle( process_info );
1813     return success;
1814
1815 error:
1816     CloseHandle( process_info );
1817     CloseHandle( info->hProcess );
1818     CloseHandle( info->hThread );
1819     info->hProcess = info->hThread = 0;
1820     info->dwProcessId = info->dwThreadId = 0;
1821     return FALSE;
1822 }
1823
1824
1825 /***********************************************************************
1826  *           create_vdm_process
1827  *
1828  * Create a new VDM process for a 16-bit or DOS application.
1829  */
1830 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1831                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1832                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1833                                 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1834                                 const struct binary_info *binary_info, int exec_only )
1835 {
1836     static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1837
1838     BOOL ret;
1839     LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1840                                      (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1841
1842     if (!new_cmd_line)
1843     {
1844         SetLastError( ERROR_OUTOFMEMORY );
1845         return FALSE;
1846     }
1847     sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1848     ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1849                           flags, startup, info, unixdir, binary_info, exec_only );
1850     HeapFree( GetProcessHeap(), 0, new_cmd_line );
1851     return ret;
1852 }
1853
1854
1855 /***********************************************************************
1856  *           create_cmd_process
1857  *
1858  * Create a new cmd shell process for a .BAT file.
1859  */
1860 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1861                                 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1862                                 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1863                                 LPPROCESS_INFORMATION info )
1864
1865 {
1866     static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1867     static const WCHAR slashcW[] = {' ','/','c',' ',0};
1868     WCHAR comspec[MAX_PATH];
1869     WCHAR *newcmdline;
1870     BOOL ret;
1871
1872     if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1873         return FALSE;
1874     if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1875                                   (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1876         return FALSE;
1877
1878     strcpyW( newcmdline, comspec );
1879     strcatW( newcmdline, slashcW );
1880     strcatW( newcmdline, cmd_line );
1881     ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1882                           flags, env, cur_dir, startup, info );
1883     HeapFree( GetProcessHeap(), 0, newcmdline );
1884     return ret;
1885 }
1886
1887
1888 /*************************************************************************
1889  *               get_file_name
1890  *
1891  * Helper for CreateProcess: retrieve the file name to load from the
1892  * app name and command line. Store the file name in buffer, and
1893  * return a possibly modified command line.
1894  * Also returns a handle to the opened file if it's a Windows binary.
1895  */
1896 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1897                              int buflen, HANDLE *handle, struct binary_info *binary_info )
1898 {
1899     static const WCHAR quotesW[] = {'"','%','s','"',0};
1900
1901     WCHAR *name, *pos, *ret = NULL;
1902     const WCHAR *p;
1903     BOOL got_space;
1904
1905     /* if we have an app name, everything is easy */
1906
1907     if (appname)
1908     {
1909         /* use the unmodified app name as file name */
1910         lstrcpynW( buffer, appname, buflen );
1911         *handle = open_exe_file( buffer, binary_info );
1912         if (!(ret = cmdline) || !cmdline[0])
1913         {
1914             /* no command-line, create one */
1915             if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1916                 sprintfW( ret, quotesW, appname );
1917         }
1918         return ret;
1919     }
1920
1921     /* first check for a quoted file name */
1922
1923     if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1924     {
1925         int len = p - cmdline - 1;
1926         /* extract the quoted portion as file name */
1927         if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1928         memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1929         name[len] = 0;
1930
1931         if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1932             ret = cmdline;  /* no change necessary */
1933         goto done;
1934     }
1935
1936     /* now try the command-line word by word */
1937
1938     if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1939         return NULL;
1940     pos = name;
1941     p = cmdline;
1942     got_space = FALSE;
1943
1944     while (*p)
1945     {
1946         do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1947         *pos = 0;
1948         if (find_exe_file( name, buffer, buflen, handle, binary_info ))
1949         {
1950             ret = cmdline;
1951             break;
1952         }
1953         if (*p) got_space = TRUE;
1954     }
1955
1956     if (ret && got_space)  /* now build a new command-line with quotes */
1957     {
1958         if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1959             goto done;
1960         sprintfW( ret, quotesW, name );
1961         strcatW( ret, p );
1962     }
1963     else if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1964
1965  done:
1966     HeapFree( GetProcessHeap(), 0, name );
1967     return ret;
1968 }
1969
1970
1971 /**********************************************************************
1972  *       CreateProcessA          (KERNEL32.@)
1973  */
1974 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1975                                               LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1976                                               DWORD flags, LPVOID env, LPCSTR cur_dir,
1977                                               LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1978 {
1979     BOOL ret = FALSE;
1980     WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1981     UNICODE_STRING desktopW, titleW;
1982     STARTUPINFOW infoW;
1983
1984     desktopW.Buffer = NULL;
1985     titleW.Buffer = NULL;
1986     if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1987     if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1988     if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1989
1990     if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1991     if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1992
1993     memcpy( &infoW, startup_info, sizeof(infoW) );
1994     infoW.lpDesktop = desktopW.Buffer;
1995     infoW.lpTitle = titleW.Buffer;
1996
1997     if (startup_info->lpReserved)
1998       FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1999             debugstr_a(startup_info->lpReserved));
2000
2001     ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
2002                           inherit, flags, env, cur_dirW, &infoW, info );
2003 done:
2004     HeapFree( GetProcessHeap(), 0, app_nameW );
2005     HeapFree( GetProcessHeap(), 0, cmd_lineW );
2006     HeapFree( GetProcessHeap(), 0, cur_dirW );
2007     RtlFreeUnicodeString( &desktopW );
2008     RtlFreeUnicodeString( &titleW );
2009     return ret;
2010 }
2011
2012
2013 /**********************************************************************
2014  *       CreateProcessW          (KERNEL32.@)
2015  */
2016 BOOL WINAPI DECLSPEC_HOTPATCH CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
2017                                               LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
2018                                               LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
2019                                               LPPROCESS_INFORMATION info )
2020 {
2021     BOOL retv = FALSE;
2022     HANDLE hFile = 0;
2023     char *unixdir = NULL;
2024     WCHAR name[MAX_PATH];
2025     WCHAR *tidy_cmdline, *p, *envW = env;
2026     struct binary_info binary_info;
2027
2028     /* Process the AppName and/or CmdLine to get module name and path */
2029
2030     TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
2031
2032     if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR),
2033                                         &hFile, &binary_info )))
2034         return FALSE;
2035     if (hFile == INVALID_HANDLE_VALUE) goto done;
2036
2037     /* Warn if unsupported features are used */
2038
2039     if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
2040                  CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
2041                  CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
2042                  PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
2043         WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
2044
2045     if (cur_dir)
2046     {
2047         if (!(unixdir = wine_get_unix_file_name( cur_dir )))
2048         {
2049             SetLastError(ERROR_DIRECTORY);
2050             goto done;
2051         }
2052     }
2053     else
2054     {
2055         WCHAR buf[MAX_PATH];
2056         if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
2057     }
2058
2059     if (env && !(flags & CREATE_UNICODE_ENVIRONMENT))  /* convert environment to unicode */
2060     {
2061         char *p = env;
2062         DWORD lenW;
2063
2064         while (*p) p += strlen(p) + 1;
2065         p++;  /* final null */
2066         lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
2067         envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
2068         MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
2069         flags |= CREATE_UNICODE_ENVIRONMENT;
2070     }
2071
2072     info->hThread = info->hProcess = 0;
2073     info->dwProcessId = info->dwThreadId = 0;
2074
2075     if (binary_info.flags & BINARY_FLAG_DLL)
2076     {
2077         TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
2078         SetLastError( ERROR_BAD_EXE_FORMAT );
2079     }
2080     else switch (binary_info.type)
2081     {
2082     case BINARY_PE:
2083         TRACE( "starting %s as Win32 binary (%p-%p)\n",
2084                debugstr_w(name), binary_info.res_start, binary_info.res_end );
2085         retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2086                                inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2087         break;
2088     case BINARY_OS216:
2089     case BINARY_WIN16:
2090     case BINARY_DOS:
2091         TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2092         retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2093                                    inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2094         break;
2095     case BINARY_UNIX_LIB:
2096         TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
2097         retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2098                                inherit, flags, startup_info, info, unixdir, &binary_info, FALSE );
2099         break;
2100     case BINARY_UNKNOWN:
2101         /* check for .com or .bat extension */
2102         if ((p = strrchrW( name, '.' )))
2103         {
2104             if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2105             {
2106                 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2107                 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2108                                            inherit, flags, startup_info, info, unixdir,
2109                                            &binary_info, FALSE );
2110                 break;
2111             }
2112             if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2113             {
2114                 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2115                 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2116                                            inherit, flags, startup_info, info );
2117                 break;
2118             }
2119         }
2120         /* fall through */
2121     case BINARY_UNIX_EXE:
2122         {
2123             /* unknown file, try as unix executable */
2124             char *unix_name;
2125
2126             TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2127
2128             if ((unix_name = wine_get_unix_file_name( name )))
2129             {
2130                 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2131                 HeapFree( GetProcessHeap(), 0, unix_name );
2132             }
2133         }
2134         break;
2135     }
2136     if (hFile) CloseHandle( hFile );
2137
2138  done:
2139     if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2140     if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2141     HeapFree( GetProcessHeap(), 0, unixdir );
2142     if (retv)
2143         TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2144     return retv;
2145 }
2146
2147
2148 /**********************************************************************
2149  *       exec_process
2150  */
2151 static void exec_process( LPCWSTR name )
2152 {
2153     HANDLE hFile;
2154     WCHAR *p;
2155     STARTUPINFOW startup_info;
2156     PROCESS_INFORMATION info;
2157     struct binary_info binary_info;
2158
2159     hFile = open_exe_file( name, &binary_info );
2160     if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2161
2162     memset( &startup_info, 0, sizeof(startup_info) );
2163     startup_info.cb = sizeof(startup_info);
2164
2165     /* Determine executable type */
2166
2167     if (binary_info.flags & BINARY_FLAG_DLL) return;
2168     switch (binary_info.type)
2169     {
2170     case BINARY_PE:
2171         TRACE( "starting %s as Win32 binary (%p-%p)\n",
2172                debugstr_w(name), binary_info.res_start, binary_info.res_end );
2173         create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2174                         FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2175         break;
2176     case BINARY_UNIX_LIB:
2177         TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2178         create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2179                         FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2180         break;
2181     case BINARY_UNKNOWN:
2182         /* check for .com or .pif extension */
2183         if (!(p = strrchrW( name, '.' ))) break;
2184         if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2185         /* fall through */
2186     case BINARY_OS216:
2187     case BINARY_WIN16:
2188     case BINARY_DOS:
2189         TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2190         create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2191                             FALSE, 0, &startup_info, &info, NULL, &binary_info, TRUE );
2192         break;
2193     default:
2194         break;
2195     }
2196     CloseHandle( hFile );
2197 }
2198
2199
2200 /***********************************************************************
2201  *           wait_input_idle
2202  *
2203  * Wrapper to call WaitForInputIdle USER function
2204  */
2205 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2206
2207 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2208 {
2209     HMODULE mod = GetModuleHandleA( "user32.dll" );
2210     if (mod)
2211     {
2212         WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2213         if (ptr) return ptr( process, timeout );
2214     }
2215     return 0;
2216 }
2217
2218
2219 /***********************************************************************
2220  *           WinExec   (KERNEL32.@)
2221  */
2222 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2223 {
2224     PROCESS_INFORMATION info;
2225     STARTUPINFOA startup;
2226     char *cmdline;
2227     UINT ret;
2228
2229     memset( &startup, 0, sizeof(startup) );
2230     startup.cb = sizeof(startup);
2231     startup.dwFlags = STARTF_USESHOWWINDOW;
2232     startup.wShowWindow = nCmdShow;
2233
2234     /* cmdline needs to be writable for CreateProcess */
2235     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2236     strcpy( cmdline, lpCmdLine );
2237
2238     if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2239                         0, NULL, NULL, &startup, &info ))
2240     {
2241         /* Give 30 seconds to the app to come up */
2242         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2243             WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2244         ret = 33;
2245         /* Close off the handles */
2246         CloseHandle( info.hThread );
2247         CloseHandle( info.hProcess );
2248     }
2249     else if ((ret = GetLastError()) >= 32)
2250     {
2251         FIXME("Strange error set by CreateProcess: %d\n", ret );
2252         ret = 11;
2253     }
2254     HeapFree( GetProcessHeap(), 0, cmdline );
2255     return ret;
2256 }
2257
2258
2259 /**********************************************************************
2260  *          LoadModule    (KERNEL32.@)
2261  */
2262 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2263 {
2264     LOADPARMS32 *params = paramBlock;
2265     PROCESS_INFORMATION info;
2266     STARTUPINFOA startup;
2267     HINSTANCE hInstance;
2268     LPSTR cmdline, p;
2269     char filename[MAX_PATH];
2270     BYTE len;
2271
2272     if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2273
2274     if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2275         !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2276         return ULongToHandle(GetLastError());
2277
2278     len = (BYTE)params->lpCmdLine[0];
2279     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2280         return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2281
2282     strcpy( cmdline, filename );
2283     p = cmdline + strlen(cmdline);
2284     *p++ = ' ';
2285     memcpy( p, params->lpCmdLine + 1, len );
2286     p[len] = 0;
2287
2288     memset( &startup, 0, sizeof(startup) );
2289     startup.cb = sizeof(startup);
2290     if (params->lpCmdShow)
2291     {
2292         startup.dwFlags = STARTF_USESHOWWINDOW;
2293         startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2294     }
2295
2296     if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2297                         params->lpEnvAddress, NULL, &startup, &info ))
2298     {
2299         /* Give 30 seconds to the app to come up */
2300         if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2301             WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2302         hInstance = (HINSTANCE)33;
2303         /* Close off the handles */
2304         CloseHandle( info.hThread );
2305         CloseHandle( info.hProcess );
2306     }
2307     else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2308     {
2309         FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2310         hInstance = (HINSTANCE)11;
2311     }
2312
2313     HeapFree( GetProcessHeap(), 0, cmdline );
2314     return hInstance;
2315 }
2316
2317
2318 /******************************************************************************
2319  *           TerminateProcess   (KERNEL32.@)
2320  *
2321  * Terminates a process.
2322  *
2323  * PARAMS
2324  *  handle    [I] Process to terminate.
2325  *  exit_code [I] Exit code.
2326  *
2327  * RETURNS
2328  *  Success: TRUE.
2329  *  Failure: FALSE, check GetLastError().
2330  */
2331 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2332 {
2333     NTSTATUS status = NtTerminateProcess( handle, exit_code );
2334     if (status) SetLastError( RtlNtStatusToDosError(status) );
2335     return !status;
2336 }
2337
2338 /***********************************************************************
2339  *           ExitProcess   (KERNEL32.@)
2340  *
2341  * Exits the current process.
2342  *
2343  * PARAMS
2344  *  status [I] Status code to exit with.
2345  *
2346  * RETURNS
2347  *  Nothing.
2348  */
2349 #ifdef __i386__
2350 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2351                    "pushl %ebp\n\t"
2352                    ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2353                    ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2354                    ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2355                    "pushl 8(%ebp)\n\t"
2356                    "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2357                    "leave\n\t"
2358                    "ret $4" )
2359
2360 void WINAPI process_ExitProcess( DWORD status )
2361 {
2362     LdrShutdownProcess();
2363     NtTerminateProcess(GetCurrentProcess(), status);
2364     exit(status);
2365 }
2366
2367 #else
2368
2369 void WINAPI ExitProcess( DWORD status )
2370 {
2371     LdrShutdownProcess();
2372     NtTerminateProcess(GetCurrentProcess(), status);
2373     exit(status);
2374 }
2375
2376 #endif
2377
2378 /***********************************************************************
2379  * GetExitCodeProcess           [KERNEL32.@]
2380  *
2381  * Gets termination status of specified process.
2382  *
2383  * PARAMS
2384  *   hProcess   [in]  Handle to the process.
2385  *   lpExitCode [out] Address to receive termination status.
2386  *
2387  * RETURNS
2388  *   Success: TRUE
2389  *   Failure: FALSE
2390  */
2391 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2392 {
2393     NTSTATUS status;
2394     PROCESS_BASIC_INFORMATION pbi;
2395
2396     status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2397                                        sizeof(pbi), NULL);
2398     if (status == STATUS_SUCCESS)
2399     {
2400         if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2401         return TRUE;
2402     }
2403     SetLastError( RtlNtStatusToDosError(status) );
2404     return FALSE;
2405 }
2406
2407
2408 /***********************************************************************
2409  *           SetErrorMode   (KERNEL32.@)
2410  */
2411 UINT WINAPI SetErrorMode( UINT mode )
2412 {
2413     UINT old = process_error_mode;
2414     process_error_mode = mode;
2415     return old;
2416 }
2417
2418 /***********************************************************************
2419  *           GetErrorMode   (KERNEL32.@)
2420  */
2421 UINT WINAPI GetErrorMode( void )
2422 {
2423     return process_error_mode;
2424 }
2425
2426 /**********************************************************************
2427  * TlsAlloc             [KERNEL32.@]
2428  *
2429  * Allocates a thread local storage index.
2430  *
2431  * RETURNS
2432  *    Success: TLS index.
2433  *    Failure: 0xFFFFFFFF
2434  */
2435 DWORD WINAPI TlsAlloc( void )
2436 {
2437     DWORD index;
2438     PEB * const peb = NtCurrentTeb()->Peb;
2439
2440     RtlAcquirePebLock();
2441     index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2442     if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2443     else
2444     {
2445         index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2446         if (index != ~0U)
2447         {
2448             if (!NtCurrentTeb()->TlsExpansionSlots &&
2449                 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2450                                          8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2451             {
2452                 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2453                 index = ~0U;
2454                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2455             }
2456             else
2457             {
2458                 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2459                 index += TLS_MINIMUM_AVAILABLE;
2460             }
2461         }
2462         else SetLastError( ERROR_NO_MORE_ITEMS );
2463     }
2464     RtlReleasePebLock();
2465     return index;
2466 }
2467
2468
2469 /**********************************************************************
2470  * TlsFree              [KERNEL32.@]
2471  *
2472  * Releases a thread local storage index, making it available for reuse.
2473  *
2474  * PARAMS
2475  *    index [in] TLS index to free.
2476  *
2477  * RETURNS
2478  *    Success: TRUE
2479  *    Failure: FALSE
2480  */
2481 BOOL WINAPI TlsFree( DWORD index )
2482 {
2483     BOOL ret;
2484
2485     RtlAcquirePebLock();
2486     if (index >= TLS_MINIMUM_AVAILABLE)
2487     {
2488         ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2489         if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2490     }
2491     else
2492     {
2493         ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2494         if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2495     }
2496     if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2497     else SetLastError( ERROR_INVALID_PARAMETER );
2498     RtlReleasePebLock();
2499     return TRUE;
2500 }
2501
2502
2503 /**********************************************************************
2504  * TlsGetValue          [KERNEL32.@]
2505  *
2506  * Gets value in a thread's TLS slot.
2507  *
2508  * PARAMS
2509  *    index [in] TLS index to retrieve value for.
2510  *
2511  * RETURNS
2512  *    Success: Value stored in calling thread's TLS slot for index.
2513  *    Failure: 0 and GetLastError() returns NO_ERROR.
2514  */
2515 LPVOID WINAPI TlsGetValue( DWORD index )
2516 {
2517     LPVOID ret;
2518
2519     if (index < TLS_MINIMUM_AVAILABLE)
2520     {
2521         ret = NtCurrentTeb()->TlsSlots[index];
2522     }
2523     else
2524     {
2525         index -= TLS_MINIMUM_AVAILABLE;
2526         if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2527         {
2528             SetLastError( ERROR_INVALID_PARAMETER );
2529             return NULL;
2530         }
2531         if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2532         else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2533     }
2534     SetLastError( ERROR_SUCCESS );
2535     return ret;
2536 }
2537
2538
2539 /**********************************************************************
2540  * TlsSetValue          [KERNEL32.@]
2541  *
2542  * Stores a value in the thread's TLS slot.
2543  *
2544  * PARAMS
2545  *    index [in] TLS index to set value for.
2546  *    value [in] Value to be stored.
2547  *
2548  * RETURNS
2549  *    Success: TRUE
2550  *    Failure: FALSE
2551  */
2552 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2553 {
2554     if (index < TLS_MINIMUM_AVAILABLE)
2555     {
2556         NtCurrentTeb()->TlsSlots[index] = value;
2557     }
2558     else
2559     {
2560         index -= TLS_MINIMUM_AVAILABLE;
2561         if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2562         {
2563             SetLastError( ERROR_INVALID_PARAMETER );
2564             return FALSE;
2565         }
2566         if (!NtCurrentTeb()->TlsExpansionSlots &&
2567             !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2568                          8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2569         {
2570             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2571             return FALSE;
2572         }
2573         NtCurrentTeb()->TlsExpansionSlots[index] = value;
2574     }
2575     return TRUE;
2576 }
2577
2578
2579 /***********************************************************************
2580  *           GetProcessFlags    (KERNEL32.@)
2581  */
2582 DWORD WINAPI GetProcessFlags( DWORD processid )
2583 {
2584     IMAGE_NT_HEADERS *nt;
2585     DWORD flags = 0;
2586
2587     if (processid && processid != GetCurrentProcessId()) return 0;
2588
2589     if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2590     {
2591         if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2592             flags |= PDB32_CONSOLE_PROC;
2593     }
2594     if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2595     if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2596     return flags;
2597 }
2598
2599
2600 /***********************************************************************
2601  *           GetProcessDword    (KERNEL32.18)
2602  */
2603 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2604 {
2605     FIXME( "(%d, %d): not supported\n", dwProcessID, offset );
2606     return 0;
2607 }
2608
2609
2610 /*********************************************************************
2611  *           OpenProcess   (KERNEL32.@)
2612  *
2613  * Opens a handle to a process.
2614  *
2615  * PARAMS
2616  *  access  [I] Desired access rights assigned to the returned handle.
2617  *  inherit [I] Determines whether or not child processes will inherit the handle.
2618  *  id      [I] Process identifier of the process to get a handle to.
2619  *
2620  * RETURNS
2621  *  Success: Valid handle to the specified process.
2622  *  Failure: NULL, check GetLastError().
2623  */
2624 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2625 {
2626     NTSTATUS            status;
2627     HANDLE              handle;
2628     OBJECT_ATTRIBUTES   attr;
2629     CLIENT_ID           cid;
2630
2631     cid.UniqueProcess = ULongToHandle(id);
2632     cid.UniqueThread = 0; /* FIXME ? */
2633
2634     attr.Length = sizeof(OBJECT_ATTRIBUTES);
2635     attr.RootDirectory = NULL;
2636     attr.Attributes = inherit ? OBJ_INHERIT : 0;
2637     attr.SecurityDescriptor = NULL;
2638     attr.SecurityQualityOfService = NULL;
2639     attr.ObjectName = NULL;
2640
2641     if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2642
2643     status = NtOpenProcess(&handle, access, &attr, &cid);
2644     if (status != STATUS_SUCCESS)
2645     {
2646         SetLastError( RtlNtStatusToDosError(status) );
2647         return NULL;
2648     }
2649     return handle;
2650 }
2651
2652
2653 /*********************************************************************
2654  *           GetProcessId       (KERNEL32.@)
2655  *
2656  * Gets the a unique identifier of a process.
2657  *
2658  * PARAMS
2659  *  hProcess [I] Handle to the process.
2660  *
2661  * RETURNS
2662  *  Success: TRUE.
2663  *  Failure: FALSE, check GetLastError().
2664  *
2665  * NOTES
2666  *
2667  * The identifier is unique only on the machine and only until the process
2668  * exits (including system shutdown).
2669  */
2670 DWORD WINAPI GetProcessId( HANDLE hProcess )
2671 {
2672     NTSTATUS status;
2673     PROCESS_BASIC_INFORMATION pbi;
2674
2675     status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2676                                        sizeof(pbi), NULL);
2677     if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2678     SetLastError( RtlNtStatusToDosError(status) );
2679     return 0;
2680 }
2681
2682
2683 /*********************************************************************
2684  *           CloseHandle    (KERNEL32.@)
2685  *
2686  * Closes a handle.
2687  *
2688  * PARAMS
2689  *  handle [I] Handle to close.
2690  *
2691  * RETURNS
2692  *  Success: TRUE.
2693  *  Failure: FALSE, check GetLastError().
2694  */
2695 BOOL WINAPI CloseHandle( HANDLE handle )
2696 {
2697     NTSTATUS status;
2698
2699     /* stdio handles need special treatment */
2700     if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2701         (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2702         (handle == (HANDLE)STD_ERROR_HANDLE))
2703         handle = GetStdHandle( HandleToULong(handle) );
2704
2705     if (is_console_handle(handle))
2706         return CloseConsoleHandle(handle);
2707
2708     status = NtClose( handle );
2709     if (status) SetLastError( RtlNtStatusToDosError(status) );
2710     return !status;
2711 }
2712
2713
2714 /*********************************************************************
2715  *           GetHandleInformation   (KERNEL32.@)
2716  */
2717 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2718 {
2719     OBJECT_DATA_INFORMATION info;
2720     NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2721
2722     if (status) SetLastError( RtlNtStatusToDosError(status) );
2723     else if (flags)
2724     {
2725         *flags = 0;
2726         if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2727         if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2728     }
2729     return !status;
2730 }
2731
2732
2733 /*********************************************************************
2734  *           SetHandleInformation   (KERNEL32.@)
2735  */
2736 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2737 {
2738     OBJECT_DATA_INFORMATION info;
2739     NTSTATUS status;
2740
2741     /* if not setting both fields, retrieve current value first */
2742     if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2743         (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2744     {
2745         if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2746         {
2747             SetLastError( RtlNtStatusToDosError(status) );
2748             return FALSE;
2749         }
2750     }
2751     if (mask & HANDLE_FLAG_INHERIT)
2752         info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2753     if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2754         info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2755
2756     status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2757     if (status) SetLastError( RtlNtStatusToDosError(status) );
2758     return !status;
2759 }
2760
2761
2762 /*********************************************************************
2763  *           DuplicateHandle   (KERNEL32.@)
2764  */
2765 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2766                              HANDLE dest_process, HANDLE *dest,
2767                              DWORD access, BOOL inherit, DWORD options )
2768 {
2769     NTSTATUS status;
2770
2771     if (is_console_handle(source))
2772     {
2773         /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2774         if (source_process != dest_process ||
2775             source_process != GetCurrentProcess())
2776         {
2777             SetLastError(ERROR_INVALID_PARAMETER);
2778             return FALSE;
2779         }
2780         *dest = DuplicateConsoleHandle( source, access, inherit, options );
2781         return (*dest != INVALID_HANDLE_VALUE);
2782     }
2783     status = NtDuplicateObject( source_process, source, dest_process, dest,
2784                                 access, inherit ? OBJ_INHERIT : 0, options );
2785     if (status) SetLastError( RtlNtStatusToDosError(status) );
2786     return !status;
2787 }
2788
2789
2790 /***********************************************************************
2791  *           ConvertToGlobalHandle  (KERNEL32.@)
2792  */
2793 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2794 {
2795     HANDLE ret = INVALID_HANDLE_VALUE;
2796     DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2797                      DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2798     return ret;
2799 }
2800
2801
2802 /***********************************************************************
2803  *           SetHandleContext   (KERNEL32.@)
2804  */
2805 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2806 {
2807     FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2808           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2809     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2810     return FALSE;
2811 }
2812
2813
2814 /***********************************************************************
2815  *           GetHandleContext   (KERNEL32.@)
2816  */
2817 DWORD WINAPI GetHandleContext(HANDLE hnd)
2818 {
2819     FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2820           "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2821     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2822     return 0;
2823 }
2824
2825
2826 /***********************************************************************
2827  *           CreateSocketHandle   (KERNEL32.@)
2828  */
2829 HANDLE WINAPI CreateSocketHandle(void)
2830 {
2831     FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2832           "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2833     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2834     return INVALID_HANDLE_VALUE;
2835 }
2836
2837
2838 /***********************************************************************
2839  *           SetPriorityClass   (KERNEL32.@)
2840  */
2841 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2842 {
2843     NTSTATUS                    status;
2844     PROCESS_PRIORITY_CLASS      ppc;
2845
2846     ppc.Foreground = FALSE;
2847     switch (priorityclass)
2848     {
2849     case IDLE_PRIORITY_CLASS:
2850         ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2851     case BELOW_NORMAL_PRIORITY_CLASS:
2852         ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2853     case NORMAL_PRIORITY_CLASS:
2854         ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2855     case ABOVE_NORMAL_PRIORITY_CLASS:
2856         ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2857     case HIGH_PRIORITY_CLASS:
2858         ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2859     case REALTIME_PRIORITY_CLASS:
2860         ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2861     default:
2862         SetLastError(ERROR_INVALID_PARAMETER);
2863         return FALSE;
2864     }
2865
2866     status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2867                                      &ppc, sizeof(ppc));
2868
2869     if (status != STATUS_SUCCESS)
2870     {
2871         SetLastError( RtlNtStatusToDosError(status) );
2872         return FALSE;
2873     }
2874     return TRUE;
2875 }
2876
2877
2878 /***********************************************************************
2879  *           GetPriorityClass   (KERNEL32.@)
2880  */
2881 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2882 {
2883     NTSTATUS status;
2884     PROCESS_BASIC_INFORMATION pbi;
2885
2886     status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2887                                        sizeof(pbi), NULL);
2888     if (status != STATUS_SUCCESS)
2889     {
2890         SetLastError( RtlNtStatusToDosError(status) );
2891         return 0;
2892     }
2893     switch (pbi.BasePriority)
2894     {
2895     case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2896     case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2897     case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2898     case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2899     case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2900     case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2901     }
2902     SetLastError( ERROR_INVALID_PARAMETER );
2903     return 0;
2904 }
2905
2906
2907 /***********************************************************************
2908  *          SetProcessAffinityMask   (KERNEL32.@)
2909  */
2910 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2911 {
2912     NTSTATUS status;
2913
2914     status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2915                                      &affmask, sizeof(DWORD_PTR));
2916     if (status)
2917     {
2918         SetLastError( RtlNtStatusToDosError(status) );
2919         return FALSE;
2920     }
2921     return TRUE;
2922 }
2923
2924
2925 /**********************************************************************
2926  *          GetProcessAffinityMask    (KERNEL32.@)
2927  */
2928 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2929                                     PDWORD_PTR lpProcessAffinityMask,
2930                                     PDWORD_PTR lpSystemAffinityMask )
2931 {
2932     PROCESS_BASIC_INFORMATION   pbi;
2933     NTSTATUS                    status;
2934
2935     status = NtQueryInformationProcess(hProcess,
2936                                        ProcessBasicInformation,
2937                                        &pbi, sizeof(pbi), NULL);
2938     if (status)
2939     {
2940         SetLastError( RtlNtStatusToDosError(status) );
2941         return FALSE;
2942     }
2943     if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2944     if (lpSystemAffinityMask)  *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2945     return TRUE;
2946 }
2947
2948
2949 /***********************************************************************
2950  *           GetProcessVersion    (KERNEL32.@)
2951  */
2952 DWORD WINAPI GetProcessVersion( DWORD pid )
2953 {
2954     HANDLE process;
2955     NTSTATUS status;
2956     PROCESS_BASIC_INFORMATION pbi;
2957     SIZE_T count;
2958     PEB peb;
2959     IMAGE_DOS_HEADER dos;
2960     IMAGE_NT_HEADERS nt;
2961     DWORD ver = 0;
2962
2963     if (!pid || pid == GetCurrentProcessId())
2964     {
2965         IMAGE_NT_HEADERS *nt;
2966
2967         if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2968             return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2969                     nt->OptionalHeader.MinorSubsystemVersion);
2970         return 0;
2971     }
2972
2973     process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2974     if (!process) return 0;
2975
2976     status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2977     if (status) goto err;
2978
2979     status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2980     if (status || count != sizeof(peb)) goto err;
2981
2982     memset(&dos, 0, sizeof(dos));
2983     status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2984     if (status || count != sizeof(dos)) goto err;
2985     if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2986
2987     memset(&nt, 0, sizeof(nt));
2988     status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2989     if (status || count != sizeof(nt)) goto err;
2990     if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2991
2992     ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2993
2994 err:
2995     CloseHandle(process);
2996
2997     if (status != STATUS_SUCCESS)
2998         SetLastError(RtlNtStatusToDosError(status));
2999
3000     return ver;
3001 }
3002
3003
3004 /***********************************************************************
3005  *              SetProcessWorkingSetSize        [KERNEL32.@]
3006  * Sets the min/max working set sizes for a specified process.
3007  *
3008  * PARAMS
3009  *    hProcess [I] Handle to the process of interest
3010  *    minset   [I] Specifies minimum working set size
3011  *    maxset   [I] Specifies maximum working set size
3012  *
3013  * RETURNS
3014  *  Success: TRUE
3015  *  Failure: FALSE
3016  */
3017 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3018                                      SIZE_T maxset)
3019 {
3020     WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3021     if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3022         /* Trim the working set to zero */
3023         /* Swap the process out of physical RAM */
3024     }
3025     return TRUE;
3026 }
3027
3028 /***********************************************************************
3029  *           GetProcessWorkingSetSize    (KERNEL32.@)
3030  */
3031 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3032                                      PSIZE_T maxset)
3033 {
3034     FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3035     /* 32 MB working set size */
3036     if (minset) *minset = 32*1024*1024;
3037     if (maxset) *maxset = 32*1024*1024;
3038     return TRUE;
3039 }
3040
3041
3042 /***********************************************************************
3043  *           SetProcessShutdownParameters    (KERNEL32.@)
3044  */
3045 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3046 {
3047     FIXME("(%08x, %08x): partial stub.\n", level, flags);
3048     shutdown_flags = flags;
3049     shutdown_priority = level;
3050     return TRUE;
3051 }
3052
3053
3054 /***********************************************************************
3055  * GetProcessShutdownParameters                 (KERNEL32.@)
3056  *
3057  */
3058 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3059 {
3060     *lpdwLevel = shutdown_priority;
3061     *lpdwFlags = shutdown_flags;
3062     return TRUE;
3063 }
3064
3065
3066 /***********************************************************************
3067  *           GetProcessPriorityBoost    (KERNEL32.@)
3068  */
3069 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3070 {
3071     FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3072     
3073     /* Report that no boost is present.. */
3074     *pDisablePriorityBoost = FALSE;
3075     
3076     return TRUE;
3077 }
3078
3079 /***********************************************************************
3080  *           SetProcessPriorityBoost    (KERNEL32.@)
3081  */
3082 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3083 {
3084     FIXME("(%p,%d): stub\n",hprocess,disableboost);
3085     /* Say we can do it. I doubt the program will notice that we don't. */
3086     return TRUE;
3087 }
3088
3089
3090 /***********************************************************************
3091  *              ReadProcessMemory (KERNEL32.@)
3092  */
3093 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3094                                SIZE_T *bytes_read )
3095 {
3096     NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3097     if (status) SetLastError( RtlNtStatusToDosError(status) );
3098     return !status;
3099 }
3100
3101
3102 /***********************************************************************
3103  *           WriteProcessMemory                 (KERNEL32.@)
3104  */
3105 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3106                                 SIZE_T *bytes_written )
3107 {
3108     NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3109     if (status) SetLastError( RtlNtStatusToDosError(status) );
3110     return !status;
3111 }
3112
3113
3114 /****************************************************************************
3115  *              FlushInstructionCache (KERNEL32.@)
3116  */
3117 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3118 {
3119     NTSTATUS status;
3120     status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3121     if (status) SetLastError( RtlNtStatusToDosError(status) );
3122     return !status;
3123 }
3124
3125
3126 /******************************************************************
3127  *              GetProcessIoCounters (KERNEL32.@)
3128  */
3129 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3130 {
3131     NTSTATUS    status;
3132
3133     status = NtQueryInformationProcess(hProcess, ProcessIoCounters, 
3134                                        ioc, sizeof(*ioc), NULL);
3135     if (status) SetLastError( RtlNtStatusToDosError(status) );
3136     return !status;
3137 }
3138
3139 /******************************************************************
3140  *              GetProcessHandleCount (KERNEL32.@)
3141  */
3142 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3143 {
3144     NTSTATUS status;
3145
3146     status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3147                                        cnt, sizeof(*cnt), NULL);
3148     if (status) SetLastError( RtlNtStatusToDosError(status) );
3149     return !status;
3150 }
3151
3152 /******************************************************************
3153  *              QueryFullProcessImageNameA (KERNEL32.@)
3154  */
3155 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3156 {
3157     BOOL retval;
3158     DWORD pdwSizeW = *pdwSize;
3159     LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3160
3161     retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3162
3163     if(retval)
3164         retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3165                                lpExeName, *pdwSize, NULL, NULL));
3166     if(retval)
3167         *pdwSize = strlen(lpExeName);
3168
3169     HeapFree(GetProcessHeap(), 0, lpExeNameW);
3170     return retval;
3171 }
3172
3173 /******************************************************************
3174  *              QueryFullProcessImageNameW (KERNEL32.@)
3175  */
3176 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3177 {
3178     BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)];  /* this buffer should be enough */
3179     UNICODE_STRING *dynamic_buffer = NULL;
3180     UNICODE_STRING nt_path;
3181     UNICODE_STRING *result = NULL;
3182     NTSTATUS status;
3183     DWORD needed;
3184
3185     RtlInitUnicodeStringEx(&nt_path, NULL);
3186     /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3187      * as this is on Wine. */
3188     status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3189                                        sizeof(buffer) - sizeof(WCHAR), &needed);
3190     if (status == STATUS_INFO_LENGTH_MISMATCH)
3191     {
3192         dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3193         status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3194         result = dynamic_buffer;
3195     }
3196     else
3197         result = (PUNICODE_STRING)buffer;
3198
3199     if (status) goto cleanup;
3200
3201     if (dwFlags & PROCESS_NAME_NATIVE)
3202     {
3203         result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3204         if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3205         {
3206             status = STATUS_OBJECT_PATH_NOT_FOUND;
3207             goto cleanup;
3208         }
3209         result = &nt_path;
3210     }
3211
3212     if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3213     {
3214         status = STATUS_BUFFER_TOO_SMALL;
3215         goto cleanup;
3216     }
3217
3218     *pdwSize = result->Length/sizeof(WCHAR);
3219     memcpy( lpExeName, result->Buffer, result->Length );
3220     lpExeName[*pdwSize] = 0;
3221
3222 cleanup:
3223     HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3224     RtlFreeUnicodeString(&nt_path);
3225     if (status) SetLastError( RtlNtStatusToDosError(status) );
3226     return !status;
3227 }
3228
3229 /***********************************************************************
3230  * ProcessIdToSessionId   (KERNEL32.@)
3231  * This function is available on Terminal Server 4SP4 and Windows 2000
3232  */
3233 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3234 {
3235     /* According to MSDN, if the calling process is not in a terminal
3236      * services environment, then the sessionid returned is zero.
3237      */
3238     *sessionid_ptr = 0;
3239     return TRUE;
3240 }
3241
3242
3243 /***********************************************************************
3244  *              RegisterServiceProcess (KERNEL32.@)
3245  *
3246  * A service process calls this function to ensure that it continues to run
3247  * even after a user logged off.
3248  */
3249 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
3250 {
3251     /* I don't think that Wine needs to do anything in this function */
3252     return 1; /* success */
3253 }
3254
3255
3256 /**********************************************************************
3257  *           IsWow64Process         (KERNEL32.@)
3258  */
3259 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
3260 {
3261     ULONG pbi;
3262     NTSTATUS status;
3263
3264     status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
3265
3266     if (status != STATUS_SUCCESS)
3267     {
3268         SetLastError( RtlNtStatusToDosError( status ) );
3269         return FALSE;
3270     }
3271     *Wow64Process = (pbi != 0);
3272     return TRUE;
3273 }
3274
3275
3276 /***********************************************************************
3277  *           GetCurrentProcess   (KERNEL32.@)
3278  *
3279  * Get a handle to the current process.
3280  *
3281  * PARAMS
3282  *  None.
3283  *
3284  * RETURNS
3285  *  A handle representing the current process.
3286  */
3287 #undef GetCurrentProcess
3288 HANDLE WINAPI GetCurrentProcess(void)
3289 {
3290     return (HANDLE)~(ULONG_PTR)0;
3291 }
3292
3293 /***********************************************************************
3294  *           CmdBatNotification   (KERNEL32.@)
3295  *
3296  * Notifies the system that a batch file has started or finished.
3297  *
3298  * PARAMS
3299  *  bBatchRunning [I]  TRUE if a batch file has started or 
3300  *                     FALSE if a batch file has finished executing.
3301  *
3302  * RETURNS
3303  *  Unknown.
3304  */
3305 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3306 {
3307     FIXME("%d\n", bBatchRunning);
3308     return FALSE;
3309 }
3310
3311
3312 /***********************************************************************
3313  *           RegisterApplicationRestart       (KERNEL32.@)
3314  */
3315 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3316 {
3317     FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3318
3319     return S_OK;
3320 }
3321
3322 /**********************************************************************
3323  *           WTSGetActiveConsoleSessionId     (KERNEL32.@)
3324  */
3325 DWORD WINAPI WTSGetActiveConsoleSessionId(void)
3326 {
3327     FIXME("stub\n");
3328     return 0;
3329 }