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