kernel: Moved main stack initialization to process.c.
[wine/wine64.git] / dlls / kernel / process.c
blobaf9e23f62b4dc512c0028ccf6d9ac30f2d5b6880
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "config.h"
22 #include "wine/port.h"
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 #include <sys/types.h>
36 #include "ntstatus.h"
37 #define WIN32_NO_STATUS
38 #include "wine/winbase16.h"
39 #include "wine/winuser16.h"
40 #include "winioctl.h"
41 #include "winternl.h"
42 #include "module.h"
43 #include "kernel_private.h"
44 #include "wine/exception.h"
45 #include "wine/server.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(process);
50 WINE_DECLARE_DEBUG_CHANNEL(file);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
53 typedef struct
55 LPSTR lpEnvAddress;
56 LPSTR lpCmdLine;
57 LPSTR lpCmdShow;
58 DWORD dwReserved;
59 } LOADPARMS32;
61 static UINT process_error_mode;
63 static HANDLE main_exe_file;
64 static DWORD shutdown_flags = 0;
65 static DWORD shutdown_priority = 0x280;
66 static DWORD process_dword;
68 int main_create_flags = 0;
69 HMODULE kernel32_handle = 0;
71 const WCHAR *DIR_Windows = NULL;
72 const WCHAR *DIR_System = NULL;
74 /* Process flags */
75 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
76 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
77 #define PDB32_DOS_PROC 0x0010 /* Dos process */
78 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
79 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
80 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
82 static const WCHAR comW[] = {'.','c','o','m',0};
83 static const WCHAR batW[] = {'.','b','a','t',0};
84 static const WCHAR pifW[] = {'.','p','i','f',0};
85 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
87 extern void SHELL_LoadRegistry(void);
90 /***********************************************************************
91 * contains_path
93 inline static int contains_path( LPCWSTR name )
95 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
99 /***********************************************************************
100 * is_special_env_var
102 * Check if an environment variable needs to be handled specially when
103 * passed through the Unix environment (i.e. prefixed with "WINE").
105 inline static int is_special_env_var( const char *var )
107 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
108 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
109 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
110 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
114 /***************************************************************************
115 * get_builtin_path
117 * Get the path of a builtin module when the native file does not exist.
119 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
121 WCHAR *file_part;
122 UINT len = strlenW( DIR_System );
124 if (contains_path( libname ))
126 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
127 filename, &file_part ) > size * sizeof(WCHAR))
128 return FALSE; /* too long */
130 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
131 return FALSE;
132 while (filename[len] == '\\') len++;
133 if (filename + len != file_part) return FALSE;
135 else
137 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
138 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
139 file_part = filename + len;
140 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
141 strcpyW( file_part, libname );
143 if (ext && !strchrW( file_part, '.' ))
145 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
146 return FALSE; /* too long */
147 strcatW( file_part, ext );
149 return TRUE;
153 /***********************************************************************
154 * open_builtin_exe_file
156 * Open an exe file for a builtin exe.
158 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
159 int test_only, int *file_exists )
161 char exename[MAX_PATH];
162 WCHAR *p;
163 UINT i, len;
165 *file_exists = 0;
166 if ((p = strrchrW( name, '/' ))) name = p + 1;
167 if ((p = strrchrW( name, '\\' ))) name = p + 1;
169 /* we don't want to depend on the current codepage here */
170 len = strlenW( name ) + 1;
171 if (len >= sizeof(exename)) return NULL;
172 for (i = 0; i < len; i++)
174 if (name[i] > 127) return NULL;
175 exename[i] = (char)name[i];
176 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
178 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
182 /***********************************************************************
183 * open_exe_file
185 * Open a specific exe file, taking load order into account.
186 * Returns the file handle or 0 for a builtin exe.
188 static HANDLE open_exe_file( const WCHAR *name )
190 enum loadorder_type loadorder[LOADORDER_NTYPES];
191 WCHAR buffer[MAX_PATH];
192 HANDLE handle;
193 int i, file_exists;
195 TRACE("looking for %s\n", debugstr_w(name) );
197 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
198 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
200 /* file doesn't exist, check for builtin */
201 if (!contains_path( name )) goto error;
202 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
203 name = buffer;
206 MODULE_GetLoadOrderW( loadorder, NULL, name );
208 for(i = 0; i < LOADORDER_NTYPES; i++)
210 if (loadorder[i] == LOADORDER_INVALID) break;
211 switch(loadorder[i])
213 case LOADORDER_DLL:
214 TRACE( "Trying native exe %s\n", debugstr_w(name) );
215 if (handle != INVALID_HANDLE_VALUE) return handle;
216 break;
217 case LOADORDER_BI:
218 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
219 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
220 if (file_exists)
222 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
223 return 0;
225 default:
226 break;
229 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
231 error:
232 SetLastError( ERROR_FILE_NOT_FOUND );
233 return INVALID_HANDLE_VALUE;
237 /***********************************************************************
238 * find_exe_file
240 * Open an exe file, and return the full name and file handle.
241 * Returns FALSE if file could not be found.
242 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
243 * If file is a builtin exe, returns TRUE and sets handle to 0.
245 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
247 static const WCHAR exeW[] = {'.','e','x','e',0};
249 enum loadorder_type loadorder[LOADORDER_NTYPES];
250 int i, file_exists;
252 TRACE("looking for %s\n", debugstr_w(name) );
254 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
255 !get_builtin_path( name, exeW, buffer, buflen ))
257 /* no builtin found, try native without extension in case it is a Unix app */
259 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
261 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
262 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
263 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
264 return TRUE;
266 return FALSE;
269 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
271 for(i = 0; i < LOADORDER_NTYPES; i++)
273 if (loadorder[i] == LOADORDER_INVALID) break;
274 switch(loadorder[i])
276 case LOADORDER_DLL:
277 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
278 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
279 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
280 return TRUE;
281 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
282 break;
283 case LOADORDER_BI:
284 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
285 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
286 if (file_exists)
288 *handle = 0;
289 return TRUE;
291 break;
292 default:
293 break;
296 SetLastError( ERROR_FILE_NOT_FOUND );
297 return FALSE;
301 /**********************************************************************
302 * load_pe_exe
304 * Load a PE format EXE file.
306 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
308 IO_STATUS_BLOCK io;
309 FILE_FS_DEVICE_INFORMATION device_info;
310 IMAGE_NT_HEADERS *nt;
311 HANDLE mapping;
312 void *module;
313 OBJECT_ATTRIBUTES attr;
314 LARGE_INTEGER size;
315 SIZE_T len = 0;
317 attr.Length = sizeof(attr);
318 attr.RootDirectory = 0;
319 attr.ObjectName = NULL;
320 attr.Attributes = 0;
321 attr.SecurityDescriptor = NULL;
322 attr.SecurityQualityOfService = NULL;
323 size.QuadPart = 0;
325 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
326 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
327 return NULL;
329 module = NULL;
330 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
331 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
332 return NULL;
334 NtClose( mapping );
336 /* virus check */
337 nt = RtlImageNtHeader( module );
338 if (nt->OptionalHeader.AddressOfEntryPoint)
340 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
341 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
342 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
343 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
346 if (NtQueryVolumeInformationFile( file, &io, &device_info, sizeof(device_info),
347 FileFsDeviceInformation ) == STATUS_SUCCESS)
349 /* don't keep the file handle open on removable media */
350 if (device_info.Characteristics & FILE_REMOVABLE_MEDIA)
352 CloseHandle( main_exe_file );
353 main_exe_file = 0;
357 return module;
360 /***********************************************************************
361 * build_initial_environment
363 * Build the Win32 environment from the Unix environment
365 static BOOL build_initial_environment( char **environ )
367 SIZE_T size = 1;
368 char **e;
369 WCHAR *p, *endptr;
370 void *ptr;
372 /* Compute the total size of the Unix environment */
373 for (e = environ; *e; e++)
375 if (is_special_env_var( *e )) continue;
376 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
378 size *= sizeof(WCHAR);
380 /* Now allocate the environment */
381 ptr = NULL;
382 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
383 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
384 return FALSE;
386 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
387 endptr = p + size / sizeof(WCHAR);
389 /* And fill it with the Unix environment */
390 for (e = environ; *e; e++)
392 char *str = *e;
394 /* skip Unix special variables and use the Wine variants instead */
395 if (!strncmp( str, "WINE", 4 ))
397 if (is_special_env_var( str + 4 )) str += 4;
398 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
400 else if (is_special_env_var( str )) continue; /* skip it */
402 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
403 p += strlenW(p) + 1;
405 *p = 0;
406 return TRUE;
410 /***********************************************************************
411 * set_registry_variables
413 * Set environment variables by enumerating the values of a key;
414 * helper for set_registry_environment().
415 * Note that Windows happily truncates the value if it's too big.
417 static void set_registry_variables( HANDLE hkey, ULONG type )
419 UNICODE_STRING env_name, env_value;
420 NTSTATUS status;
421 DWORD size;
422 int index;
423 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
424 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
426 for (index = 0; ; index++)
428 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
429 buffer, sizeof(buffer), &size );
430 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
431 break;
432 if (info->Type != type)
433 continue;
434 env_name.Buffer = info->Name;
435 env_name.Length = env_name.MaximumLength = info->NameLength;
436 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
437 env_value.Length = env_value.MaximumLength = info->DataLength;
438 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
439 env_value.Length--; /* don't count terminating null if any */
440 if (info->Type == REG_EXPAND_SZ)
442 WCHAR buf_expanded[1024];
443 UNICODE_STRING env_expanded;
444 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
445 env_expanded.Buffer=buf_expanded;
446 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
447 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
448 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
450 else
452 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
458 /***********************************************************************
459 * set_registry_environment
461 * Set the environment variables specified in the registry.
463 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
464 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
465 * on the order in which the variables are processed. But on Windows it
466 * does not really matter since they only use %SystemDrive% and
467 * %SystemRoot% which are predefined. But Wine defines these in the
468 * registry, so we need two passes.
470 static void set_registry_environment(void)
472 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
473 'S','y','s','t','e','m','\\',
474 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
475 'C','o','n','t','r','o','l','\\',
476 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
477 'E','n','v','i','r','o','n','m','e','n','t',0};
478 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
480 OBJECT_ATTRIBUTES attr;
481 UNICODE_STRING nameW;
482 HANDLE hkey;
484 attr.Length = sizeof(attr);
485 attr.RootDirectory = 0;
486 attr.ObjectName = &nameW;
487 attr.Attributes = 0;
488 attr.SecurityDescriptor = NULL;
489 attr.SecurityQualityOfService = NULL;
491 /* first the system environment variables */
492 RtlInitUnicodeString( &nameW, env_keyW );
493 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
495 set_registry_variables( hkey, REG_SZ );
496 set_registry_variables( hkey, REG_EXPAND_SZ );
497 NtClose( hkey );
500 /* then the ones for the current user */
501 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return;
502 RtlInitUnicodeString( &nameW, envW );
503 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
505 set_registry_variables( hkey, REG_SZ );
506 set_registry_variables( hkey, REG_EXPAND_SZ );
507 NtClose( hkey );
509 NtClose( attr.RootDirectory );
513 /***********************************************************************
514 * set_library_wargv
516 * Set the Wine library Unicode argv global variables.
518 static void set_library_wargv( char **argv )
520 int argc;
521 char *q;
522 WCHAR *p;
523 WCHAR **wargv;
524 DWORD total = 0;
526 for (argc = 0; argv[argc]; argc++)
527 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
529 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
530 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
531 p = (WCHAR *)(wargv + argc + 1);
532 for (argc = 0; argv[argc]; argc++)
534 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
535 wargv[argc] = p;
536 p += reslen;
537 total -= reslen;
539 wargv[argc] = NULL;
541 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
543 for (argc = 0; wargv[argc]; argc++)
544 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
546 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
547 q = (char *)(argv + argc + 1);
548 for (argc = 0; wargv[argc]; argc++)
550 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
551 argv[argc] = q;
552 q += reslen;
553 total -= reslen;
555 argv[argc] = NULL;
557 __wine_main_argv = argv;
558 __wine_main_wargv = wargv;
562 /***********************************************************************
563 * build_command_line
565 * Build the command line of a process from the argv array.
567 * Note that it does NOT necessarily include the file name.
568 * Sometimes we don't even have any command line options at all.
570 * We must quote and escape characters so that the argv array can be rebuilt
571 * from the command line:
572 * - spaces and tabs must be quoted
573 * 'a b' -> '"a b"'
574 * - quotes must be escaped
575 * '"' -> '\"'
576 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
577 * resulting in an odd number of '\' followed by a '"'
578 * '\"' -> '\\\"'
579 * '\\"' -> '\\\\\"'
580 * - '\'s that are not followed by a '"' can be left as is
581 * 'a\b' == 'a\b'
582 * 'a\\b' == 'a\\b'
584 static BOOL build_command_line( WCHAR **argv )
586 int len;
587 WCHAR **arg;
588 LPWSTR p;
589 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
591 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
593 len = 0;
594 for (arg = argv; *arg; arg++)
596 int has_space,bcount;
597 WCHAR* a;
599 has_space=0;
600 bcount=0;
601 a=*arg;
602 if( !*a ) has_space=1;
603 while (*a!='\0') {
604 if (*a=='\\') {
605 bcount++;
606 } else {
607 if (*a==' ' || *a=='\t') {
608 has_space=1;
609 } else if (*a=='"') {
610 /* doubling of '\' preceding a '"',
611 * plus escaping of said '"'
613 len+=2*bcount+1;
615 bcount=0;
617 a++;
619 len+=(a-*arg)+1 /* for the separating space */;
620 if (has_space)
621 len+=2; /* for the quotes */
624 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
625 return FALSE;
627 p = rupp->CommandLine.Buffer;
628 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
629 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
630 for (arg = argv; *arg; arg++)
632 int has_space,has_quote;
633 WCHAR* a;
635 /* Check for quotes and spaces in this argument */
636 has_space=has_quote=0;
637 a=*arg;
638 if( !*a ) has_space=1;
639 while (*a!='\0') {
640 if (*a==' ' || *a=='\t') {
641 has_space=1;
642 if (has_quote)
643 break;
644 } else if (*a=='"') {
645 has_quote=1;
646 if (has_space)
647 break;
649 a++;
652 /* Now transfer it to the command line */
653 if (has_space)
654 *p++='"';
655 if (has_quote) {
656 int bcount;
657 WCHAR* a;
659 bcount=0;
660 a=*arg;
661 while (*a!='\0') {
662 if (*a=='\\') {
663 *p++=*a;
664 bcount++;
665 } else {
666 if (*a=='"') {
667 int i;
669 /* Double all the '\\' preceding this '"', plus one */
670 for (i=0;i<=bcount;i++)
671 *p++='\\';
672 *p++='"';
673 } else {
674 *p++=*a;
676 bcount=0;
678 a++;
680 } else {
681 WCHAR* x = *arg;
682 while ((*p=*x++)) p++;
684 if (has_space)
685 *p++='"';
686 *p++=' ';
688 if (p > rupp->CommandLine.Buffer)
689 p--; /* remove last space */
690 *p = '\0';
692 return TRUE;
696 /* make sure the unicode string doesn't point beyond the end pointer */
697 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
699 if ((char *)str->Buffer >= end_ptr)
701 str->Length = str->MaximumLength = 0;
702 str->Buffer = NULL;
703 return;
705 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
707 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
709 if (str->Length >= str->MaximumLength)
711 if (str->MaximumLength >= sizeof(WCHAR))
712 str->Length = str->MaximumLength - sizeof(WCHAR);
713 else
714 str->Length = str->MaximumLength = 0;
718 static void version(void)
720 MESSAGE( "%s\n", PACKAGE_STRING );
721 ExitProcess(0);
724 static void usage(void)
726 MESSAGE( "%s\n", PACKAGE_STRING );
727 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
728 MESSAGE( " wine --help Display this help and exit\n");
729 MESSAGE( " wine --version Output version information and exit\n");
730 ExitProcess(0);
734 /***********************************************************************
735 * init_user_process_params
737 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
739 static BOOL init_user_process_params( RTL_USER_PROCESS_PARAMETERS *params )
741 BOOL ret;
742 void *ptr;
743 SIZE_T size, env_size, info_size;
744 HANDLE hstdin, hstdout, hstderr;
746 size = info_size = params->AllocationSize;
747 if (!size) return TRUE; /* no parameters received from parent */
749 SERVER_START_REQ( get_startup_info )
751 wine_server_set_reply( req, params, size );
752 if ((ret = !wine_server_call( req )))
754 info_size = wine_server_reply_size( reply );
755 main_create_flags = reply->create_flags;
756 main_exe_file = reply->exe_file;
757 hstdin = reply->hstdin;
758 hstdout = reply->hstdout;
759 hstderr = reply->hstderr;
762 SERVER_END_REQ;
763 if (!ret) return ret;
765 params->AllocationSize = size;
766 if (params->Size > info_size) params->Size = info_size;
768 /* make sure the strings are valid */
769 fix_unicode_string( &params->CurrentDirectory.DosPath, (char *)info_size );
770 fix_unicode_string( &params->DllPath, (char *)info_size );
771 fix_unicode_string( &params->ImagePathName, (char *)info_size );
772 fix_unicode_string( &params->CommandLine, (char *)info_size );
773 fix_unicode_string( &params->WindowTitle, (char *)info_size );
774 fix_unicode_string( &params->Desktop, (char *)info_size );
775 fix_unicode_string( &params->ShellInfo, (char *)info_size );
776 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
778 /* environment needs to be a separate memory block */
779 env_size = info_size - params->Size;
780 if (!env_size) env_size = 1;
781 ptr = NULL;
782 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
783 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
784 return FALSE;
785 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
786 params->Environment = ptr;
788 /* convert value from server:
789 * + 0 => INVALID_HANDLE_VALUE
790 * + console handle needs to be mapped
792 if (!hstdin)
793 hstdin = INVALID_HANDLE_VALUE;
794 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
795 hstdin = console_handle_map(hstdin);
797 if (!hstdout)
798 hstdout = INVALID_HANDLE_VALUE;
799 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
800 hstdout = console_handle_map(hstdout);
802 if (!hstderr)
803 hstderr = INVALID_HANDLE_VALUE;
804 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
805 hstderr = console_handle_map(hstderr);
807 params->hStdInput = hstdin;
808 params->hStdOutput = hstdout;
809 params->hStdError = hstderr;
811 RtlNormalizeProcessParams( params );
812 return TRUE;
816 /***********************************************************************
817 * init_current_directory
819 * Initialize the current directory from the Unix cwd or the parent info.
821 static void init_current_directory( CURDIR *cur_dir )
823 UNICODE_STRING dir_str;
824 char *cwd;
825 int size;
827 /* if we received a cur dir from the parent, try this first */
829 if (cur_dir->DosPath.Length)
831 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
834 /* now try to get it from the Unix cwd */
836 for (size = 256; ; size *= 2)
838 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
839 if (getcwd( cwd, size )) break;
840 HeapFree( GetProcessHeap(), 0, cwd );
841 if (errno == ERANGE) continue;
842 cwd = NULL;
843 break;
846 if (cwd)
848 WCHAR *dirW;
849 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
850 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
852 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
853 RtlInitUnicodeString( &dir_str, dirW );
854 RtlSetCurrentDirectory_U( &dir_str );
855 RtlFreeUnicodeString( &dir_str );
859 if (!cur_dir->DosPath.Length) /* still not initialized */
861 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
862 "starting in the Windows directory.\n", cwd ? cwd : "" );
863 RtlInitUnicodeString( &dir_str, DIR_Windows );
864 RtlSetCurrentDirectory_U( &dir_str );
866 HeapFree( GetProcessHeap(), 0, cwd );
868 done:
869 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
870 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
874 /***********************************************************************
875 * init_windows_dirs
877 * Initialize the windows and system directories from the environment.
879 static void init_windows_dirs(void)
881 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
883 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
884 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
885 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
886 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
888 DWORD len;
889 WCHAR *buffer;
891 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
893 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
894 GetEnvironmentVariableW( windirW, buffer, len );
895 DIR_Windows = buffer;
897 else DIR_Windows = default_windirW;
899 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
901 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
902 GetEnvironmentVariableW( winsysdirW, buffer, len );
903 DIR_System = buffer;
905 else
907 len = strlenW( DIR_Windows );
908 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
909 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
910 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
911 DIR_System = buffer;
914 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
915 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
916 debugstr_w(DIR_Windows) );
917 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
918 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
919 debugstr_w(DIR_System) );
921 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
922 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
924 /* set the directories in ntdll too */
925 __wine_init_windows_dir( DIR_Windows, DIR_System );
929 /***********************************************************************
930 * process_init
932 * Main process initialisation code
934 static BOOL process_init(void)
936 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
937 PEB *peb = NtCurrentTeb()->Peb;
939 PTHREAD_Init();
941 setbuf(stdout,NULL);
942 setbuf(stderr,NULL);
943 setlocale(LC_CTYPE,"");
945 if (!init_user_process_params( peb->ProcessParameters )) return FALSE;
947 kernel32_handle = GetModuleHandleW(kernel32W);
949 LOCALE_Init();
951 if (!peb->ProcessParameters->Environment)
953 /* Copy the parent environment */
954 if (!build_initial_environment( __wine_main_environ )) return FALSE;
956 /* convert old configuration to new format */
957 convert_old_config();
959 set_registry_environment();
962 init_windows_dirs();
963 init_current_directory( &peb->ProcessParameters->CurrentDirectory );
965 return TRUE;
969 /***********************************************************************
970 * init_stack
972 * Allocate the stack of new process.
974 static void *init_stack(void)
976 void *base;
977 SIZE_T stack_size, page_size = getpagesize();
978 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
980 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
981 stack_size = (stack_size + (page_size - 1)) & ~(page_size - 1);
982 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
984 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
986 ERR( "failed to allocate main process stack\n" );
987 ExitProcess( 1 );
990 /* note: limit is lower than base since the stack grows down */
991 NtCurrentTeb()->DeallocationStack = base;
992 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
993 NtCurrentTeb()->Tib.StackLimit = base;
995 /* setup guard page */
996 VirtualProtect( base, 1, PAGE_READWRITE | PAGE_GUARD, NULL );
997 return NtCurrentTeb()->Tib.StackBase;
1001 /***********************************************************************
1002 * start_process
1004 * Startup routine of a new process. Runs on the new process stack.
1006 static void start_process( void *arg )
1008 __TRY
1010 PEB *peb = NtCurrentTeb()->Peb;
1011 IMAGE_NT_HEADERS *nt;
1012 LPTHREAD_START_ROUTINE entry;
1014 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
1016 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1017 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1018 nt->OptionalHeader.AddressOfEntryPoint);
1020 if (TRACE_ON(relay))
1021 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1022 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1024 SetLastError( 0 ); /* clear error code */
1025 if (peb->BeingDebugged) DbgBreakPoint();
1026 ExitProcess( entry( peb ) );
1028 __EXCEPT(UnhandledExceptionFilter)
1030 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1032 __ENDTRY
1036 /***********************************************************************
1037 * __wine_kernel_init
1039 * Wine initialisation: load and start the main exe file.
1041 void __wine_kernel_init(void)
1043 WCHAR *main_exe_name, *p;
1044 char error[1024];
1045 int file_exists;
1046 PEB *peb = NtCurrentTeb()->Peb;
1048 /* Initialize everything */
1049 if (!process_init()) exit(1);
1051 __wine_main_argv++; /* remove argv[0] (wine itself) */
1052 __wine_main_argc--;
1054 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1056 WCHAR buffer[MAX_PATH];
1057 WCHAR exe_nameW[MAX_PATH];
1059 if (!__wine_main_argv[0]) usage();
1060 if (__wine_main_argc == 1)
1062 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1063 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1066 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1067 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1069 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1070 ExitProcess(1);
1072 if (main_exe_file == INVALID_HANDLE_VALUE)
1074 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1075 ExitProcess(1);
1077 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1078 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1081 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1082 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1084 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1085 MODULE_get_dll_load_path(NULL) );
1087 if (!main_exe_file) /* no file handle -> Winelib app */
1089 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1090 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1091 goto found;
1092 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1093 debugstr_w(main_exe_name), error );
1094 ExitProcess(1);
1097 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1099 case BINARY_PE_EXE:
1100 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1101 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1102 goto found;
1103 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1104 ExitProcess(1);
1105 case BINARY_PE_DLL:
1106 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1107 ExitProcess(1);
1108 case BINARY_UNKNOWN:
1109 /* check for .com extension */
1110 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1112 MESSAGE( "wine: cannot determine executable type for %s\n",
1113 debugstr_w(main_exe_name) );
1114 ExitProcess(1);
1116 /* fall through */
1117 case BINARY_OS216:
1118 case BINARY_WIN16:
1119 case BINARY_DOS:
1120 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1121 CloseHandle( main_exe_file );
1122 main_exe_file = 0;
1123 __wine_main_argv--;
1124 __wine_main_argc++;
1125 __wine_main_argv[0] = "winevdm.exe";
1126 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1127 goto found;
1128 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1129 debugstr_w(main_exe_name), error );
1130 ExitProcess(1);
1131 case BINARY_UNIX_EXE:
1132 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1133 ExitProcess(1);
1134 case BINARY_UNIX_LIB:
1136 char *unix_name;
1138 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1139 CloseHandle( main_exe_file );
1140 main_exe_file = 0;
1141 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1142 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1144 static const WCHAR soW[] = {'.','s','o',0};
1145 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1147 *p = 0;
1148 /* update the unicode string */
1149 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1151 HeapFree( GetProcessHeap(), 0, unix_name );
1152 goto found;
1154 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1155 ExitProcess(1);
1159 found:
1160 /* build command line */
1161 set_library_wargv( __wine_main_argv );
1162 if (!build_command_line( __wine_main_wargv )) goto error;
1164 /* switch to the new stack */
1165 wine_switch_to_stack( start_process, NULL, init_stack() );
1167 error:
1168 ExitProcess( GetLastError() );
1172 /***********************************************************************
1173 * build_argv
1175 * Build an argv array from a command-line.
1176 * 'reserved' is the number of args to reserve before the first one.
1178 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1180 int argc;
1181 char** argv;
1182 char *arg,*s,*d,*cmdline;
1183 int in_quotes,bcount,len;
1185 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1186 if (!(cmdline = malloc(len))) return NULL;
1187 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1189 argc=reserved+1;
1190 bcount=0;
1191 in_quotes=0;
1192 s=cmdline;
1193 while (1) {
1194 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1195 /* space */
1196 argc++;
1197 /* skip the remaining spaces */
1198 while (*s==' ' || *s=='\t') {
1199 s++;
1201 if (*s=='\0')
1202 break;
1203 bcount=0;
1204 continue;
1205 } else if (*s=='\\') {
1206 /* '\', count them */
1207 bcount++;
1208 } else if ((*s=='"') && ((bcount & 1)==0)) {
1209 /* unescaped '"' */
1210 in_quotes=!in_quotes;
1211 bcount=0;
1212 } else {
1213 /* a regular character */
1214 bcount=0;
1216 s++;
1218 argv=malloc(argc*sizeof(*argv));
1219 if (!argv)
1220 return NULL;
1222 arg=d=s=cmdline;
1223 bcount=0;
1224 in_quotes=0;
1225 argc=reserved;
1226 while (*s) {
1227 if ((*s==' ' || *s=='\t') && !in_quotes) {
1228 /* Close the argument and copy it */
1229 *d=0;
1230 argv[argc++]=arg;
1232 /* skip the remaining spaces */
1233 do {
1234 s++;
1235 } while (*s==' ' || *s=='\t');
1237 /* Start with a new argument */
1238 arg=d=s;
1239 bcount=0;
1240 } else if (*s=='\\') {
1241 /* '\\' */
1242 *d++=*s++;
1243 bcount++;
1244 } else if (*s=='"') {
1245 /* '"' */
1246 if ((bcount & 1)==0) {
1247 /* Preceded by an even number of '\', this is half that
1248 * number of '\', plus a '"' which we discard.
1250 d-=bcount/2;
1251 s++;
1252 in_quotes=!in_quotes;
1253 } else {
1254 /* Preceded by an odd number of '\', this is half that
1255 * number of '\' followed by a '"'
1257 d=d-bcount/2-1;
1258 *d++='"';
1259 s++;
1261 bcount=0;
1262 } else {
1263 /* a regular character */
1264 *d++=*s++;
1265 bcount=0;
1268 if (*arg) {
1269 *d='\0';
1270 argv[argc++]=arg;
1272 argv[argc]=NULL;
1274 return argv;
1278 /***********************************************************************
1279 * alloc_env_string
1281 * Allocate an environment string; helper for build_envp
1283 static char *alloc_env_string( const char *name, const char *value )
1285 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1286 strcpy( ret, name );
1287 strcat( ret, value );
1288 return ret;
1291 /***********************************************************************
1292 * build_envp
1294 * Build the environment of a new child process.
1296 static char **build_envp( const WCHAR *envW )
1298 const WCHAR *end;
1299 char **envp;
1300 char *env, *p;
1301 int count = 0, length;
1303 for (end = envW; *end; count++) end += strlenW(end) + 1;
1304 end++;
1305 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1306 if (!(env = malloc( length ))) return NULL;
1307 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1309 count += 4;
1311 if ((envp = malloc( count * sizeof(*envp) )))
1313 char **envptr = envp;
1315 /* some variables must not be modified, so we get them directly from the unix env */
1316 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1317 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1318 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1319 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1320 /* now put the Windows environment strings */
1321 for (p = env; *p; p += strlen(p) + 1)
1323 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1324 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1325 if (is_special_env_var( p )) /* prefix it with "WINE" */
1326 *envptr++ = alloc_env_string( "WINE", p );
1327 else
1328 *envptr++ = p;
1330 *envptr = 0;
1332 return envp;
1336 /***********************************************************************
1337 * fork_and_exec
1339 * Fork and exec a new Unix binary, checking for errors.
1341 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1342 const WCHAR *env, const char *newdir )
1344 int fd[2];
1345 int pid, err;
1347 if (!env) env = GetEnvironmentStringsW();
1349 if (pipe(fd) == -1)
1351 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1352 return -1;
1354 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1355 if (!(pid = fork())) /* child */
1357 char **argv = build_argv( cmdline, 0 );
1358 char **envp = build_envp( env );
1359 close( fd[0] );
1361 /* Reset signals that we previously set to SIG_IGN */
1362 signal( SIGPIPE, SIG_DFL );
1363 signal( SIGCHLD, SIG_DFL );
1365 if (newdir) chdir(newdir);
1367 if (argv && envp) execve( filename, argv, envp );
1368 err = errno;
1369 write( fd[1], &err, sizeof(err) );
1370 _exit(1);
1372 close( fd[1] );
1373 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1375 errno = err;
1376 pid = -1;
1378 if (pid == -1) FILE_SetDosError();
1379 close( fd[0] );
1380 return pid;
1384 /***********************************************************************
1385 * create_user_params
1387 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1388 LPCWSTR cur_dir, LPWSTR env,
1389 const STARTUPINFOW *startup )
1391 RTL_USER_PROCESS_PARAMETERS *params;
1392 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1393 NTSTATUS status;
1394 WCHAR buffer[MAX_PATH];
1396 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1397 lstrcpynW( buffer, filename, MAX_PATH );
1398 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1399 lstrcpynW( buffer, filename, MAX_PATH );
1400 RtlInitUnicodeString( &image_str, buffer );
1402 RtlInitUnicodeString( &cmdline_str, cmdline );
1403 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1404 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1405 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1406 if (startup->lpReserved2 && startup->cbReserved2)
1408 runtime.Length = 0;
1409 runtime.MaximumLength = startup->cbReserved2;
1410 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1413 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1414 cur_dir ? &curdir_str : NULL,
1415 &cmdline_str, env,
1416 startup->lpTitle ? &title : NULL,
1417 startup->lpDesktop ? &desktop : NULL,
1418 NULL,
1419 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1420 if (status != STATUS_SUCCESS)
1422 SetLastError( RtlNtStatusToDosError(status) );
1423 return NULL;
1426 params->hStdInput = startup->hStdInput;
1427 params->hStdOutput = startup->hStdOutput;
1428 params->hStdError = startup->hStdError;
1429 params->dwX = startup->dwX;
1430 params->dwY = startup->dwY;
1431 params->dwXSize = startup->dwXSize;
1432 params->dwYSize = startup->dwYSize;
1433 params->dwXCountChars = startup->dwXCountChars;
1434 params->dwYCountChars = startup->dwYCountChars;
1435 params->dwFillAttribute = startup->dwFillAttribute;
1436 params->dwFlags = startup->dwFlags;
1437 params->wShowWindow = startup->wShowWindow;
1438 return params;
1442 /***********************************************************************
1443 * create_process
1445 * Create a new process. If hFile is a valid handle we have an exe
1446 * file, otherwise it is a Winelib app.
1448 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1449 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1450 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1451 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1452 void *res_start, void *res_end )
1454 BOOL ret, success = FALSE;
1455 HANDLE process_info;
1456 WCHAR *env_end;
1457 char *winedebug = NULL;
1458 RTL_USER_PROCESS_PARAMETERS *params;
1459 int startfd[2];
1460 int execfd[2];
1461 pid_t pid;
1462 int err;
1463 char dummy = 0;
1464 char preloader_reserve[64];
1466 if (!env) RtlAcquirePebLock();
1468 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, startup )))
1470 if (!env) RtlReleasePebLock();
1471 return FALSE;
1473 env_end = params->Environment;
1474 while (*env_end)
1476 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1477 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1479 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1480 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1481 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1483 env_end += strlenW(env_end) + 1;
1485 env_end++;
1487 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1488 (unsigned long)res_start, (unsigned long)res_end, 0 );
1490 /* create the synchronization pipes */
1492 if (pipe( startfd ) == -1)
1494 if (!env) RtlReleasePebLock();
1495 HeapFree( GetProcessHeap(), 0, winedebug );
1496 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1497 RtlDestroyProcessParameters( params );
1498 return FALSE;
1500 if (pipe( execfd ) == -1)
1502 if (!env) RtlReleasePebLock();
1503 HeapFree( GetProcessHeap(), 0, winedebug );
1504 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1505 close( startfd[0] );
1506 close( startfd[1] );
1507 RtlDestroyProcessParameters( params );
1508 return FALSE;
1510 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1512 /* create the child process */
1514 if (!(pid = fork())) /* child */
1516 char **argv = build_argv( cmd_line, 1 );
1518 close( startfd[1] );
1519 close( execfd[0] );
1521 /* wait for parent to tell us to start */
1522 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1524 close( startfd[0] );
1525 /* Reset signals that we previously set to SIG_IGN */
1526 signal( SIGPIPE, SIG_DFL );
1527 signal( SIGCHLD, SIG_DFL );
1529 putenv( preloader_reserve );
1530 if (winedebug) putenv( winedebug );
1531 if (unixdir) chdir(unixdir);
1533 if (argv)
1535 /* first, try for a WINELOADER environment variable */
1536 const char *loader = getenv("WINELOADER");
1537 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1538 /* now use the standard search strategy */
1539 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1541 err = errno;
1542 write( execfd[1], &err, sizeof(err) );
1543 _exit(1);
1546 /* this is the parent */
1548 close( startfd[0] );
1549 close( execfd[1] );
1550 HeapFree( GetProcessHeap(), 0, winedebug );
1551 if (pid == -1)
1553 if (!env) RtlReleasePebLock();
1554 close( startfd[1] );
1555 close( execfd[0] );
1556 FILE_SetDosError();
1557 RtlDestroyProcessParameters( params );
1558 return FALSE;
1561 /* create the process on the server side */
1563 SERVER_START_REQ( new_process )
1565 req->inherit_all = inherit;
1566 req->create_flags = flags;
1567 req->unix_pid = pid;
1568 req->exe_file = hFile;
1569 if (startup->dwFlags & STARTF_USESTDHANDLES)
1571 req->hstdin = startup->hStdInput;
1572 req->hstdout = startup->hStdOutput;
1573 req->hstderr = startup->hStdError;
1575 else
1577 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1578 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1579 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1582 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1584 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1585 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1586 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1587 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1589 else
1591 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1592 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1593 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1596 wine_server_add_data( req, params, params->Size );
1597 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1598 ret = !wine_server_call_err( req );
1599 process_info = reply->info;
1601 SERVER_END_REQ;
1603 if (!env) RtlReleasePebLock();
1604 RtlDestroyProcessParameters( params );
1605 if (!ret)
1607 close( startfd[1] );
1608 close( execfd[0] );
1609 return FALSE;
1612 /* tell child to start and wait for it to exec */
1614 write( startfd[1], &dummy, 1 );
1615 close( startfd[1] );
1617 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1619 errno = err;
1620 FILE_SetDosError();
1621 close( execfd[0] );
1622 CloseHandle( process_info );
1623 return FALSE;
1625 close( execfd[0] );
1627 /* wait for the new process info to be ready */
1629 WaitForSingleObject( process_info, INFINITE );
1630 SERVER_START_REQ( get_new_process_info )
1632 req->info = process_info;
1633 req->process_access = PROCESS_ALL_ACCESS;
1634 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1635 req->thread_access = THREAD_ALL_ACCESS;
1636 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1637 if ((ret = !wine_server_call_err( req )))
1639 info->dwProcessId = (DWORD)reply->pid;
1640 info->dwThreadId = (DWORD)reply->tid;
1641 info->hProcess = reply->phandle;
1642 info->hThread = reply->thandle;
1643 success = reply->success;
1646 SERVER_END_REQ;
1648 if (ret && !success) /* new process failed to start */
1650 DWORD exitcode;
1651 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1652 CloseHandle( info->hThread );
1653 CloseHandle( info->hProcess );
1654 ret = FALSE;
1656 CloseHandle( process_info );
1657 return ret;
1661 /***********************************************************************
1662 * create_vdm_process
1664 * Create a new VDM process for a 16-bit or DOS application.
1666 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1667 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1668 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1669 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1671 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1673 BOOL ret;
1674 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1675 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1677 if (!new_cmd_line)
1679 SetLastError( ERROR_OUTOFMEMORY );
1680 return FALSE;
1682 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1683 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1684 flags, startup, info, unixdir, NULL, NULL );
1685 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1686 return ret;
1690 /***********************************************************************
1691 * create_cmd_process
1693 * Create a new cmd shell process for a .BAT file.
1695 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1696 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1697 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1698 LPPROCESS_INFORMATION info )
1701 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1702 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1703 WCHAR comspec[MAX_PATH];
1704 WCHAR *newcmdline;
1705 BOOL ret;
1707 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1708 return FALSE;
1709 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1710 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1711 return FALSE;
1713 strcpyW( newcmdline, comspec );
1714 strcatW( newcmdline, slashcW );
1715 strcatW( newcmdline, cmd_line );
1716 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1717 flags, env, cur_dir, startup, info );
1718 HeapFree( GetProcessHeap(), 0, newcmdline );
1719 return ret;
1723 /*************************************************************************
1724 * get_file_name
1726 * Helper for CreateProcess: retrieve the file name to load from the
1727 * app name and command line. Store the file name in buffer, and
1728 * return a possibly modified command line.
1729 * Also returns a handle to the opened file if it's a Windows binary.
1731 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1732 int buflen, HANDLE *handle )
1734 static const WCHAR quotesW[] = {'"','%','s','"',0};
1736 WCHAR *name, *pos, *ret = NULL;
1737 const WCHAR *p;
1739 /* if we have an app name, everything is easy */
1741 if (appname)
1743 /* use the unmodified app name as file name */
1744 lstrcpynW( buffer, appname, buflen );
1745 *handle = open_exe_file( buffer );
1746 if (!(ret = cmdline) || !cmdline[0])
1748 /* no command-line, create one */
1749 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1750 sprintfW( ret, quotesW, appname );
1752 return ret;
1755 if (!cmdline)
1757 SetLastError( ERROR_INVALID_PARAMETER );
1758 return NULL;
1761 /* first check for a quoted file name */
1763 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1765 int len = p - cmdline - 1;
1766 /* extract the quoted portion as file name */
1767 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1768 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1769 name[len] = 0;
1771 if (find_exe_file( name, buffer, buflen, handle ))
1772 ret = cmdline; /* no change necessary */
1773 goto done;
1776 /* now try the command-line word by word */
1778 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1779 return NULL;
1780 pos = name;
1781 p = cmdline;
1783 while (*p)
1785 do *pos++ = *p++; while (*p && *p != ' ');
1786 *pos = 0;
1787 if (find_exe_file( name, buffer, buflen, handle ))
1789 ret = cmdline;
1790 break;
1794 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1796 /* now build a new command-line with quotes */
1798 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1799 goto done;
1800 sprintfW( ret, quotesW, name );
1801 strcatW( ret, p );
1803 done:
1804 HeapFree( GetProcessHeap(), 0, name );
1805 return ret;
1809 /**********************************************************************
1810 * CreateProcessA (KERNEL32.@)
1812 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1813 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1814 DWORD flags, LPVOID env, LPCSTR cur_dir,
1815 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1817 BOOL ret = FALSE;
1818 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1819 UNICODE_STRING desktopW, titleW;
1820 STARTUPINFOW infoW;
1822 desktopW.Buffer = NULL;
1823 titleW.Buffer = NULL;
1824 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1825 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1826 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1828 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1829 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1831 memcpy( &infoW, startup_info, sizeof(infoW) );
1832 infoW.lpDesktop = desktopW.Buffer;
1833 infoW.lpTitle = titleW.Buffer;
1835 if (startup_info->lpReserved)
1836 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1837 debugstr_a(startup_info->lpReserved));
1839 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1840 inherit, flags, env, cur_dirW, &infoW, info );
1841 done:
1842 HeapFree( GetProcessHeap(), 0, app_nameW );
1843 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1844 HeapFree( GetProcessHeap(), 0, cur_dirW );
1845 RtlFreeUnicodeString( &desktopW );
1846 RtlFreeUnicodeString( &titleW );
1847 return ret;
1851 /**********************************************************************
1852 * CreateProcessW (KERNEL32.@)
1854 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1855 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1856 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1857 LPPROCESS_INFORMATION info )
1859 BOOL retv = FALSE;
1860 HANDLE hFile = 0;
1861 char *unixdir = NULL;
1862 WCHAR name[MAX_PATH];
1863 WCHAR *tidy_cmdline, *p, *envW = env;
1864 void *res_start, *res_end;
1866 /* Process the AppName and/or CmdLine to get module name and path */
1868 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1870 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1871 return FALSE;
1872 if (hFile == INVALID_HANDLE_VALUE) goto done;
1874 /* Warn if unsupported features are used */
1876 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1877 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1878 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1879 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1880 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1882 if (cur_dir)
1884 unixdir = wine_get_unix_file_name( cur_dir );
1886 else
1888 WCHAR buf[MAX_PATH];
1889 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1892 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1894 char *p = env;
1895 DWORD lenW;
1897 while (*p) p += strlen(p) + 1;
1898 p++; /* final null */
1899 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1900 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1901 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1902 flags |= CREATE_UNICODE_ENVIRONMENT;
1905 info->hThread = info->hProcess = 0;
1906 info->dwProcessId = info->dwThreadId = 0;
1908 /* Determine executable type */
1910 if (!hFile) /* builtin exe */
1912 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1913 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1914 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1915 goto done;
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 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1923 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1924 break;
1925 case BINARY_OS216:
1926 case BINARY_WIN16:
1927 case BINARY_DOS:
1928 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1929 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1930 inherit, flags, startup_info, info, unixdir );
1931 break;
1932 case BINARY_PE_DLL:
1933 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1934 SetLastError( ERROR_BAD_EXE_FORMAT );
1935 break;
1936 case BINARY_UNIX_LIB:
1937 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1938 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1939 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1940 break;
1941 case BINARY_UNKNOWN:
1942 /* check for .com or .bat extension */
1943 if ((p = strrchrW( name, '.' )))
1945 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1947 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1948 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1949 inherit, flags, startup_info, info, unixdir );
1950 break;
1952 if (!strcmpiW( p, batW ))
1954 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1955 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1956 inherit, flags, startup_info, info );
1957 break;
1960 /* fall through */
1961 case BINARY_UNIX_EXE:
1963 /* unknown file, try as unix executable */
1964 char *unix_name;
1966 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1968 if ((unix_name = wine_get_unix_file_name( name )))
1970 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1971 HeapFree( GetProcessHeap(), 0, unix_name );
1974 break;
1976 CloseHandle( hFile );
1978 done:
1979 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1980 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1981 HeapFree( GetProcessHeap(), 0, unixdir );
1982 return retv;
1986 /***********************************************************************
1987 * wait_input_idle
1989 * Wrapper to call WaitForInputIdle USER function
1991 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1993 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1995 HMODULE mod = GetModuleHandleA( "user32.dll" );
1996 if (mod)
1998 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1999 if (ptr) return ptr( process, timeout );
2001 return 0;
2005 /***********************************************************************
2006 * WinExec (KERNEL32.@)
2008 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2010 PROCESS_INFORMATION info;
2011 STARTUPINFOA startup;
2012 char *cmdline;
2013 UINT ret;
2015 memset( &startup, 0, sizeof(startup) );
2016 startup.cb = sizeof(startup);
2017 startup.dwFlags = STARTF_USESHOWWINDOW;
2018 startup.wShowWindow = nCmdShow;
2020 /* cmdline needs to be writeable for CreateProcess */
2021 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2022 strcpy( cmdline, lpCmdLine );
2024 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2025 0, NULL, NULL, &startup, &info ))
2027 /* Give 30 seconds to the app to come up */
2028 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2029 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2030 ret = 33;
2031 /* Close off the handles */
2032 CloseHandle( info.hThread );
2033 CloseHandle( info.hProcess );
2035 else if ((ret = GetLastError()) >= 32)
2037 FIXME("Strange error set by CreateProcess: %d\n", ret );
2038 ret = 11;
2040 HeapFree( GetProcessHeap(), 0, cmdline );
2041 return ret;
2045 /**********************************************************************
2046 * LoadModule (KERNEL32.@)
2048 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2050 LOADPARMS32 *params = paramBlock;
2051 PROCESS_INFORMATION info;
2052 STARTUPINFOA startup;
2053 HINSTANCE hInstance;
2054 LPSTR cmdline, p;
2055 char filename[MAX_PATH];
2056 BYTE len;
2058 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2060 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2061 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2062 return (HINSTANCE)GetLastError();
2064 len = (BYTE)params->lpCmdLine[0];
2065 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2066 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2068 strcpy( cmdline, filename );
2069 p = cmdline + strlen(cmdline);
2070 *p++ = ' ';
2071 memcpy( p, params->lpCmdLine + 1, len );
2072 p[len] = 0;
2074 memset( &startup, 0, sizeof(startup) );
2075 startup.cb = sizeof(startup);
2076 if (params->lpCmdShow)
2078 startup.dwFlags = STARTF_USESHOWWINDOW;
2079 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2082 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2083 params->lpEnvAddress, NULL, &startup, &info ))
2085 /* Give 30 seconds to the app to come up */
2086 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2087 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2088 hInstance = (HINSTANCE)33;
2089 /* Close off the handles */
2090 CloseHandle( info.hThread );
2091 CloseHandle( info.hProcess );
2093 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2095 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2096 hInstance = (HINSTANCE)11;
2099 HeapFree( GetProcessHeap(), 0, cmdline );
2100 return hInstance;
2104 /******************************************************************************
2105 * TerminateProcess (KERNEL32.@)
2107 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2109 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2110 if (status) SetLastError( RtlNtStatusToDosError(status) );
2111 return !status;
2115 /***********************************************************************
2116 * ExitProcess (KERNEL32.@)
2118 void WINAPI ExitProcess( DWORD status )
2120 LdrShutdownProcess();
2121 NtTerminateProcess(GetCurrentProcess(), status);
2122 exit(status);
2126 /***********************************************************************
2127 * GetExitCodeProcess [KERNEL32.@]
2129 * Gets termination status of specified process
2131 * RETURNS
2132 * Success: TRUE
2133 * Failure: FALSE
2135 BOOL WINAPI GetExitCodeProcess(
2136 HANDLE hProcess, /* [in] handle to the process */
2137 LPDWORD lpExitCode) /* [out] address to receive termination status */
2139 NTSTATUS status;
2140 PROCESS_BASIC_INFORMATION pbi;
2142 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2143 sizeof(pbi), NULL);
2144 if (status == STATUS_SUCCESS)
2146 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2147 return TRUE;
2149 SetLastError( RtlNtStatusToDosError(status) );
2150 return FALSE;
2154 /***********************************************************************
2155 * SetErrorMode (KERNEL32.@)
2157 UINT WINAPI SetErrorMode( UINT mode )
2159 UINT old = process_error_mode;
2160 process_error_mode = mode;
2161 return old;
2165 /**********************************************************************
2166 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2168 * Allocates a thread local storage index
2170 * RETURNS
2171 * Success: TLS Index
2172 * Failure: 0xFFFFFFFF
2174 DWORD WINAPI TlsAlloc( void )
2176 DWORD index;
2177 PEB * const peb = NtCurrentTeb()->Peb;
2179 RtlAcquirePebLock();
2180 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2181 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2182 else
2184 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2185 if (index != ~0U)
2187 if (!NtCurrentTeb()->TlsExpansionSlots &&
2188 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2189 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2191 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2192 index = ~0U;
2193 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2195 else
2197 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2198 index += TLS_MINIMUM_AVAILABLE;
2201 else SetLastError( ERROR_NO_MORE_ITEMS );
2203 RtlReleasePebLock();
2204 return index;
2208 /**********************************************************************
2209 * TlsFree [KERNEL32.@] Releases a TLS index.
2211 * Releases a thread local storage index, making it available for reuse
2213 * RETURNS
2214 * Success: TRUE
2215 * Failure: FALSE
2217 BOOL WINAPI TlsFree(
2218 DWORD index) /* [in] TLS Index to free */
2220 BOOL ret;
2222 RtlAcquirePebLock();
2223 if (index >= TLS_MINIMUM_AVAILABLE)
2225 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2226 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2228 else
2230 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2231 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2233 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2234 else SetLastError( ERROR_INVALID_PARAMETER );
2235 RtlReleasePebLock();
2236 return TRUE;
2240 /**********************************************************************
2241 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2243 * RETURNS
2244 * Success: Value stored in calling thread's TLS slot for index
2245 * Failure: 0 and GetLastError() returns NO_ERROR
2247 LPVOID WINAPI TlsGetValue(
2248 DWORD index) /* [in] TLS index to retrieve value for */
2250 LPVOID ret;
2252 if (index < TLS_MINIMUM_AVAILABLE)
2254 ret = NtCurrentTeb()->TlsSlots[index];
2256 else
2258 index -= TLS_MINIMUM_AVAILABLE;
2259 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2261 SetLastError( ERROR_INVALID_PARAMETER );
2262 return NULL;
2264 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2265 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2267 SetLastError( ERROR_SUCCESS );
2268 return ret;
2272 /**********************************************************************
2273 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2275 * RETURNS
2276 * Success: TRUE
2277 * Failure: FALSE
2279 BOOL WINAPI TlsSetValue(
2280 DWORD index, /* [in] TLS index to set value for */
2281 LPVOID value) /* [in] Value to be stored */
2283 if (index < TLS_MINIMUM_AVAILABLE)
2285 NtCurrentTeb()->TlsSlots[index] = value;
2287 else
2289 index -= TLS_MINIMUM_AVAILABLE;
2290 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2292 SetLastError( ERROR_INVALID_PARAMETER );
2293 return FALSE;
2295 if (!NtCurrentTeb()->TlsExpansionSlots &&
2296 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2297 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2299 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2300 return FALSE;
2302 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2304 return TRUE;
2308 /***********************************************************************
2309 * GetProcessFlags (KERNEL32.@)
2311 DWORD WINAPI GetProcessFlags( DWORD processid )
2313 IMAGE_NT_HEADERS *nt;
2314 DWORD flags = 0;
2316 if (processid && processid != GetCurrentProcessId()) return 0;
2318 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2320 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2321 flags |= PDB32_CONSOLE_PROC;
2323 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2324 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2325 return flags;
2329 /***********************************************************************
2330 * GetProcessDword (KERNEL.485)
2331 * GetProcessDword (KERNEL32.18)
2332 * 'Of course you cannot directly access Windows internal structures'
2334 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2336 DWORD x, y;
2337 STARTUPINFOW siw;
2339 TRACE("(%ld, %d)\n", dwProcessID, offset );
2341 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2343 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2344 return 0;
2347 switch ( offset )
2349 case GPD_APP_COMPAT_FLAGS:
2350 return GetAppCompatFlags16(0);
2351 case GPD_LOAD_DONE_EVENT:
2352 return 0;
2353 case GPD_HINSTANCE16:
2354 return GetTaskDS16();
2355 case GPD_WINDOWS_VERSION:
2356 return GetExeVersion16();
2357 case GPD_THDB:
2358 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2359 case GPD_PDB:
2360 return (DWORD)NtCurrentTeb()->Peb;
2361 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2362 GetStartupInfoW(&siw);
2363 return (DWORD)siw.hStdOutput;
2364 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2365 GetStartupInfoW(&siw);
2366 return (DWORD)siw.hStdInput;
2367 case GPD_STARTF_SHOWWINDOW:
2368 GetStartupInfoW(&siw);
2369 return siw.wShowWindow;
2370 case GPD_STARTF_SIZE:
2371 GetStartupInfoW(&siw);
2372 x = siw.dwXSize;
2373 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2374 y = siw.dwYSize;
2375 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2376 return MAKELONG( x, y );
2377 case GPD_STARTF_POSITION:
2378 GetStartupInfoW(&siw);
2379 x = siw.dwX;
2380 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2381 y = siw.dwY;
2382 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2383 return MAKELONG( x, y );
2384 case GPD_STARTF_FLAGS:
2385 GetStartupInfoW(&siw);
2386 return siw.dwFlags;
2387 case GPD_PARENT:
2388 return 0;
2389 case GPD_FLAGS:
2390 return GetProcessFlags(0);
2391 case GPD_USERDATA:
2392 return process_dword;
2393 default:
2394 ERR("Unknown offset %d\n", offset );
2395 return 0;
2399 /***********************************************************************
2400 * SetProcessDword (KERNEL.484)
2401 * 'Of course you cannot directly access Windows internal structures'
2403 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2405 TRACE("(%ld, %d)\n", dwProcessID, offset );
2407 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2409 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2410 return;
2413 switch ( offset )
2415 case GPD_APP_COMPAT_FLAGS:
2416 case GPD_LOAD_DONE_EVENT:
2417 case GPD_HINSTANCE16:
2418 case GPD_WINDOWS_VERSION:
2419 case GPD_THDB:
2420 case GPD_PDB:
2421 case GPD_STARTF_SHELLDATA:
2422 case GPD_STARTF_HOTKEY:
2423 case GPD_STARTF_SHOWWINDOW:
2424 case GPD_STARTF_SIZE:
2425 case GPD_STARTF_POSITION:
2426 case GPD_STARTF_FLAGS:
2427 case GPD_PARENT:
2428 case GPD_FLAGS:
2429 ERR("Not allowed to modify offset %d\n", offset );
2430 break;
2431 case GPD_USERDATA:
2432 process_dword = value;
2433 break;
2434 default:
2435 ERR("Unknown offset %d\n", offset );
2436 break;
2441 /***********************************************************************
2442 * ExitProcess (KERNEL.466)
2444 void WINAPI ExitProcess16( WORD status )
2446 DWORD count;
2447 ReleaseThunkLock( &count );
2448 ExitProcess( status );
2452 /*********************************************************************
2453 * OpenProcess (KERNEL32.@)
2455 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2457 NTSTATUS status;
2458 HANDLE handle;
2459 OBJECT_ATTRIBUTES attr;
2460 CLIENT_ID cid;
2462 cid.UniqueProcess = (HANDLE)id;
2463 cid.UniqueThread = 0; /* FIXME ? */
2465 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2466 attr.RootDirectory = NULL;
2467 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2468 attr.SecurityDescriptor = NULL;
2469 attr.SecurityQualityOfService = NULL;
2470 attr.ObjectName = NULL;
2472 status = NtOpenProcess(&handle, access, &attr, &cid);
2473 if (status != STATUS_SUCCESS)
2475 SetLastError( RtlNtStatusToDosError(status) );
2476 return NULL;
2478 return handle;
2482 /*********************************************************************
2483 * MapProcessHandle (KERNEL.483)
2484 * GetProcessId (KERNEL32.@)
2486 DWORD WINAPI GetProcessId( HANDLE hProcess )
2488 NTSTATUS status;
2489 PROCESS_BASIC_INFORMATION pbi;
2491 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2492 sizeof(pbi), NULL);
2493 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2494 SetLastError( RtlNtStatusToDosError(status) );
2495 return 0;
2499 /*********************************************************************
2500 * CloseW32Handle (KERNEL.474)
2501 * CloseHandle (KERNEL32.@)
2503 BOOL WINAPI CloseHandle( HANDLE handle )
2505 NTSTATUS status;
2507 /* stdio handles need special treatment */
2508 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2509 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2510 (handle == (HANDLE)STD_ERROR_HANDLE))
2511 handle = GetStdHandle( (DWORD)handle );
2513 if (is_console_handle(handle))
2514 return CloseConsoleHandle(handle);
2516 status = NtClose( handle );
2517 if (status) SetLastError( RtlNtStatusToDosError(status) );
2518 return !status;
2522 /*********************************************************************
2523 * GetHandleInformation (KERNEL32.@)
2525 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2527 OBJECT_DATA_INFORMATION info;
2528 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2530 if (status) SetLastError( RtlNtStatusToDosError(status) );
2531 else if (flags)
2533 *flags = 0;
2534 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2535 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2537 return !status;
2541 /*********************************************************************
2542 * SetHandleInformation (KERNEL32.@)
2544 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2546 OBJECT_DATA_INFORMATION info;
2547 NTSTATUS status;
2549 /* if not setting both fields, retrieve current value first */
2550 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2551 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2553 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2555 SetLastError( RtlNtStatusToDosError(status) );
2556 return FALSE;
2559 if (mask & HANDLE_FLAG_INHERIT)
2560 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2561 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2562 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2564 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2565 if (status) SetLastError( RtlNtStatusToDosError(status) );
2566 return !status;
2570 /*********************************************************************
2571 * DuplicateHandle (KERNEL32.@)
2573 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2574 HANDLE dest_process, HANDLE *dest,
2575 DWORD access, BOOL inherit, DWORD options )
2577 NTSTATUS status;
2579 if (is_console_handle(source))
2581 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2582 if (source_process != dest_process ||
2583 source_process != GetCurrentProcess())
2585 SetLastError(ERROR_INVALID_PARAMETER);
2586 return FALSE;
2588 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2589 return (*dest != INVALID_HANDLE_VALUE);
2591 status = NtDuplicateObject( source_process, source, dest_process, dest,
2592 access, inherit ? OBJ_INHERIT : 0, options );
2593 if (status) SetLastError( RtlNtStatusToDosError(status) );
2594 return !status;
2598 /***********************************************************************
2599 * ConvertToGlobalHandle (KERNEL.476)
2600 * ConvertToGlobalHandle (KERNEL32.@)
2602 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2604 HANDLE ret = INVALID_HANDLE_VALUE;
2605 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2606 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2607 return ret;
2611 /***********************************************************************
2612 * SetHandleContext (KERNEL32.@)
2614 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2616 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2617 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2618 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2619 return FALSE;
2623 /***********************************************************************
2624 * GetHandleContext (KERNEL32.@)
2626 DWORD WINAPI GetHandleContext(HANDLE hnd)
2628 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2629 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2630 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2631 return 0;
2635 /***********************************************************************
2636 * CreateSocketHandle (KERNEL32.@)
2638 HANDLE WINAPI CreateSocketHandle(void)
2640 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2641 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2642 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2643 return INVALID_HANDLE_VALUE;
2647 /***********************************************************************
2648 * SetPriorityClass (KERNEL32.@)
2650 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2652 NTSTATUS status;
2653 PROCESS_PRIORITY_CLASS ppc;
2655 ppc.Foreground = FALSE;
2656 switch (priorityclass)
2658 case IDLE_PRIORITY_CLASS:
2659 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2660 case BELOW_NORMAL_PRIORITY_CLASS:
2661 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2662 case NORMAL_PRIORITY_CLASS:
2663 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2664 case ABOVE_NORMAL_PRIORITY_CLASS:
2665 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2666 case HIGH_PRIORITY_CLASS:
2667 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2668 case REALTIME_PRIORITY_CLASS:
2669 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2670 default:
2671 SetLastError(ERROR_INVALID_PARAMETER);
2672 return FALSE;
2675 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2676 &ppc, sizeof(ppc));
2678 if (status != STATUS_SUCCESS)
2680 SetLastError( RtlNtStatusToDosError(status) );
2681 return FALSE;
2683 return TRUE;
2687 /***********************************************************************
2688 * GetPriorityClass (KERNEL32.@)
2690 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2692 NTSTATUS status;
2693 PROCESS_BASIC_INFORMATION pbi;
2695 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2696 sizeof(pbi), NULL);
2697 if (status != STATUS_SUCCESS)
2699 SetLastError( RtlNtStatusToDosError(status) );
2700 return 0;
2702 switch (pbi.BasePriority)
2704 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2705 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2706 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2707 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2708 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2709 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2711 SetLastError( ERROR_INVALID_PARAMETER );
2712 return 0;
2716 /***********************************************************************
2717 * SetProcessAffinityMask (KERNEL32.@)
2719 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2721 NTSTATUS status;
2723 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2724 &affmask, sizeof(DWORD_PTR));
2725 if (!status)
2727 SetLastError( RtlNtStatusToDosError(status) );
2728 return FALSE;
2730 return TRUE;
2734 /**********************************************************************
2735 * GetProcessAffinityMask (KERNEL32.@)
2737 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2738 PDWORD_PTR lpProcessAffinityMask,
2739 PDWORD_PTR lpSystemAffinityMask )
2741 PROCESS_BASIC_INFORMATION pbi;
2742 NTSTATUS status;
2744 status = NtQueryInformationProcess(hProcess,
2745 ProcessBasicInformation,
2746 &pbi, sizeof(pbi), NULL);
2747 if (status)
2749 SetLastError( RtlNtStatusToDosError(status) );
2750 return FALSE;
2752 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2753 /* FIXME */
2754 if (lpSystemAffinityMask) *lpSystemAffinityMask = 1;
2755 return TRUE;
2759 /***********************************************************************
2760 * GetProcessVersion (KERNEL32.@)
2762 DWORD WINAPI GetProcessVersion( DWORD processid )
2764 IMAGE_NT_HEADERS *nt;
2766 if (processid && processid != GetCurrentProcessId())
2768 FIXME("should use ReadProcessMemory\n");
2769 return 0;
2771 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2772 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2773 nt->OptionalHeader.MinorSubsystemVersion);
2774 return 0;
2778 /***********************************************************************
2779 * SetProcessWorkingSetSize [KERNEL32.@]
2780 * Sets the min/max working set sizes for a specified process.
2782 * PARAMS
2783 * hProcess [I] Handle to the process of interest
2784 * minset [I] Specifies minimum working set size
2785 * maxset [I] Specifies maximum working set size
2787 * RETURNS
2788 * Success: TRUE
2789 * Failure: FALSE
2791 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2792 SIZE_T maxset)
2794 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2795 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2796 /* Trim the working set to zero */
2797 /* Swap the process out of physical RAM */
2799 return TRUE;
2802 /***********************************************************************
2803 * GetProcessWorkingSetSize (KERNEL32.@)
2805 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2806 PSIZE_T maxset)
2808 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2809 /* 32 MB working set size */
2810 if (minset) *minset = 32*1024*1024;
2811 if (maxset) *maxset = 32*1024*1024;
2812 return TRUE;
2816 /***********************************************************************
2817 * SetProcessShutdownParameters (KERNEL32.@)
2819 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2821 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2822 shutdown_flags = flags;
2823 shutdown_priority = level;
2824 return TRUE;
2828 /***********************************************************************
2829 * GetProcessShutdownParameters (KERNEL32.@)
2832 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2834 *lpdwLevel = shutdown_priority;
2835 *lpdwFlags = shutdown_flags;
2836 return TRUE;
2840 /***********************************************************************
2841 * GetProcessPriorityBoost (KERNEL32.@)
2843 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2845 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2847 /* Report that no boost is present.. */
2848 *pDisablePriorityBoost = FALSE;
2850 return TRUE;
2853 /***********************************************************************
2854 * SetProcessPriorityBoost (KERNEL32.@)
2856 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2858 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2859 /* Say we can do it. I doubt the program will notice that we don't. */
2860 return TRUE;
2864 /***********************************************************************
2865 * ReadProcessMemory (KERNEL32.@)
2867 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2868 SIZE_T *bytes_read )
2870 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2871 if (status) SetLastError( RtlNtStatusToDosError(status) );
2872 return !status;
2876 /***********************************************************************
2877 * WriteProcessMemory (KERNEL32.@)
2879 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2880 SIZE_T *bytes_written )
2882 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2883 if (status) SetLastError( RtlNtStatusToDosError(status) );
2884 return !status;
2888 /****************************************************************************
2889 * FlushInstructionCache (KERNEL32.@)
2891 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2893 NTSTATUS status;
2894 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2895 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2896 if (status) SetLastError( RtlNtStatusToDosError(status) );
2897 return !status;
2901 /******************************************************************
2902 * GetProcessIoCounters (KERNEL32.@)
2904 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2906 NTSTATUS status;
2908 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2909 ioc, sizeof(*ioc), NULL);
2910 if (status) SetLastError( RtlNtStatusToDosError(status) );
2911 return !status;
2914 /***********************************************************************
2915 * ProcessIdToSessionId (KERNEL32.@)
2916 * This function is available on Terminal Server 4SP4 and Windows 2000
2918 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2920 /* According to MSDN, if the calling process is not in a terminal
2921 * services environment, then the sessionid returned is zero.
2923 *sessionid_ptr = 0;
2924 return TRUE;
2928 /***********************************************************************
2929 * RegisterServiceProcess (KERNEL.491)
2930 * RegisterServiceProcess (KERNEL32.@)
2932 * A service process calls this function to ensure that it continues to run
2933 * even after a user logged off.
2935 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2937 /* I don't think that Wine needs to do anything in this function */
2938 return 1; /* success */
2942 /***********************************************************************
2943 * GetCurrentProcess (KERNEL32.@)
2945 * Get a handle to the current process.
2947 * PARAMS
2948 * None.
2950 * RETURNS
2951 * A handle representing the current process.
2953 #undef GetCurrentProcess
2954 HANDLE WINAPI GetCurrentProcess(void)
2956 return (HANDLE)0xffffffff;