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