winedbg: Fix the path traversal.
[wine.git] / dlls / kernel32 / process.c
blob21185117a3b02080f754cbc3138675d16cdc7f6f
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
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.
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.
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <time.h>
30 #ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
32 #endif
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
35 #endif
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
38 #endif
39 #ifdef HAVE_SYS_PRCTL_H
40 # include <sys/prctl.h>
41 #endif
42 #include <sys/types.h>
44 #include "ntstatus.h"
45 #define WIN32_NO_STATUS
46 #include "wine/winbase16.h"
47 #include "wine/winuser16.h"
48 #include "winternl.h"
49 #include "kernel_private.h"
50 #include "wine/exception.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(process);
56 WINE_DECLARE_DEBUG_CHANNEL(file);
57 WINE_DECLARE_DEBUG_CHANNEL(relay);
59 typedef struct
61 LPSTR lpEnvAddress;
62 LPSTR lpCmdLine;
63 LPSTR lpCmdShow;
64 DWORD dwReserved;
65 } LOADPARMS32;
67 static UINT process_error_mode;
69 static DWORD shutdown_flags = 0;
70 static DWORD shutdown_priority = 0x280;
71 static DWORD process_dword;
73 HMODULE kernel32_handle = 0;
75 const WCHAR *DIR_Windows = NULL;
76 const WCHAR *DIR_System = NULL;
78 /* Process flags */
79 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
80 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
81 #define PDB32_DOS_PROC 0x0010 /* Dos process */
82 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
83 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
84 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
86 static const WCHAR comW[] = {'.','c','o','m',0};
87 static const WCHAR batW[] = {'.','b','a','t',0};
88 static const WCHAR cmdW[] = {'.','c','m','d',0};
89 static const WCHAR pifW[] = {'.','p','i','f',0};
90 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
92 static void exec_process( LPCWSTR name );
94 extern void SHELL_LoadRegistry(void);
97 /***********************************************************************
98 * contains_path
100 static inline int contains_path( LPCWSTR name )
102 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
106 /***********************************************************************
107 * is_special_env_var
109 * Check if an environment variable needs to be handled specially when
110 * passed through the Unix environment (i.e. prefixed with "WINE").
112 static inline int is_special_env_var( const char *var )
114 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
115 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
116 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
117 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
121 /***************************************************************************
122 * get_builtin_path
124 * Get the path of a builtin module when the native file does not exist.
126 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
128 WCHAR *file_part;
129 UINT len = strlenW( DIR_System );
131 if (contains_path( libname ))
133 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
134 filename, &file_part ) > size * sizeof(WCHAR))
135 return FALSE; /* too long */
137 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
138 return FALSE;
139 while (filename[len] == '\\') len++;
140 if (filename + len != file_part) return FALSE;
142 else
144 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
145 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
146 file_part = filename + len;
147 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
148 strcpyW( file_part, libname );
150 if (ext && !strchrW( file_part, '.' ))
152 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
153 return FALSE; /* too long */
154 strcatW( file_part, ext );
156 return TRUE;
160 /***********************************************************************
161 * open_builtin_exe_file
163 * Open an exe file for a builtin exe.
165 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
166 int test_only, int *file_exists )
168 char exename[MAX_PATH];
169 WCHAR *p;
170 UINT i, len;
172 *file_exists = 0;
173 if ((p = strrchrW( name, '/' ))) name = p + 1;
174 if ((p = strrchrW( name, '\\' ))) name = p + 1;
176 /* we don't want to depend on the current codepage here */
177 len = strlenW( name ) + 1;
178 if (len >= sizeof(exename)) return NULL;
179 for (i = 0; i < len; i++)
181 if (name[i] > 127) return NULL;
182 exename[i] = (char)name[i];
183 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
185 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
189 /***********************************************************************
190 * open_exe_file
192 * Open a specific exe file, taking load order into account.
193 * Returns the file handle or 0 for a builtin exe.
195 static HANDLE open_exe_file( const WCHAR *name )
197 HANDLE handle;
199 TRACE("looking for %s\n", debugstr_w(name) );
201 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
202 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
204 WCHAR buffer[MAX_PATH];
205 /* file doesn't exist, check for builtin */
206 if (!contains_path( name )) goto error;
207 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
208 handle = 0;
210 return handle;
212 error:
213 SetLastError( ERROR_FILE_NOT_FOUND );
214 return INVALID_HANDLE_VALUE;
218 /***********************************************************************
219 * find_exe_file
221 * Open an exe file, and return the full name and file handle.
222 * Returns FALSE if file could not be found.
223 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
224 * If file is a builtin exe, returns TRUE and sets handle to 0.
226 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
228 static const WCHAR exeW[] = {'.','e','x','e',0};
229 int file_exists;
231 TRACE("looking for %s\n", debugstr_w(name) );
233 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
234 !get_builtin_path( name, exeW, buffer, buflen ))
236 /* no builtin found, try native without extension in case it is a Unix app */
238 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
240 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
241 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
242 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
243 return TRUE;
245 return FALSE;
248 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
249 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
250 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
251 return TRUE;
253 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
254 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
255 if (file_exists)
257 *handle = 0;
258 return TRUE;
261 return FALSE;
265 /***********************************************************************
266 * build_initial_environment
268 * Build the Win32 environment from the Unix environment
270 static BOOL build_initial_environment( char **environ )
272 SIZE_T size = 1;
273 char **e;
274 WCHAR *p, *endptr;
275 void *ptr;
277 /* Compute the total size of the Unix environment */
278 for (e = environ; *e; e++)
280 if (is_special_env_var( *e )) continue;
281 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
283 size *= sizeof(WCHAR);
285 /* Now allocate the environment */
286 ptr = NULL;
287 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
288 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
289 return FALSE;
291 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
292 endptr = p + size / sizeof(WCHAR);
294 /* And fill it with the Unix environment */
295 for (e = environ; *e; e++)
297 char *str = *e;
299 /* skip Unix special variables and use the Wine variants instead */
300 if (!strncmp( str, "WINE", 4 ))
302 if (is_special_env_var( str + 4 )) str += 4;
303 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
305 else if (is_special_env_var( str )) continue; /* skip it */
307 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
308 p += strlenW(p) + 1;
310 *p = 0;
311 return TRUE;
315 /***********************************************************************
316 * set_registry_variables
318 * Set environment variables by enumerating the values of a key;
319 * helper for set_registry_environment().
320 * Note that Windows happily truncates the value if it's too big.
322 static void set_registry_variables( HANDLE hkey, ULONG type )
324 UNICODE_STRING env_name, env_value;
325 NTSTATUS status;
326 DWORD size;
327 int index;
328 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
329 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
331 for (index = 0; ; index++)
333 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
334 buffer, sizeof(buffer), &size );
335 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
336 break;
337 if (info->Type != type)
338 continue;
339 env_name.Buffer = info->Name;
340 env_name.Length = env_name.MaximumLength = info->NameLength;
341 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
342 env_value.Length = env_value.MaximumLength = info->DataLength;
343 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
344 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
345 if (info->Type == REG_EXPAND_SZ)
347 WCHAR buf_expanded[1024];
348 UNICODE_STRING env_expanded;
349 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
350 env_expanded.Buffer=buf_expanded;
351 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
352 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
353 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
355 else
357 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
363 /***********************************************************************
364 * set_registry_environment
366 * Set the environment variables specified in the registry.
368 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
369 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
370 * on the order in which the variables are processed. But on Windows it
371 * does not really matter since they only use %SystemDrive% and
372 * %SystemRoot% which are predefined. But Wine defines these in the
373 * registry, so we need two passes.
375 static BOOL set_registry_environment(void)
377 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
378 'S','y','s','t','e','m','\\',
379 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
380 'C','o','n','t','r','o','l','\\',
381 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
382 'E','n','v','i','r','o','n','m','e','n','t',0};
383 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
385 OBJECT_ATTRIBUTES attr;
386 UNICODE_STRING nameW;
387 HANDLE hkey;
388 BOOL ret = FALSE;
390 attr.Length = sizeof(attr);
391 attr.RootDirectory = 0;
392 attr.ObjectName = &nameW;
393 attr.Attributes = 0;
394 attr.SecurityDescriptor = NULL;
395 attr.SecurityQualityOfService = NULL;
397 /* first the system environment variables */
398 RtlInitUnicodeString( &nameW, env_keyW );
399 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
401 set_registry_variables( hkey, REG_SZ );
402 set_registry_variables( hkey, REG_EXPAND_SZ );
403 NtClose( hkey );
404 ret = TRUE;
407 /* then the ones for the current user */
408 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
409 RtlInitUnicodeString( &nameW, envW );
410 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
412 set_registry_variables( hkey, REG_SZ );
413 set_registry_variables( hkey, REG_EXPAND_SZ );
414 NtClose( hkey );
416 NtClose( attr.RootDirectory );
417 return ret;
421 /***********************************************************************
422 * get_reg_value
424 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
426 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
427 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
428 DWORD len, size = sizeof(buffer);
429 WCHAR *ret = NULL;
430 UNICODE_STRING nameW;
432 RtlInitUnicodeString( &nameW, name );
433 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
434 return NULL;
436 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
437 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
439 if (info->Type == REG_EXPAND_SZ)
441 UNICODE_STRING value, expanded;
443 value.MaximumLength = len * sizeof(WCHAR);
444 value.Buffer = (WCHAR *)info->Data;
445 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
446 value.Length = len * sizeof(WCHAR);
447 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
448 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
449 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
450 else RtlFreeUnicodeString( &expanded );
452 else if (info->Type == REG_SZ)
454 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
456 memcpy( ret, info->Data, len * sizeof(WCHAR) );
457 ret[len] = 0;
460 return ret;
464 /***********************************************************************
465 * set_additional_environment
467 * Set some additional environment variables not specified in the registry.
469 static void set_additional_environment(void)
471 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
472 'S','o','f','t','w','a','r','e','\\',
473 'M','i','c','r','o','s','o','f','t','\\',
474 'W','i','n','d','o','w','s',' ','N','T','\\',
475 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
476 'P','r','o','f','i','l','e','L','i','s','t',0};
477 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
478 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
479 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
480 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
481 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
482 OBJECT_ATTRIBUTES attr;
483 UNICODE_STRING nameW;
484 WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
485 HANDLE hkey;
486 const char *name = wine_get_user_name();
487 DWORD len;
489 /* set the USERNAME variable */
491 len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
492 if (len)
494 user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
495 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
496 SetEnvironmentVariableW( usernameW, user_name );
499 /* set the USERPROFILE and ALLUSERSPROFILE variables */
501 attr.Length = sizeof(attr);
502 attr.RootDirectory = 0;
503 attr.ObjectName = &nameW;
504 attr.Attributes = 0;
505 attr.SecurityDescriptor = NULL;
506 attr.SecurityQualityOfService = NULL;
507 RtlInitUnicodeString( &nameW, profile_keyW );
508 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
510 profile_dir = get_reg_value( hkey, profiles_valueW );
511 all_users_dir = get_reg_value( hkey, all_users_valueW );
512 NtClose( hkey );
515 if (profile_dir)
517 WCHAR *value, *p;
519 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
520 len += strlenW(profile_dir) + 1;
521 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
522 strcpyW( value, profile_dir );
523 p = value + strlenW(value);
524 if (p > value && p[-1] != '\\') *p++ = '\\';
525 strcpyW( p, user_name );
526 SetEnvironmentVariableW( userprofileW, value );
527 if (all_users_dir)
529 strcpyW( p, all_users_dir );
530 SetEnvironmentVariableW( allusersW, value );
532 HeapFree( GetProcessHeap(), 0, value );
535 HeapFree( GetProcessHeap(), 0, all_users_dir );
536 HeapFree( GetProcessHeap(), 0, profile_dir );
537 HeapFree( GetProcessHeap(), 0, user_name );
540 /***********************************************************************
541 * set_library_wargv
543 * Set the Wine library Unicode argv global variables.
545 static void set_library_wargv( char **argv )
547 int argc;
548 char *q;
549 WCHAR *p;
550 WCHAR **wargv;
551 DWORD total = 0;
553 for (argc = 0; argv[argc]; argc++)
554 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
556 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
557 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
558 p = (WCHAR *)(wargv + argc + 1);
559 for (argc = 0; argv[argc]; argc++)
561 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
562 wargv[argc] = p;
563 p += reslen;
564 total -= reslen;
566 wargv[argc] = NULL;
568 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
570 for (argc = 0; wargv[argc]; argc++)
571 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
573 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
574 q = (char *)(argv + argc + 1);
575 for (argc = 0; wargv[argc]; argc++)
577 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
578 argv[argc] = q;
579 q += reslen;
580 total -= reslen;
582 argv[argc] = NULL;
584 __wine_main_argc = argc;
585 __wine_main_argv = argv;
586 __wine_main_wargv = wargv;
590 /***********************************************************************
591 * build_command_line
593 * Build the command line of a process from the argv array.
595 * Note that it does NOT necessarily include the file name.
596 * Sometimes we don't even have any command line options at all.
598 * We must quote and escape characters so that the argv array can be rebuilt
599 * from the command line:
600 * - spaces and tabs must be quoted
601 * 'a b' -> '"a b"'
602 * - quotes must be escaped
603 * '"' -> '\"'
604 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
605 * resulting in an odd number of '\' followed by a '"'
606 * '\"' -> '\\\"'
607 * '\\"' -> '\\\\\"'
608 * - '\'s that are not followed by a '"' can be left as is
609 * 'a\b' == 'a\b'
610 * 'a\\b' == 'a\\b'
612 static BOOL build_command_line( WCHAR **argv )
614 int len;
615 WCHAR **arg;
616 LPWSTR p;
617 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
619 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
621 len = 0;
622 for (arg = argv; *arg; arg++)
624 int has_space,bcount;
625 WCHAR* a;
627 has_space=0;
628 bcount=0;
629 a=*arg;
630 if( !*a ) has_space=1;
631 while (*a!='\0') {
632 if (*a=='\\') {
633 bcount++;
634 } else {
635 if (*a==' ' || *a=='\t') {
636 has_space=1;
637 } else if (*a=='"') {
638 /* doubling of '\' preceding a '"',
639 * plus escaping of said '"'
641 len+=2*bcount+1;
643 bcount=0;
645 a++;
647 len+=(a-*arg)+1 /* for the separating space */;
648 if (has_space)
649 len+=2; /* for the quotes */
652 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
653 return FALSE;
655 p = rupp->CommandLine.Buffer;
656 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
657 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
658 for (arg = argv; *arg; arg++)
660 int has_space,has_quote;
661 WCHAR* a;
663 /* Check for quotes and spaces in this argument */
664 has_space=has_quote=0;
665 a=*arg;
666 if( !*a ) has_space=1;
667 while (*a!='\0') {
668 if (*a==' ' || *a=='\t') {
669 has_space=1;
670 if (has_quote)
671 break;
672 } else if (*a=='"') {
673 has_quote=1;
674 if (has_space)
675 break;
677 a++;
680 /* Now transfer it to the command line */
681 if (has_space)
682 *p++='"';
683 if (has_quote) {
684 int bcount;
685 WCHAR* a;
687 bcount=0;
688 a=*arg;
689 while (*a!='\0') {
690 if (*a=='\\') {
691 *p++=*a;
692 bcount++;
693 } else {
694 if (*a=='"') {
695 int i;
697 /* Double all the '\\' preceding this '"', plus one */
698 for (i=0;i<=bcount;i++)
699 *p++='\\';
700 *p++='"';
701 } else {
702 *p++=*a;
704 bcount=0;
706 a++;
708 } else {
709 WCHAR* x = *arg;
710 while ((*p=*x++)) p++;
712 if (has_space)
713 *p++='"';
714 *p++=' ';
716 if (p > rupp->CommandLine.Buffer)
717 p--; /* remove last space */
718 *p = '\0';
720 return TRUE;
724 /***********************************************************************
725 * init_current_directory
727 * Initialize the current directory from the Unix cwd or the parent info.
729 static void init_current_directory( CURDIR *cur_dir )
731 UNICODE_STRING dir_str;
732 char *cwd;
733 int size;
735 /* if we received a cur dir from the parent, try this first */
737 if (cur_dir->DosPath.Length)
739 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
742 /* now try to get it from the Unix cwd */
744 for (size = 256; ; size *= 2)
746 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
747 if (getcwd( cwd, size )) break;
748 HeapFree( GetProcessHeap(), 0, cwd );
749 if (errno == ERANGE) continue;
750 cwd = NULL;
751 break;
754 if (cwd)
756 WCHAR *dirW;
757 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
758 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
760 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
761 RtlInitUnicodeString( &dir_str, dirW );
762 RtlSetCurrentDirectory_U( &dir_str );
763 RtlFreeUnicodeString( &dir_str );
767 if (!cur_dir->DosPath.Length) /* still not initialized */
769 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
770 "starting in the Windows directory.\n", cwd ? cwd : "" );
771 RtlInitUnicodeString( &dir_str, DIR_Windows );
772 RtlSetCurrentDirectory_U( &dir_str );
774 HeapFree( GetProcessHeap(), 0, cwd );
776 done:
777 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
778 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
782 /***********************************************************************
783 * init_windows_dirs
785 * Initialize the windows and system directories from the environment.
787 static void init_windows_dirs(void)
789 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
791 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
792 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
793 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
794 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
796 DWORD len;
797 WCHAR *buffer;
799 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
801 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
802 GetEnvironmentVariableW( windirW, buffer, len );
803 DIR_Windows = buffer;
805 else DIR_Windows = default_windirW;
807 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
809 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
810 GetEnvironmentVariableW( winsysdirW, buffer, len );
811 DIR_System = buffer;
813 else
815 len = strlenW( DIR_Windows );
816 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
817 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
818 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
819 DIR_System = buffer;
822 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
823 ERR( "directory %s could not be created, error %u\n",
824 debugstr_w(DIR_Windows), GetLastError() );
825 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
826 ERR( "directory %s could not be created, error %u\n",
827 debugstr_w(DIR_System), GetLastError() );
829 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
830 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
832 /* set the directories in ntdll too */
833 __wine_init_windows_dir( DIR_Windows, DIR_System );
837 /***********************************************************************
838 * start_wineboot
840 * Start the wineboot process if necessary. Return the event to wait on.
842 static HANDLE start_wineboot(void)
844 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
845 HANDLE event;
847 if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
849 ERR( "failed to create wineboot event, expect trouble\n" );
850 return 0;
852 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
854 static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
855 STARTUPINFOW si;
856 PROCESS_INFORMATION pi;
857 WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];
859 memset( &si, 0, sizeof(si) );
860 si.cb = sizeof(si);
861 si.dwFlags = STARTF_USESTDHANDLES;
862 si.hStdInput = 0;
863 si.hStdOutput = 0;
864 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
866 GetSystemDirectoryW( cmdline, MAX_PATH );
867 lstrcatW( cmdline, command_line );
868 if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
870 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
871 CloseHandle( pi.hThread );
872 CloseHandle( pi.hProcess );
875 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
877 return event;
881 /***********************************************************************
882 * start_process
884 * Startup routine of a new process. Runs on the new process stack.
886 static void start_process( void *arg )
888 __TRY
890 PEB *peb = NtCurrentTeb()->Peb;
891 IMAGE_NT_HEADERS *nt;
892 LPTHREAD_START_ROUTINE entry;
894 nt = RtlImageNtHeader( peb->ImageBaseAddress );
895 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
896 nt->OptionalHeader.AddressOfEntryPoint);
898 if (TRACE_ON(relay))
899 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
900 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
902 SetLastError( 0 ); /* clear error code */
903 if (peb->BeingDebugged) DbgBreakPoint();
904 ExitThread( entry( peb ) );
906 __EXCEPT(UnhandledExceptionFilter)
908 TerminateThread( GetCurrentThread(), GetExceptionCode() );
910 __ENDTRY
914 /***********************************************************************
915 * set_process_name
917 * Change the process name in the ps output.
919 static void set_process_name( int argc, char *argv[] )
921 #ifdef HAVE_SETPROCTITLE
922 setproctitle("-%s", argv[1]);
923 #endif
925 #ifdef HAVE_PRCTL
926 int i, offset;
927 char *p, *prctl_name = argv[1];
928 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
930 #ifndef PR_SET_NAME
931 # define PR_SET_NAME 15
932 #endif
934 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
935 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
937 if (prctl( PR_SET_NAME, prctl_name ) != -1)
939 offset = argv[1] - argv[0];
940 memmove( argv[1] - offset, argv[1], end - argv[1] );
941 memset( end - offset, 0, offset );
942 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
943 argv[i-1] = NULL;
945 else
946 #endif /* HAVE_PRCTL */
948 /* remove argv[0] */
949 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
954 /***********************************************************************
955 * __wine_kernel_init
957 * Wine initialisation: load and start the main exe file.
959 void __wine_kernel_init(void)
961 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
962 static const WCHAR dotW[] = {'.',0};
963 static const WCHAR exeW[] = {'.','e','x','e',0};
965 WCHAR *p, main_exe_name[MAX_PATH+1];
966 PEB *peb = NtCurrentTeb()->Peb;
967 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
968 HANDLE boot_event = 0;
969 BOOL got_environment = TRUE;
971 /* Initialize everything */
973 PTHREAD_Init();
975 setbuf(stdout,NULL);
976 setbuf(stderr,NULL);
977 kernel32_handle = GetModuleHandleW(kernel32W);
979 LOCALE_Init();
981 if (!params->Environment)
983 /* Copy the parent environment */
984 if (!build_initial_environment( __wine_main_environ )) exit(1);
986 /* convert old configuration to new format */
987 convert_old_config();
989 got_environment = set_registry_environment();
990 set_additional_environment();
993 init_windows_dirs();
994 init_current_directory( &params->CurrentDirectory );
996 set_process_name( __wine_main_argc, __wine_main_argv );
997 set_library_wargv( __wine_main_argv );
999 if (peb->ProcessParameters->ImagePathName.Buffer)
1001 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1003 else
1005 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1006 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1008 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1009 ExitProcess( GetLastError() );
1011 if (!build_command_line( __wine_main_wargv )) goto error;
1012 boot_event = start_wineboot();
1015 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1016 p = strrchrW( main_exe_name, '.' );
1017 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1019 TRACE( "starting process name=%s argv[0]=%s\n",
1020 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1022 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1023 MODULE_get_dll_load_path(main_exe_name) );
1025 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1027 char msg[1024];
1028 DWORD error = GetLastError();
1030 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1031 if (error == ERROR_BAD_EXE_FORMAT ||
1032 error == ERROR_INVALID_ADDRESS ||
1033 error == ERROR_NOT_ENOUGH_MEMORY)
1035 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1036 /* if we get back here, it failed */
1039 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1040 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1041 ExitProcess( error );
1044 if (boot_event)
1046 if (WaitForSingleObject( boot_event, 30000 )) WARN( "boot event wait timed out\n" );
1047 CloseHandle( boot_event );
1048 /* if we didn't find environment section, try again now that wineboot has run */
1049 if (!got_environment)
1051 set_registry_environment();
1052 set_additional_environment();
1056 LdrInitializeThunk( 0, 0, 0, 0 );
1057 /* switch to the new stack */
1058 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1060 error:
1061 ExitProcess( GetLastError() );
1065 /***********************************************************************
1066 * build_argv
1068 * Build an argv array from a command-line.
1069 * 'reserved' is the number of args to reserve before the first one.
1071 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1073 int argc;
1074 char** argv;
1075 char *arg,*s,*d,*cmdline;
1076 int in_quotes,bcount,len;
1078 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1079 if (!(cmdline = malloc(len))) return NULL;
1080 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1082 argc=reserved+1;
1083 bcount=0;
1084 in_quotes=0;
1085 s=cmdline;
1086 while (1) {
1087 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1088 /* space */
1089 argc++;
1090 /* skip the remaining spaces */
1091 while (*s==' ' || *s=='\t') {
1092 s++;
1094 if (*s=='\0')
1095 break;
1096 bcount=0;
1097 continue;
1098 } else if (*s=='\\') {
1099 /* '\', count them */
1100 bcount++;
1101 } else if ((*s=='"') && ((bcount & 1)==0)) {
1102 /* unescaped '"' */
1103 in_quotes=!in_quotes;
1104 bcount=0;
1105 } else {
1106 /* a regular character */
1107 bcount=0;
1109 s++;
1111 argv=malloc(argc*sizeof(*argv));
1112 if (!argv)
1113 return NULL;
1115 arg=d=s=cmdline;
1116 bcount=0;
1117 in_quotes=0;
1118 argc=reserved;
1119 while (*s) {
1120 if ((*s==' ' || *s=='\t') && !in_quotes) {
1121 /* Close the argument and copy it */
1122 *d=0;
1123 argv[argc++]=arg;
1125 /* skip the remaining spaces */
1126 do {
1127 s++;
1128 } while (*s==' ' || *s=='\t');
1130 /* Start with a new argument */
1131 arg=d=s;
1132 bcount=0;
1133 } else if (*s=='\\') {
1134 /* '\\' */
1135 *d++=*s++;
1136 bcount++;
1137 } else if (*s=='"') {
1138 /* '"' */
1139 if ((bcount & 1)==0) {
1140 /* Preceded by an even number of '\', this is half that
1141 * number of '\', plus a '"' which we discard.
1143 d-=bcount/2;
1144 s++;
1145 in_quotes=!in_quotes;
1146 } else {
1147 /* Preceded by an odd number of '\', this is half that
1148 * number of '\' followed by a '"'
1150 d=d-bcount/2-1;
1151 *d++='"';
1152 s++;
1154 bcount=0;
1155 } else {
1156 /* a regular character */
1157 *d++=*s++;
1158 bcount=0;
1161 if (*arg) {
1162 *d='\0';
1163 argv[argc++]=arg;
1165 argv[argc]=NULL;
1167 return argv;
1171 /***********************************************************************
1172 * alloc_env_string
1174 * Allocate an environment string; helper for build_envp
1176 static char *alloc_env_string( const char *name, const char *value )
1178 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1179 strcpy( ret, name );
1180 strcat( ret, value );
1181 return ret;
1184 /***********************************************************************
1185 * build_envp
1187 * Build the environment of a new child process.
1189 static char **build_envp( const WCHAR *envW )
1191 const WCHAR *end;
1192 char **envp;
1193 char *env, *p;
1194 int count = 0, length;
1196 for (end = envW; *end; count++) end += strlenW(end) + 1;
1197 end++;
1198 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1199 if (!(env = malloc( length ))) return NULL;
1200 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1202 count += 4;
1204 if ((envp = malloc( count * sizeof(*envp) )))
1206 char **envptr = envp;
1208 /* some variables must not be modified, so we get them directly from the unix env */
1209 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1210 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1211 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1212 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1213 /* now put the Windows environment strings */
1214 for (p = env; *p; p += strlen(p) + 1)
1216 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1217 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1218 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1219 if (is_special_env_var( p )) /* prefix it with "WINE" */
1220 *envptr++ = alloc_env_string( "WINE", p );
1221 else
1222 *envptr++ = p;
1224 *envptr = 0;
1226 return envp;
1230 /***********************************************************************
1231 * fork_and_exec
1233 * Fork and exec a new Unix binary, checking for errors.
1235 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1236 const WCHAR *env, const char *newdir, DWORD flags )
1238 int fd[2];
1239 int pid, err;
1241 if (!env) env = GetEnvironmentStringsW();
1243 if (pipe(fd) == -1)
1245 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1246 return -1;
1248 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1249 if (!(pid = fork())) /* child */
1251 char **argv = build_argv( cmdline, 0 );
1252 char **envp = build_envp( env );
1253 close( fd[0] );
1255 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1257 int pid;
1258 if (!(pid = fork()))
1260 int fd = open( "/dev/null", O_RDWR );
1261 setsid();
1262 /* close stdin and stdout */
1263 if (fd != -1)
1265 dup2( fd, 0 );
1266 dup2( fd, 1 );
1267 close( fd );
1270 else if (pid != -1) _exit(0); /* parent */
1273 /* Reset signals that we previously set to SIG_IGN */
1274 signal( SIGPIPE, SIG_DFL );
1275 signal( SIGCHLD, SIG_DFL );
1277 if (newdir) chdir(newdir);
1279 if (argv && envp) execve( filename, argv, envp );
1280 err = errno;
1281 write( fd[1], &err, sizeof(err) );
1282 _exit(1);
1284 close( fd[1] );
1285 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1287 errno = err;
1288 pid = -1;
1290 if (pid == -1) FILE_SetDosError();
1291 close( fd[0] );
1292 return pid;
1296 /***********************************************************************
1297 * create_user_params
1299 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1300 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1301 const STARTUPINFOW *startup )
1303 RTL_USER_PROCESS_PARAMETERS *params;
1304 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1305 NTSTATUS status;
1306 WCHAR buffer[MAX_PATH];
1308 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1309 lstrcpynW( buffer, filename, MAX_PATH );
1310 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1311 lstrcpynW( buffer, filename, MAX_PATH );
1312 RtlInitUnicodeString( &image_str, buffer );
1314 RtlInitUnicodeString( &cmdline_str, cmdline );
1315 newdir.Buffer = NULL;
1316 if (cur_dir)
1318 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1320 /* skip \??\ prefix */
1321 curdir_str.Buffer = newdir.Buffer + 4;
1322 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1323 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1325 else cur_dir = NULL;
1327 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1328 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1329 if (startup->lpReserved2 && startup->cbReserved2)
1331 runtime.Length = 0;
1332 runtime.MaximumLength = startup->cbReserved2;
1333 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1336 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1337 cur_dir ? &curdir_str : NULL,
1338 &cmdline_str, env,
1339 startup->lpTitle ? &title : NULL,
1340 startup->lpDesktop ? &desktop : NULL,
1341 NULL,
1342 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1343 RtlFreeUnicodeString( &newdir );
1344 if (status != STATUS_SUCCESS)
1346 SetLastError( RtlNtStatusToDosError(status) );
1347 return NULL;
1350 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1351 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1353 if (startup->dwFlags & STARTF_USESTDHANDLES)
1355 params->hStdInput = startup->hStdInput;
1356 params->hStdOutput = startup->hStdOutput;
1357 params->hStdError = startup->hStdError;
1359 else
1361 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1362 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1363 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1365 params->dwX = startup->dwX;
1366 params->dwY = startup->dwY;
1367 params->dwXSize = startup->dwXSize;
1368 params->dwYSize = startup->dwYSize;
1369 params->dwXCountChars = startup->dwXCountChars;
1370 params->dwYCountChars = startup->dwYCountChars;
1371 params->dwFillAttribute = startup->dwFillAttribute;
1372 params->dwFlags = startup->dwFlags;
1373 params->wShowWindow = startup->wShowWindow;
1374 return params;
1378 /***********************************************************************
1379 * create_process
1381 * Create a new process. If hFile is a valid handle we have an exe
1382 * file, otherwise it is a Winelib app.
1384 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1385 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1386 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1387 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1388 void *res_start, void *res_end, int exec_only )
1390 BOOL ret, success = FALSE;
1391 HANDLE process_info;
1392 WCHAR *env_end;
1393 char *winedebug = NULL;
1394 RTL_USER_PROCESS_PARAMETERS *params;
1395 int socketfd[2];
1396 pid_t pid;
1397 int err;
1399 if (!env) RtlAcquirePebLock();
1401 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1403 if (!env) RtlReleasePebLock();
1404 return FALSE;
1406 env_end = params->Environment;
1407 while (*env_end)
1409 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1410 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1412 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1413 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1414 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1416 env_end += strlenW(env_end) + 1;
1418 env_end++;
1420 /* create the socket for the new process */
1422 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1424 if (!env) RtlReleasePebLock();
1425 HeapFree( GetProcessHeap(), 0, winedebug );
1426 RtlDestroyProcessParameters( params );
1427 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1428 return FALSE;
1430 wine_server_send_fd( socketfd[1] );
1431 close( socketfd[1] );
1433 /* create the process on the server side */
1435 SERVER_START_REQ( new_process )
1437 req->inherit_all = inherit;
1438 req->create_flags = flags;
1439 req->socket_fd = socketfd[1];
1440 req->exe_file = hFile;
1441 req->process_access = PROCESS_ALL_ACCESS;
1442 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1443 req->thread_access = THREAD_ALL_ACCESS;
1444 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1445 req->hstdin = params->hStdInput;
1446 req->hstdout = params->hStdOutput;
1447 req->hstderr = params->hStdError;
1449 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1451 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1452 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1453 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1454 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1456 else
1458 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1459 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1460 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1463 wine_server_add_data( req, params, params->Size );
1464 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1465 if ((ret = !wine_server_call_err( req )))
1467 info->dwProcessId = (DWORD)reply->pid;
1468 info->dwThreadId = (DWORD)reply->tid;
1469 info->hProcess = reply->phandle;
1470 info->hThread = reply->thandle;
1472 process_info = reply->info;
1474 SERVER_END_REQ;
1476 if (!env) RtlReleasePebLock();
1477 RtlDestroyProcessParameters( params );
1478 if (!ret)
1480 close( socketfd[0] );
1481 HeapFree( GetProcessHeap(), 0, winedebug );
1482 return FALSE;
1485 /* create the child process */
1487 if (exec_only || !(pid = fork())) /* child */
1489 char preloader_reserve[64], socket_env[64];
1490 char **argv = build_argv( cmd_line, 1 );
1492 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1494 if (!(pid = fork()))
1496 int fd = open( "/dev/null", O_RDWR );
1497 setsid();
1498 /* close stdin and stdout */
1499 if (fd != -1)
1501 dup2( fd, 0 );
1502 dup2( fd, 1 );
1503 close( fd );
1506 else if (pid != -1) _exit(0); /* parent */
1509 /* Reset signals that we previously set to SIG_IGN */
1510 signal( SIGPIPE, SIG_DFL );
1511 signal( SIGCHLD, SIG_DFL );
1513 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1514 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1515 (unsigned long)res_start, (unsigned long)res_end );
1517 putenv( preloader_reserve );
1518 putenv( socket_env );
1519 if (winedebug) putenv( winedebug );
1520 if (unixdir) chdir(unixdir);
1522 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1523 _exit(1);
1526 /* this is the parent */
1528 close( socketfd[0] );
1529 HeapFree( GetProcessHeap(), 0, winedebug );
1530 if (pid == -1)
1532 FILE_SetDosError();
1533 goto error;
1536 /* wait for the new process info to be ready */
1538 WaitForSingleObject( process_info, INFINITE );
1539 SERVER_START_REQ( get_new_process_info )
1541 req->info = process_info;
1542 wine_server_call( req );
1543 success = reply->success;
1544 err = reply->exit_code;
1546 SERVER_END_REQ;
1548 if (!success)
1550 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1551 goto error;
1553 CloseHandle( process_info );
1554 return success;
1556 error:
1557 CloseHandle( process_info );
1558 CloseHandle( info->hProcess );
1559 CloseHandle( info->hThread );
1560 info->hProcess = info->hThread = 0;
1561 info->dwProcessId = info->dwThreadId = 0;
1562 return FALSE;
1566 /***********************************************************************
1567 * create_vdm_process
1569 * Create a new VDM process for a 16-bit or DOS application.
1571 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1572 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1573 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1574 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1576 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1578 BOOL ret;
1579 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1580 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1582 if (!new_cmd_line)
1584 SetLastError( ERROR_OUTOFMEMORY );
1585 return FALSE;
1587 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1588 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1589 flags, startup, info, unixdir, NULL, NULL, exec_only );
1590 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1591 return ret;
1595 /***********************************************************************
1596 * create_cmd_process
1598 * Create a new cmd shell process for a .BAT file.
1600 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1601 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1602 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1603 LPPROCESS_INFORMATION info )
1606 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1607 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1608 WCHAR comspec[MAX_PATH];
1609 WCHAR *newcmdline;
1610 BOOL ret;
1612 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1613 return FALSE;
1614 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1615 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1616 return FALSE;
1618 strcpyW( newcmdline, comspec );
1619 strcatW( newcmdline, slashcW );
1620 strcatW( newcmdline, cmd_line );
1621 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1622 flags, env, cur_dir, startup, info );
1623 HeapFree( GetProcessHeap(), 0, newcmdline );
1624 return ret;
1628 /*************************************************************************
1629 * get_file_name
1631 * Helper for CreateProcess: retrieve the file name to load from the
1632 * app name and command line. Store the file name in buffer, and
1633 * return a possibly modified command line.
1634 * Also returns a handle to the opened file if it's a Windows binary.
1636 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1637 int buflen, HANDLE *handle )
1639 static const WCHAR quotesW[] = {'"','%','s','"',0};
1641 WCHAR *name, *pos, *ret = NULL;
1642 const WCHAR *p;
1643 BOOL got_space;
1645 /* if we have an app name, everything is easy */
1647 if (appname)
1649 /* use the unmodified app name as file name */
1650 lstrcpynW( buffer, appname, buflen );
1651 *handle = open_exe_file( buffer );
1652 if (!(ret = cmdline) || !cmdline[0])
1654 /* no command-line, create one */
1655 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1656 sprintfW( ret, quotesW, appname );
1658 return ret;
1661 if (!cmdline)
1663 SetLastError( ERROR_INVALID_PARAMETER );
1664 return NULL;
1667 /* first check for a quoted file name */
1669 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1671 int len = p - cmdline - 1;
1672 /* extract the quoted portion as file name */
1673 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1674 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1675 name[len] = 0;
1677 if (find_exe_file( name, buffer, buflen, handle ))
1678 ret = cmdline; /* no change necessary */
1679 goto done;
1682 /* now try the command-line word by word */
1684 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1685 return NULL;
1686 pos = name;
1687 p = cmdline;
1688 got_space = FALSE;
1690 while (*p)
1692 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1693 *pos = 0;
1694 if (find_exe_file( name, buffer, buflen, handle ))
1696 ret = cmdline;
1697 break;
1699 if (*p) got_space = TRUE;
1702 if (ret && got_space) /* now build a new command-line with quotes */
1704 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1705 goto done;
1706 sprintfW( ret, quotesW, name );
1707 strcatW( ret, p );
1710 done:
1711 HeapFree( GetProcessHeap(), 0, name );
1712 return ret;
1716 /**********************************************************************
1717 * CreateProcessA (KERNEL32.@)
1719 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1720 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1721 DWORD flags, LPVOID env, LPCSTR cur_dir,
1722 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1724 BOOL ret = FALSE;
1725 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1726 UNICODE_STRING desktopW, titleW;
1727 STARTUPINFOW infoW;
1729 desktopW.Buffer = NULL;
1730 titleW.Buffer = NULL;
1731 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1732 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1733 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1735 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1736 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1738 memcpy( &infoW, startup_info, sizeof(infoW) );
1739 infoW.lpDesktop = desktopW.Buffer;
1740 infoW.lpTitle = titleW.Buffer;
1742 if (startup_info->lpReserved)
1743 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1744 debugstr_a(startup_info->lpReserved));
1746 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1747 inherit, flags, env, cur_dirW, &infoW, info );
1748 done:
1749 HeapFree( GetProcessHeap(), 0, app_nameW );
1750 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1751 HeapFree( GetProcessHeap(), 0, cur_dirW );
1752 RtlFreeUnicodeString( &desktopW );
1753 RtlFreeUnicodeString( &titleW );
1754 return ret;
1758 /**********************************************************************
1759 * CreateProcessW (KERNEL32.@)
1761 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1762 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1763 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1764 LPPROCESS_INFORMATION info )
1766 BOOL retv = FALSE;
1767 HANDLE hFile = 0;
1768 char *unixdir = NULL;
1769 WCHAR name[MAX_PATH];
1770 WCHAR *tidy_cmdline, *p, *envW = env;
1771 void *res_start, *res_end;
1773 /* Process the AppName and/or CmdLine to get module name and path */
1775 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1777 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1778 return FALSE;
1779 if (hFile == INVALID_HANDLE_VALUE) goto done;
1781 /* Warn if unsupported features are used */
1783 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1784 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1785 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1786 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1787 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1789 if (cur_dir)
1791 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1793 SetLastError(ERROR_DIRECTORY);
1794 goto done;
1797 else
1799 WCHAR buf[MAX_PATH];
1800 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1803 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1805 char *p = env;
1806 DWORD lenW;
1808 while (*p) p += strlen(p) + 1;
1809 p++; /* final null */
1810 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1811 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1812 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1813 flags |= CREATE_UNICODE_ENVIRONMENT;
1816 info->hThread = info->hProcess = 0;
1817 info->dwProcessId = info->dwThreadId = 0;
1819 /* Determine executable type */
1821 if (!hFile) /* builtin exe */
1823 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1824 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1825 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1826 goto done;
1829 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1831 case BINARY_PE_EXE:
1832 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1833 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1834 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1835 break;
1836 case BINARY_OS216:
1837 case BINARY_WIN16:
1838 case BINARY_DOS:
1839 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1840 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1841 inherit, flags, startup_info, info, unixdir, FALSE );
1842 break;
1843 case BINARY_PE_DLL:
1844 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1845 SetLastError( ERROR_BAD_EXE_FORMAT );
1846 break;
1847 case BINARY_UNIX_LIB:
1848 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1849 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1850 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1851 break;
1852 case BINARY_UNKNOWN:
1853 /* check for .com or .bat extension */
1854 if ((p = strrchrW( name, '.' )))
1856 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1858 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1859 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1860 inherit, flags, startup_info, info, unixdir, FALSE );
1861 break;
1863 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1865 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1866 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1867 inherit, flags, startup_info, info );
1868 break;
1871 /* fall through */
1872 case BINARY_UNIX_EXE:
1874 /* unknown file, try as unix executable */
1875 char *unix_name;
1877 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1879 if ((unix_name = wine_get_unix_file_name( name )))
1881 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags ) != -1);
1882 HeapFree( GetProcessHeap(), 0, unix_name );
1885 break;
1887 CloseHandle( hFile );
1889 done:
1890 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1891 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1892 HeapFree( GetProcessHeap(), 0, unixdir );
1893 if (retv)
1894 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
1895 return retv;
1899 /**********************************************************************
1900 * exec_process
1902 static void exec_process( LPCWSTR name )
1904 HANDLE hFile;
1905 WCHAR *p;
1906 void *res_start, *res_end;
1907 STARTUPINFOW startup_info;
1908 PROCESS_INFORMATION info;
1910 hFile = open_exe_file( name );
1911 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
1913 memset( &startup_info, 0, sizeof(startup_info) );
1914 startup_info.cb = sizeof(startup_info);
1916 /* Determine executable type */
1918 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1920 case BINARY_PE_EXE:
1921 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1922 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1923 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
1924 break;
1925 case BINARY_UNIX_LIB:
1926 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1927 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1928 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
1929 break;
1930 case BINARY_UNKNOWN:
1931 /* check for .com or .pif extension */
1932 if (!(p = strrchrW( name, '.' ))) break;
1933 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
1934 /* fall through */
1935 case BINARY_OS216:
1936 case BINARY_WIN16:
1937 case BINARY_DOS:
1938 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1939 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1940 FALSE, 0, &startup_info, &info, NULL, TRUE );
1941 break;
1942 default:
1943 break;
1945 CloseHandle( hFile );
1949 /***********************************************************************
1950 * wait_input_idle
1952 * Wrapper to call WaitForInputIdle USER function
1954 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1956 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1958 HMODULE mod = GetModuleHandleA( "user32.dll" );
1959 if (mod)
1961 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1962 if (ptr) return ptr( process, timeout );
1964 return 0;
1968 /***********************************************************************
1969 * WinExec (KERNEL32.@)
1971 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1973 PROCESS_INFORMATION info;
1974 STARTUPINFOA startup;
1975 char *cmdline;
1976 UINT ret;
1978 memset( &startup, 0, sizeof(startup) );
1979 startup.cb = sizeof(startup);
1980 startup.dwFlags = STARTF_USESHOWWINDOW;
1981 startup.wShowWindow = nCmdShow;
1983 /* cmdline needs to be writable for CreateProcess */
1984 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1985 strcpy( cmdline, lpCmdLine );
1987 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1988 0, NULL, NULL, &startup, &info ))
1990 /* Give 30 seconds to the app to come up */
1991 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1992 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1993 ret = 33;
1994 /* Close off the handles */
1995 CloseHandle( info.hThread );
1996 CloseHandle( info.hProcess );
1998 else if ((ret = GetLastError()) >= 32)
2000 FIXME("Strange error set by CreateProcess: %d\n", ret );
2001 ret = 11;
2003 HeapFree( GetProcessHeap(), 0, cmdline );
2004 return ret;
2008 /**********************************************************************
2009 * LoadModule (KERNEL32.@)
2011 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2013 LOADPARMS32 *params = paramBlock;
2014 PROCESS_INFORMATION info;
2015 STARTUPINFOA startup;
2016 HINSTANCE hInstance;
2017 LPSTR cmdline, p;
2018 char filename[MAX_PATH];
2019 BYTE len;
2021 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2023 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2024 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2025 return ULongToHandle(GetLastError());
2027 len = (BYTE)params->lpCmdLine[0];
2028 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2029 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2031 strcpy( cmdline, filename );
2032 p = cmdline + strlen(cmdline);
2033 *p++ = ' ';
2034 memcpy( p, params->lpCmdLine + 1, len );
2035 p[len] = 0;
2037 memset( &startup, 0, sizeof(startup) );
2038 startup.cb = sizeof(startup);
2039 if (params->lpCmdShow)
2041 startup.dwFlags = STARTF_USESHOWWINDOW;
2042 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2045 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2046 params->lpEnvAddress, NULL, &startup, &info ))
2048 /* Give 30 seconds to the app to come up */
2049 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2050 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2051 hInstance = (HINSTANCE)33;
2052 /* Close off the handles */
2053 CloseHandle( info.hThread );
2054 CloseHandle( info.hProcess );
2056 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2058 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2059 hInstance = (HINSTANCE)11;
2062 HeapFree( GetProcessHeap(), 0, cmdline );
2063 return hInstance;
2067 /******************************************************************************
2068 * TerminateProcess (KERNEL32.@)
2070 * Terminates a process.
2072 * PARAMS
2073 * handle [I] Process to terminate.
2074 * exit_code [I] Exit code.
2076 * RETURNS
2077 * Success: TRUE.
2078 * Failure: FALSE, check GetLastError().
2080 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2082 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2083 if (status) SetLastError( RtlNtStatusToDosError(status) );
2084 return !status;
2088 /***********************************************************************
2089 * ExitProcess (KERNEL32.@)
2091 * Exits the current process.
2093 * PARAMS
2094 * status [I] Status code to exit with.
2096 * RETURNS
2097 * Nothing.
2099 void WINAPI ExitProcess( DWORD status )
2101 LdrShutdownProcess();
2102 NtTerminateProcess(GetCurrentProcess(), status);
2103 exit(status);
2107 /***********************************************************************
2108 * GetExitCodeProcess [KERNEL32.@]
2110 * Gets termination status of specified process.
2112 * PARAMS
2113 * hProcess [in] Handle to the process.
2114 * lpExitCode [out] Address to receive termination status.
2116 * RETURNS
2117 * Success: TRUE
2118 * Failure: FALSE
2120 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2122 NTSTATUS status;
2123 PROCESS_BASIC_INFORMATION pbi;
2125 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2126 sizeof(pbi), NULL);
2127 if (status == STATUS_SUCCESS)
2129 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2130 return TRUE;
2132 SetLastError( RtlNtStatusToDosError(status) );
2133 return FALSE;
2137 /***********************************************************************
2138 * SetErrorMode (KERNEL32.@)
2140 UINT WINAPI SetErrorMode( UINT mode )
2142 UINT old = process_error_mode;
2143 process_error_mode = mode;
2144 return old;
2148 /**********************************************************************
2149 * TlsAlloc [KERNEL32.@]
2151 * Allocates a thread local storage index.
2153 * RETURNS
2154 * Success: TLS index.
2155 * Failure: 0xFFFFFFFF
2157 DWORD WINAPI TlsAlloc( void )
2159 DWORD index;
2160 PEB * const peb = NtCurrentTeb()->Peb;
2162 RtlAcquirePebLock();
2163 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2164 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2165 else
2167 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2168 if (index != ~0U)
2170 if (!NtCurrentTeb()->TlsExpansionSlots &&
2171 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2172 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2174 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2175 index = ~0U;
2176 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2178 else
2180 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2181 index += TLS_MINIMUM_AVAILABLE;
2184 else SetLastError( ERROR_NO_MORE_ITEMS );
2186 RtlReleasePebLock();
2187 return index;
2191 /**********************************************************************
2192 * TlsFree [KERNEL32.@]
2194 * Releases a thread local storage index, making it available for reuse.
2196 * PARAMS
2197 * index [in] TLS index to free.
2199 * RETURNS
2200 * Success: TRUE
2201 * Failure: FALSE
2203 BOOL WINAPI TlsFree( DWORD index )
2205 BOOL ret;
2207 RtlAcquirePebLock();
2208 if (index >= TLS_MINIMUM_AVAILABLE)
2210 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2211 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2213 else
2215 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2216 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2218 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2219 else SetLastError( ERROR_INVALID_PARAMETER );
2220 RtlReleasePebLock();
2221 return TRUE;
2225 /**********************************************************************
2226 * TlsGetValue [KERNEL32.@]
2228 * Gets value in a thread's TLS slot.
2230 * PARAMS
2231 * index [in] TLS index to retrieve value for.
2233 * RETURNS
2234 * Success: Value stored in calling thread's TLS slot for index.
2235 * Failure: 0 and GetLastError() returns NO_ERROR.
2237 LPVOID WINAPI TlsGetValue( DWORD index )
2239 LPVOID ret;
2241 if (index < TLS_MINIMUM_AVAILABLE)
2243 ret = NtCurrentTeb()->TlsSlots[index];
2245 else
2247 index -= TLS_MINIMUM_AVAILABLE;
2248 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2250 SetLastError( ERROR_INVALID_PARAMETER );
2251 return NULL;
2253 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2254 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2256 SetLastError( ERROR_SUCCESS );
2257 return ret;
2261 /**********************************************************************
2262 * TlsSetValue [KERNEL32.@]
2264 * Stores a value in the thread's TLS slot.
2266 * PARAMS
2267 * index [in] TLS index to set value for.
2268 * value [in] Value to be stored.
2270 * RETURNS
2271 * Success: TRUE
2272 * Failure: FALSE
2274 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2276 if (index < TLS_MINIMUM_AVAILABLE)
2278 NtCurrentTeb()->TlsSlots[index] = value;
2280 else
2282 index -= TLS_MINIMUM_AVAILABLE;
2283 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2285 SetLastError( ERROR_INVALID_PARAMETER );
2286 return FALSE;
2288 if (!NtCurrentTeb()->TlsExpansionSlots &&
2289 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2290 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2292 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2293 return FALSE;
2295 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2297 return TRUE;
2301 /***********************************************************************
2302 * GetProcessFlags (KERNEL32.@)
2304 DWORD WINAPI GetProcessFlags( DWORD processid )
2306 IMAGE_NT_HEADERS *nt;
2307 DWORD flags = 0;
2309 if (processid && processid != GetCurrentProcessId()) return 0;
2311 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2313 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2314 flags |= PDB32_CONSOLE_PROC;
2316 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2317 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2318 return flags;
2322 /***********************************************************************
2323 * GetProcessDword (KERNEL.485)
2324 * GetProcessDword (KERNEL32.18)
2325 * 'Of course you cannot directly access Windows internal structures'
2327 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2329 DWORD x, y;
2330 STARTUPINFOW siw;
2332 TRACE("(%d, %d)\n", dwProcessID, offset );
2334 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2336 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2337 return 0;
2340 switch ( offset )
2342 case GPD_APP_COMPAT_FLAGS:
2343 return GetAppCompatFlags16(0);
2344 case GPD_LOAD_DONE_EVENT:
2345 return 0;
2346 case GPD_HINSTANCE16:
2347 return GetTaskDS16();
2348 case GPD_WINDOWS_VERSION:
2349 return GetExeVersion16();
2350 case GPD_THDB:
2351 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2352 case GPD_PDB:
2353 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2354 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2355 GetStartupInfoW(&siw);
2356 return HandleToULong(siw.hStdOutput);
2357 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2358 GetStartupInfoW(&siw);
2359 return HandleToULong(siw.hStdInput);
2360 case GPD_STARTF_SHOWWINDOW:
2361 GetStartupInfoW(&siw);
2362 return siw.wShowWindow;
2363 case GPD_STARTF_SIZE:
2364 GetStartupInfoW(&siw);
2365 x = siw.dwXSize;
2366 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2367 y = siw.dwYSize;
2368 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2369 return MAKELONG( x, y );
2370 case GPD_STARTF_POSITION:
2371 GetStartupInfoW(&siw);
2372 x = siw.dwX;
2373 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2374 y = siw.dwY;
2375 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2376 return MAKELONG( x, y );
2377 case GPD_STARTF_FLAGS:
2378 GetStartupInfoW(&siw);
2379 return siw.dwFlags;
2380 case GPD_PARENT:
2381 return 0;
2382 case GPD_FLAGS:
2383 return GetProcessFlags(0);
2384 case GPD_USERDATA:
2385 return process_dword;
2386 default:
2387 ERR("Unknown offset %d\n", offset );
2388 return 0;
2392 /***********************************************************************
2393 * SetProcessDword (KERNEL.484)
2394 * 'Of course you cannot directly access Windows internal structures'
2396 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2398 TRACE("(%d, %d)\n", dwProcessID, offset );
2400 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2402 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2403 return;
2406 switch ( offset )
2408 case GPD_APP_COMPAT_FLAGS:
2409 case GPD_LOAD_DONE_EVENT:
2410 case GPD_HINSTANCE16:
2411 case GPD_WINDOWS_VERSION:
2412 case GPD_THDB:
2413 case GPD_PDB:
2414 case GPD_STARTF_SHELLDATA:
2415 case GPD_STARTF_HOTKEY:
2416 case GPD_STARTF_SHOWWINDOW:
2417 case GPD_STARTF_SIZE:
2418 case GPD_STARTF_POSITION:
2419 case GPD_STARTF_FLAGS:
2420 case GPD_PARENT:
2421 case GPD_FLAGS:
2422 ERR("Not allowed to modify offset %d\n", offset );
2423 break;
2424 case GPD_USERDATA:
2425 process_dword = value;
2426 break;
2427 default:
2428 ERR("Unknown offset %d\n", offset );
2429 break;
2434 /***********************************************************************
2435 * ExitProcess (KERNEL.466)
2437 void WINAPI ExitProcess16( WORD status )
2439 DWORD count;
2440 ReleaseThunkLock( &count );
2441 ExitProcess( status );
2445 /*********************************************************************
2446 * OpenProcess (KERNEL32.@)
2448 * Opens a handle to a process.
2450 * PARAMS
2451 * access [I] Desired access rights assigned to the returned handle.
2452 * inherit [I] Determines whether or not child processes will inherit the handle.
2453 * id [I] Process identifier of the process to get a handle to.
2455 * RETURNS
2456 * Success: Valid handle to the specified process.
2457 * Failure: NULL, check GetLastError().
2459 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2461 NTSTATUS status;
2462 HANDLE handle;
2463 OBJECT_ATTRIBUTES attr;
2464 CLIENT_ID cid;
2466 cid.UniqueProcess = ULongToHandle(id);
2467 cid.UniqueThread = 0; /* FIXME ? */
2469 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2470 attr.RootDirectory = NULL;
2471 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2472 attr.SecurityDescriptor = NULL;
2473 attr.SecurityQualityOfService = NULL;
2474 attr.ObjectName = NULL;
2476 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2478 status = NtOpenProcess(&handle, access, &attr, &cid);
2479 if (status != STATUS_SUCCESS)
2481 SetLastError( RtlNtStatusToDosError(status) );
2482 return NULL;
2484 return handle;
2488 /*********************************************************************
2489 * MapProcessHandle (KERNEL.483)
2490 * GetProcessId (KERNEL32.@)
2492 * Gets the a unique identifier of a process.
2494 * PARAMS
2495 * hProcess [I] Handle to the process.
2497 * RETURNS
2498 * Success: TRUE.
2499 * Failure: FALSE, check GetLastError().
2501 * NOTES
2503 * The identifier is unique only on the machine and only until the process
2504 * exits (including system shutdown).
2506 DWORD WINAPI GetProcessId( HANDLE hProcess )
2508 NTSTATUS status;
2509 PROCESS_BASIC_INFORMATION pbi;
2511 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2512 sizeof(pbi), NULL);
2513 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2514 SetLastError( RtlNtStatusToDosError(status) );
2515 return 0;
2519 /*********************************************************************
2520 * CloseW32Handle (KERNEL.474)
2521 * CloseHandle (KERNEL32.@)
2523 * Closes a handle.
2525 * PARAMS
2526 * handle [I] Handle to close.
2528 * RETURNS
2529 * Success: TRUE.
2530 * Failure: FALSE, check GetLastError().
2532 BOOL WINAPI CloseHandle( HANDLE handle )
2534 NTSTATUS status;
2536 /* stdio handles need special treatment */
2537 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2538 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2539 (handle == (HANDLE)STD_ERROR_HANDLE))
2540 handle = GetStdHandle( HandleToULong(handle) );
2542 if (is_console_handle(handle))
2543 return CloseConsoleHandle(handle);
2545 status = NtClose( handle );
2546 if (status) SetLastError( RtlNtStatusToDosError(status) );
2547 return !status;
2551 /*********************************************************************
2552 * GetHandleInformation (KERNEL32.@)
2554 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2556 OBJECT_DATA_INFORMATION info;
2557 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2559 if (status) SetLastError( RtlNtStatusToDosError(status) );
2560 else if (flags)
2562 *flags = 0;
2563 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2564 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2566 return !status;
2570 /*********************************************************************
2571 * SetHandleInformation (KERNEL32.@)
2573 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2575 OBJECT_DATA_INFORMATION info;
2576 NTSTATUS status;
2578 /* if not setting both fields, retrieve current value first */
2579 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2580 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2582 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2584 SetLastError( RtlNtStatusToDosError(status) );
2585 return FALSE;
2588 if (mask & HANDLE_FLAG_INHERIT)
2589 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2590 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2591 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2593 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2594 if (status) SetLastError( RtlNtStatusToDosError(status) );
2595 return !status;
2599 /*********************************************************************
2600 * DuplicateHandle (KERNEL32.@)
2602 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2603 HANDLE dest_process, HANDLE *dest,
2604 DWORD access, BOOL inherit, DWORD options )
2606 NTSTATUS status;
2608 if (is_console_handle(source))
2610 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2611 if (source_process != dest_process ||
2612 source_process != GetCurrentProcess())
2614 SetLastError(ERROR_INVALID_PARAMETER);
2615 return FALSE;
2617 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2618 return (*dest != INVALID_HANDLE_VALUE);
2620 status = NtDuplicateObject( source_process, source, dest_process, dest,
2621 access, inherit ? OBJ_INHERIT : 0, options );
2622 if (status) SetLastError( RtlNtStatusToDosError(status) );
2623 return !status;
2627 /***********************************************************************
2628 * ConvertToGlobalHandle (KERNEL.476)
2629 * ConvertToGlobalHandle (KERNEL32.@)
2631 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2633 HANDLE ret = INVALID_HANDLE_VALUE;
2634 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2635 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2636 return ret;
2640 /***********************************************************************
2641 * SetHandleContext (KERNEL32.@)
2643 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2645 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2646 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2647 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2648 return FALSE;
2652 /***********************************************************************
2653 * GetHandleContext (KERNEL32.@)
2655 DWORD WINAPI GetHandleContext(HANDLE hnd)
2657 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2658 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2659 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2660 return 0;
2664 /***********************************************************************
2665 * CreateSocketHandle (KERNEL32.@)
2667 HANDLE WINAPI CreateSocketHandle(void)
2669 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2670 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2671 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2672 return INVALID_HANDLE_VALUE;
2676 /***********************************************************************
2677 * SetPriorityClass (KERNEL32.@)
2679 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2681 NTSTATUS status;
2682 PROCESS_PRIORITY_CLASS ppc;
2684 ppc.Foreground = FALSE;
2685 switch (priorityclass)
2687 case IDLE_PRIORITY_CLASS:
2688 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2689 case BELOW_NORMAL_PRIORITY_CLASS:
2690 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2691 case NORMAL_PRIORITY_CLASS:
2692 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2693 case ABOVE_NORMAL_PRIORITY_CLASS:
2694 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2695 case HIGH_PRIORITY_CLASS:
2696 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2697 case REALTIME_PRIORITY_CLASS:
2698 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2699 default:
2700 SetLastError(ERROR_INVALID_PARAMETER);
2701 return FALSE;
2704 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2705 &ppc, sizeof(ppc));
2707 if (status != STATUS_SUCCESS)
2709 SetLastError( RtlNtStatusToDosError(status) );
2710 return FALSE;
2712 return TRUE;
2716 /***********************************************************************
2717 * GetPriorityClass (KERNEL32.@)
2719 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2721 NTSTATUS status;
2722 PROCESS_BASIC_INFORMATION pbi;
2724 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2725 sizeof(pbi), NULL);
2726 if (status != STATUS_SUCCESS)
2728 SetLastError( RtlNtStatusToDosError(status) );
2729 return 0;
2731 switch (pbi.BasePriority)
2733 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2734 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2735 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2736 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2737 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2738 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2740 SetLastError( ERROR_INVALID_PARAMETER );
2741 return 0;
2745 /***********************************************************************
2746 * SetProcessAffinityMask (KERNEL32.@)
2748 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2750 NTSTATUS status;
2752 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2753 &affmask, sizeof(DWORD_PTR));
2754 if (!status)
2756 SetLastError( RtlNtStatusToDosError(status) );
2757 return FALSE;
2759 return TRUE;
2763 /**********************************************************************
2764 * GetProcessAffinityMask (KERNEL32.@)
2766 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2767 PDWORD_PTR lpProcessAffinityMask,
2768 PDWORD_PTR lpSystemAffinityMask )
2770 PROCESS_BASIC_INFORMATION pbi;
2771 NTSTATUS status;
2773 status = NtQueryInformationProcess(hProcess,
2774 ProcessBasicInformation,
2775 &pbi, sizeof(pbi), NULL);
2776 if (status)
2778 SetLastError( RtlNtStatusToDosError(status) );
2779 return FALSE;
2781 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2782 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2783 return TRUE;
2787 /***********************************************************************
2788 * GetProcessVersion (KERNEL32.@)
2790 DWORD WINAPI GetProcessVersion( DWORD processid )
2792 IMAGE_NT_HEADERS *nt;
2794 if (processid && processid != GetCurrentProcessId())
2796 FIXME("should use ReadProcessMemory\n");
2797 return 0;
2799 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2800 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2801 nt->OptionalHeader.MinorSubsystemVersion);
2802 return 0;
2806 /***********************************************************************
2807 * SetProcessWorkingSetSize [KERNEL32.@]
2808 * Sets the min/max working set sizes for a specified process.
2810 * PARAMS
2811 * hProcess [I] Handle to the process of interest
2812 * minset [I] Specifies minimum working set size
2813 * maxset [I] Specifies maximum working set size
2815 * RETURNS
2816 * Success: TRUE
2817 * Failure: FALSE
2819 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2820 SIZE_T maxset)
2822 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2823 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2824 /* Trim the working set to zero */
2825 /* Swap the process out of physical RAM */
2827 return TRUE;
2830 /***********************************************************************
2831 * GetProcessWorkingSetSize (KERNEL32.@)
2833 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2834 PSIZE_T maxset)
2836 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2837 /* 32 MB working set size */
2838 if (minset) *minset = 32*1024*1024;
2839 if (maxset) *maxset = 32*1024*1024;
2840 return TRUE;
2844 /***********************************************************************
2845 * SetProcessShutdownParameters (KERNEL32.@)
2847 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2849 FIXME("(%08x, %08x): partial stub.\n", level, flags);
2850 shutdown_flags = flags;
2851 shutdown_priority = level;
2852 return TRUE;
2856 /***********************************************************************
2857 * GetProcessShutdownParameters (KERNEL32.@)
2860 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2862 *lpdwLevel = shutdown_priority;
2863 *lpdwFlags = shutdown_flags;
2864 return TRUE;
2868 /***********************************************************************
2869 * GetProcessPriorityBoost (KERNEL32.@)
2871 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2873 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2875 /* Report that no boost is present.. */
2876 *pDisablePriorityBoost = FALSE;
2878 return TRUE;
2881 /***********************************************************************
2882 * SetProcessPriorityBoost (KERNEL32.@)
2884 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2886 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2887 /* Say we can do it. I doubt the program will notice that we don't. */
2888 return TRUE;
2892 /***********************************************************************
2893 * ReadProcessMemory (KERNEL32.@)
2895 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2896 SIZE_T *bytes_read )
2898 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2899 if (status) SetLastError( RtlNtStatusToDosError(status) );
2900 return !status;
2904 /***********************************************************************
2905 * WriteProcessMemory (KERNEL32.@)
2907 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2908 SIZE_T *bytes_written )
2910 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2911 if (status) SetLastError( RtlNtStatusToDosError(status) );
2912 return !status;
2916 /****************************************************************************
2917 * FlushInstructionCache (KERNEL32.@)
2919 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2921 NTSTATUS status;
2922 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2923 if (status) SetLastError( RtlNtStatusToDosError(status) );
2924 return !status;
2928 /******************************************************************
2929 * GetProcessIoCounters (KERNEL32.@)
2931 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2933 NTSTATUS status;
2935 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2936 ioc, sizeof(*ioc), NULL);
2937 if (status) SetLastError( RtlNtStatusToDosError(status) );
2938 return !status;
2941 /******************************************************************
2942 * GetProcessHandleCount (KERNEL32.@)
2944 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
2946 NTSTATUS status;
2948 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
2949 cnt, sizeof(*cnt), NULL);
2950 if (status) SetLastError( RtlNtStatusToDosError(status) );
2951 return !status;
2954 /***********************************************************************
2955 * ProcessIdToSessionId (KERNEL32.@)
2956 * This function is available on Terminal Server 4SP4 and Windows 2000
2958 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2960 /* According to MSDN, if the calling process is not in a terminal
2961 * services environment, then the sessionid returned is zero.
2963 *sessionid_ptr = 0;
2964 return TRUE;
2968 /***********************************************************************
2969 * RegisterServiceProcess (KERNEL.491)
2970 * RegisterServiceProcess (KERNEL32.@)
2972 * A service process calls this function to ensure that it continues to run
2973 * even after a user logged off.
2975 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2977 /* I don't think that Wine needs to do anything in this function */
2978 return 1; /* success */
2982 /**********************************************************************
2983 * IsWow64Process (KERNEL32.@)
2985 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
2987 ULONG pbi;
2988 NTSTATUS status;
2990 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
2992 if (status != STATUS_SUCCESS)
2994 SetLastError( RtlNtStatusToDosError( status ) );
2995 return FALSE;
2997 *Wow64Process = (pbi != 0);
2998 return TRUE;
3002 /***********************************************************************
3003 * GetCurrentProcess (KERNEL32.@)
3005 * Get a handle to the current process.
3007 * PARAMS
3008 * None.
3010 * RETURNS
3011 * A handle representing the current process.
3013 #undef GetCurrentProcess
3014 HANDLE WINAPI GetCurrentProcess(void)
3016 return (HANDLE)0xffffffff;
3019 /***********************************************************************
3020 * CmdBatNotification (KERNEL32.@)
3022 * Notifies the system that a batch file has started or finished.
3024 * PARAMS
3025 * bBatchRunning [I] TRUE if a batch file has started or
3026 * FALSE if a batch file has finished executing.
3028 * RETURNS
3029 * Unknown.
3031 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
3033 FIXME("%d\n", bBatchRunning);
3034 return FALSE;
3038 /***********************************************************************
3039 * RegisterApplicationRestart (KERNEL32.@)
3041 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
3043 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
3045 return S_OK;