kernel: Use a standard LoadLibrary call to load the main exe.
[wine/multimedia.git] / dlls / kernel / process.c
blob1a890c3295989950081cb30d894fd938f9efd2a0
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 HMODULE kernel32_handle = 0;
70 const WCHAR *DIR_Windows = NULL;
71 const WCHAR *DIR_System = NULL;
73 /* Process flags */
74 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
75 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
76 #define PDB32_DOS_PROC 0x0010 /* Dos process */
77 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
78 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
79 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
81 static const WCHAR comW[] = {'.','c','o','m',0};
82 static const WCHAR batW[] = {'.','b','a','t',0};
83 static const WCHAR pifW[] = {'.','p','i','f',0};
84 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
86 extern void SHELL_LoadRegistry(void);
89 /***********************************************************************
90 * contains_path
92 inline static int contains_path( LPCWSTR name )
94 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
98 /***********************************************************************
99 * is_special_env_var
101 * Check if an environment variable needs to be handled specially when
102 * passed through the Unix environment (i.e. prefixed with "WINE").
104 inline static int is_special_env_var( const char *var )
106 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
107 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
108 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
109 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
113 /***************************************************************************
114 * get_builtin_path
116 * Get the path of a builtin module when the native file does not exist.
118 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
120 WCHAR *file_part;
121 UINT len = strlenW( DIR_System );
123 if (contains_path( libname ))
125 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
126 filename, &file_part ) > size * sizeof(WCHAR))
127 return FALSE; /* too long */
129 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
130 return FALSE;
131 while (filename[len] == '\\') len++;
132 if (filename + len != file_part) return FALSE;
134 else
136 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
137 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
138 file_part = filename + len;
139 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
140 strcpyW( file_part, libname );
142 if (ext && !strchrW( file_part, '.' ))
144 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
145 return FALSE; /* too long */
146 strcatW( file_part, ext );
148 return TRUE;
152 /***********************************************************************
153 * open_builtin_exe_file
155 * Open an exe file for a builtin exe.
157 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
158 int test_only, int *file_exists )
160 char exename[MAX_PATH];
161 WCHAR *p;
162 UINT i, len;
164 *file_exists = 0;
165 if ((p = strrchrW( name, '/' ))) name = p + 1;
166 if ((p = strrchrW( name, '\\' ))) name = p + 1;
168 /* we don't want to depend on the current codepage here */
169 len = strlenW( name ) + 1;
170 if (len >= sizeof(exename)) return NULL;
171 for (i = 0; i < len; i++)
173 if (name[i] > 127) return NULL;
174 exename[i] = (char)name[i];
175 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
177 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
181 /***********************************************************************
182 * open_exe_file
184 * Open a specific exe file, taking load order into account.
185 * Returns the file handle or 0 for a builtin exe.
187 static HANDLE open_exe_file( const WCHAR *name )
189 enum loadorder_type loadorder[LOADORDER_NTYPES];
190 WCHAR buffer[MAX_PATH];
191 HANDLE handle;
192 int i, file_exists;
194 TRACE("looking for %s\n", debugstr_w(name) );
196 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
197 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
199 /* file doesn't exist, check for builtin */
200 if (!contains_path( name )) goto error;
201 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
202 name = buffer;
205 MODULE_GetLoadOrderW( loadorder, NULL, name );
207 for(i = 0; i < LOADORDER_NTYPES; i++)
209 if (loadorder[i] == LOADORDER_INVALID) break;
210 switch(loadorder[i])
212 case LOADORDER_DLL:
213 TRACE( "Trying native exe %s\n", debugstr_w(name) );
214 if (handle != INVALID_HANDLE_VALUE) return handle;
215 break;
216 case LOADORDER_BI:
217 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
218 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
219 if (file_exists)
221 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
222 return 0;
224 default:
225 break;
228 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
230 error:
231 SetLastError( ERROR_FILE_NOT_FOUND );
232 return INVALID_HANDLE_VALUE;
236 /***********************************************************************
237 * find_exe_file
239 * Open an exe file, and return the full name and file handle.
240 * Returns FALSE if file could not be found.
241 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
242 * If file is a builtin exe, returns TRUE and sets handle to 0.
244 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
246 static const WCHAR exeW[] = {'.','e','x','e',0};
248 enum loadorder_type loadorder[LOADORDER_NTYPES];
249 int i, file_exists;
251 TRACE("looking for %s\n", debugstr_w(name) );
253 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
254 !get_builtin_path( name, exeW, buffer, buflen ))
256 /* no builtin found, try native without extension in case it is a Unix app */
258 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
260 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
261 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
262 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
263 return TRUE;
265 return FALSE;
268 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
270 for(i = 0; i < LOADORDER_NTYPES; i++)
272 if (loadorder[i] == LOADORDER_INVALID) break;
273 switch(loadorder[i])
275 case LOADORDER_DLL:
276 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
277 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
278 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
279 return TRUE;
280 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
281 break;
282 case LOADORDER_BI:
283 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
284 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
285 if (file_exists)
287 *handle = 0;
288 return TRUE;
290 break;
291 default:
292 break;
295 SetLastError( ERROR_FILE_NOT_FOUND );
296 return FALSE;
300 /***********************************************************************
301 * build_initial_environment
303 * Build the Win32 environment from the Unix environment
305 static BOOL build_initial_environment( char **environ )
307 SIZE_T size = 1;
308 char **e;
309 WCHAR *p, *endptr;
310 void *ptr;
312 /* Compute the total size of the Unix environment */
313 for (e = environ; *e; e++)
315 if (is_special_env_var( *e )) continue;
316 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
318 size *= sizeof(WCHAR);
320 /* Now allocate the environment */
321 ptr = NULL;
322 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
323 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
324 return FALSE;
326 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
327 endptr = p + size / sizeof(WCHAR);
329 /* And fill it with the Unix environment */
330 for (e = environ; *e; e++)
332 char *str = *e;
334 /* skip Unix special variables and use the Wine variants instead */
335 if (!strncmp( str, "WINE", 4 ))
337 if (is_special_env_var( str + 4 )) str += 4;
338 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
340 else if (is_special_env_var( str )) continue; /* skip it */
342 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
343 p += strlenW(p) + 1;
345 *p = 0;
346 return TRUE;
350 /***********************************************************************
351 * set_registry_variables
353 * Set environment variables by enumerating the values of a key;
354 * helper for set_registry_environment().
355 * Note that Windows happily truncates the value if it's too big.
357 static void set_registry_variables( HANDLE hkey, ULONG type )
359 UNICODE_STRING env_name, env_value;
360 NTSTATUS status;
361 DWORD size;
362 int index;
363 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
364 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
366 for (index = 0; ; index++)
368 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
369 buffer, sizeof(buffer), &size );
370 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
371 break;
372 if (info->Type != type)
373 continue;
374 env_name.Buffer = info->Name;
375 env_name.Length = env_name.MaximumLength = info->NameLength;
376 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
377 env_value.Length = env_value.MaximumLength = info->DataLength;
378 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
379 env_value.Length--; /* don't count terminating null if any */
380 if (info->Type == REG_EXPAND_SZ)
382 WCHAR buf_expanded[1024];
383 UNICODE_STRING env_expanded;
384 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
385 env_expanded.Buffer=buf_expanded;
386 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
387 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
388 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
390 else
392 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
398 /***********************************************************************
399 * set_registry_environment
401 * Set the environment variables specified in the registry.
403 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
404 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
405 * on the order in which the variables are processed. But on Windows it
406 * does not really matter since they only use %SystemDrive% and
407 * %SystemRoot% which are predefined. But Wine defines these in the
408 * registry, so we need two passes.
410 static void set_registry_environment(void)
412 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
413 'S','y','s','t','e','m','\\',
414 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
415 'C','o','n','t','r','o','l','\\',
416 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
417 'E','n','v','i','r','o','n','m','e','n','t',0};
418 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
420 OBJECT_ATTRIBUTES attr;
421 UNICODE_STRING nameW;
422 HANDLE hkey;
424 attr.Length = sizeof(attr);
425 attr.RootDirectory = 0;
426 attr.ObjectName = &nameW;
427 attr.Attributes = 0;
428 attr.SecurityDescriptor = NULL;
429 attr.SecurityQualityOfService = NULL;
431 /* first the system environment variables */
432 RtlInitUnicodeString( &nameW, env_keyW );
433 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
435 set_registry_variables( hkey, REG_SZ );
436 set_registry_variables( hkey, REG_EXPAND_SZ );
437 NtClose( hkey );
440 /* then the ones for the current user */
441 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return;
442 RtlInitUnicodeString( &nameW, envW );
443 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
445 set_registry_variables( hkey, REG_SZ );
446 set_registry_variables( hkey, REG_EXPAND_SZ );
447 NtClose( hkey );
449 NtClose( attr.RootDirectory );
453 /***********************************************************************
454 * set_library_wargv
456 * Set the Wine library Unicode argv global variables.
458 static void set_library_wargv( char **argv )
460 int argc;
461 char *q;
462 WCHAR *p;
463 WCHAR **wargv;
464 DWORD total = 0;
466 for (argc = 0; argv[argc]; argc++)
467 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
469 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
470 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
471 p = (WCHAR *)(wargv + argc + 1);
472 for (argc = 0; argv[argc]; argc++)
474 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
475 wargv[argc] = p;
476 p += reslen;
477 total -= reslen;
479 wargv[argc] = NULL;
481 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
483 for (argc = 0; wargv[argc]; argc++)
484 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
486 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
487 q = (char *)(argv + argc + 1);
488 for (argc = 0; wargv[argc]; argc++)
490 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
491 argv[argc] = q;
492 q += reslen;
493 total -= reslen;
495 argv[argc] = NULL;
497 __wine_main_argv = argv;
498 __wine_main_wargv = wargv;
502 /***********************************************************************
503 * build_command_line
505 * Build the command line of a process from the argv array.
507 * Note that it does NOT necessarily include the file name.
508 * Sometimes we don't even have any command line options at all.
510 * We must quote and escape characters so that the argv array can be rebuilt
511 * from the command line:
512 * - spaces and tabs must be quoted
513 * 'a b' -> '"a b"'
514 * - quotes must be escaped
515 * '"' -> '\"'
516 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
517 * resulting in an odd number of '\' followed by a '"'
518 * '\"' -> '\\\"'
519 * '\\"' -> '\\\\\"'
520 * - '\'s that are not followed by a '"' can be left as is
521 * 'a\b' == 'a\b'
522 * 'a\\b' == 'a\\b'
524 static BOOL build_command_line( WCHAR **argv )
526 int len;
527 WCHAR **arg;
528 LPWSTR p;
529 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
531 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
533 len = 0;
534 for (arg = argv; *arg; arg++)
536 int has_space,bcount;
537 WCHAR* a;
539 has_space=0;
540 bcount=0;
541 a=*arg;
542 if( !*a ) has_space=1;
543 while (*a!='\0') {
544 if (*a=='\\') {
545 bcount++;
546 } else {
547 if (*a==' ' || *a=='\t') {
548 has_space=1;
549 } else if (*a=='"') {
550 /* doubling of '\' preceding a '"',
551 * plus escaping of said '"'
553 len+=2*bcount+1;
555 bcount=0;
557 a++;
559 len+=(a-*arg)+1 /* for the separating space */;
560 if (has_space)
561 len+=2; /* for the quotes */
564 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
565 return FALSE;
567 p = rupp->CommandLine.Buffer;
568 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
569 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
570 for (arg = argv; *arg; arg++)
572 int has_space,has_quote;
573 WCHAR* a;
575 /* Check for quotes and spaces in this argument */
576 has_space=has_quote=0;
577 a=*arg;
578 if( !*a ) has_space=1;
579 while (*a!='\0') {
580 if (*a==' ' || *a=='\t') {
581 has_space=1;
582 if (has_quote)
583 break;
584 } else if (*a=='"') {
585 has_quote=1;
586 if (has_space)
587 break;
589 a++;
592 /* Now transfer it to the command line */
593 if (has_space)
594 *p++='"';
595 if (has_quote) {
596 int bcount;
597 WCHAR* a;
599 bcount=0;
600 a=*arg;
601 while (*a!='\0') {
602 if (*a=='\\') {
603 *p++=*a;
604 bcount++;
605 } else {
606 if (*a=='"') {
607 int i;
609 /* Double all the '\\' preceding this '"', plus one */
610 for (i=0;i<=bcount;i++)
611 *p++='\\';
612 *p++='"';
613 } else {
614 *p++=*a;
616 bcount=0;
618 a++;
620 } else {
621 WCHAR* x = *arg;
622 while ((*p=*x++)) p++;
624 if (has_space)
625 *p++='"';
626 *p++=' ';
628 if (p > rupp->CommandLine.Buffer)
629 p--; /* remove last space */
630 *p = '\0';
632 return TRUE;
636 /* make sure the unicode string doesn't point beyond the end pointer */
637 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
639 if ((char *)str->Buffer >= end_ptr)
641 str->Length = str->MaximumLength = 0;
642 str->Buffer = NULL;
643 return;
645 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
647 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
649 if (str->Length >= str->MaximumLength)
651 if (str->MaximumLength >= sizeof(WCHAR))
652 str->Length = str->MaximumLength - sizeof(WCHAR);
653 else
654 str->Length = str->MaximumLength = 0;
658 static void version(void)
660 MESSAGE( "%s\n", PACKAGE_STRING );
661 ExitProcess(0);
664 static void usage(void)
666 MESSAGE( "%s\n", PACKAGE_STRING );
667 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
668 MESSAGE( " wine --help Display this help and exit\n");
669 MESSAGE( " wine --version Output version information and exit\n");
670 ExitProcess(0);
674 /***********************************************************************
675 * init_user_process_params
677 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
679 static BOOL init_user_process_params( RTL_USER_PROCESS_PARAMETERS *params )
681 BOOL ret;
682 void *ptr;
683 SIZE_T size, env_size, info_size;
684 HANDLE hstdin, hstdout, hstderr;
686 size = info_size = params->AllocationSize;
687 if (!size) return TRUE; /* no parameters received from parent */
689 SERVER_START_REQ( get_startup_info )
691 wine_server_set_reply( req, params, size );
692 if ((ret = !wine_server_call( req )))
694 info_size = wine_server_reply_size( reply );
695 main_exe_file = reply->exe_file;
696 hstdin = reply->hstdin;
697 hstdout = reply->hstdout;
698 hstderr = reply->hstderr;
701 SERVER_END_REQ;
702 if (!ret) return ret;
704 params->AllocationSize = size;
705 if (params->Size > info_size) params->Size = info_size;
707 /* make sure the strings are valid */
708 fix_unicode_string( &params->CurrentDirectory.DosPath, (char *)info_size );
709 fix_unicode_string( &params->DllPath, (char *)info_size );
710 fix_unicode_string( &params->ImagePathName, (char *)info_size );
711 fix_unicode_string( &params->CommandLine, (char *)info_size );
712 fix_unicode_string( &params->WindowTitle, (char *)info_size );
713 fix_unicode_string( &params->Desktop, (char *)info_size );
714 fix_unicode_string( &params->ShellInfo, (char *)info_size );
715 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
717 /* environment needs to be a separate memory block */
718 env_size = info_size - params->Size;
719 if (!env_size) env_size = 1;
720 ptr = NULL;
721 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
722 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
723 return FALSE;
724 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
725 params->Environment = ptr;
727 /* convert value from server:
728 * + 0 => INVALID_HANDLE_VALUE
729 * + console handle needs to be mapped
731 if (!hstdin)
732 hstdin = INVALID_HANDLE_VALUE;
733 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
734 hstdin = console_handle_map(hstdin);
736 if (!hstdout)
737 hstdout = INVALID_HANDLE_VALUE;
738 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
739 hstdout = console_handle_map(hstdout);
741 if (!hstderr)
742 hstderr = INVALID_HANDLE_VALUE;
743 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
744 hstderr = console_handle_map(hstderr);
746 params->hStdInput = hstdin;
747 params->hStdOutput = hstdout;
748 params->hStdError = hstderr;
750 RtlNormalizeProcessParams( params );
751 return TRUE;
755 /***********************************************************************
756 * init_current_directory
758 * Initialize the current directory from the Unix cwd or the parent info.
760 static void init_current_directory( CURDIR *cur_dir )
762 UNICODE_STRING dir_str;
763 char *cwd;
764 int size;
766 /* if we received a cur dir from the parent, try this first */
768 if (cur_dir->DosPath.Length)
770 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
773 /* now try to get it from the Unix cwd */
775 for (size = 256; ; size *= 2)
777 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
778 if (getcwd( cwd, size )) break;
779 HeapFree( GetProcessHeap(), 0, cwd );
780 if (errno == ERANGE) continue;
781 cwd = NULL;
782 break;
785 if (cwd)
787 WCHAR *dirW;
788 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
789 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
791 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
792 RtlInitUnicodeString( &dir_str, dirW );
793 RtlSetCurrentDirectory_U( &dir_str );
794 RtlFreeUnicodeString( &dir_str );
798 if (!cur_dir->DosPath.Length) /* still not initialized */
800 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
801 "starting in the Windows directory.\n", cwd ? cwd : "" );
802 RtlInitUnicodeString( &dir_str, DIR_Windows );
803 RtlSetCurrentDirectory_U( &dir_str );
805 HeapFree( GetProcessHeap(), 0, cwd );
807 done:
808 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
809 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
813 /***********************************************************************
814 * init_windows_dirs
816 * Initialize the windows and system directories from the environment.
818 static void init_windows_dirs(void)
820 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
822 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
823 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
824 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
825 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
827 DWORD len;
828 WCHAR *buffer;
830 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
832 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
833 GetEnvironmentVariableW( windirW, buffer, len );
834 DIR_Windows = buffer;
836 else DIR_Windows = default_windirW;
838 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
840 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
841 GetEnvironmentVariableW( winsysdirW, buffer, len );
842 DIR_System = buffer;
844 else
846 len = strlenW( DIR_Windows );
847 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
848 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
849 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
850 DIR_System = buffer;
853 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
854 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
855 debugstr_w(DIR_Windows) );
856 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
857 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
858 debugstr_w(DIR_System) );
860 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
861 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
863 /* set the directories in ntdll too */
864 __wine_init_windows_dir( DIR_Windows, DIR_System );
868 /***********************************************************************
869 * process_init
871 * Main process initialisation code
873 static BOOL process_init(void)
875 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
876 PEB *peb = NtCurrentTeb()->Peb;
878 PTHREAD_Init();
880 setbuf(stdout,NULL);
881 setbuf(stderr,NULL);
882 setlocale(LC_CTYPE,"");
884 if (!init_user_process_params( peb->ProcessParameters )) return FALSE;
886 kernel32_handle = GetModuleHandleW(kernel32W);
888 LOCALE_Init();
890 if (!peb->ProcessParameters->Environment)
892 /* Copy the parent environment */
893 if (!build_initial_environment( __wine_main_environ )) return FALSE;
895 /* convert old configuration to new format */
896 convert_old_config();
898 set_registry_environment();
901 init_windows_dirs();
902 init_current_directory( &peb->ProcessParameters->CurrentDirectory );
904 return TRUE;
908 /***********************************************************************
909 * init_stack
911 * Allocate the stack of new process.
913 static void *init_stack(void)
915 void *base;
916 SIZE_T stack_size, page_size = getpagesize();
917 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
919 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
920 stack_size += page_size; /* for the guard page */
921 stack_size = (stack_size + 0xffff) & ~0xffff; /* round to 64K boundary */
922 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
924 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
926 ERR( "failed to allocate main process stack\n" );
927 ExitProcess( 1 );
930 /* note: limit is lower than base since the stack grows down */
931 NtCurrentTeb()->DeallocationStack = base;
932 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
933 NtCurrentTeb()->Tib.StackLimit = (char *)base + page_size;
935 /* setup guard page */
936 VirtualProtect( base, page_size, PAGE_NOACCESS, NULL );
937 return NtCurrentTeb()->Tib.StackBase;
941 /***********************************************************************
942 * start_process
944 * Startup routine of a new process. Runs on the new process stack.
946 static void start_process( void *arg )
948 __TRY
950 PEB *peb = NtCurrentTeb()->Peb;
951 IMAGE_NT_HEADERS *nt;
952 LPTHREAD_START_ROUTINE entry;
954 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
956 nt = RtlImageNtHeader( peb->ImageBaseAddress );
957 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
958 nt->OptionalHeader.AddressOfEntryPoint);
960 if (TRACE_ON(relay))
961 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
962 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
964 SetLastError( 0 ); /* clear error code */
965 if (peb->BeingDebugged) DbgBreakPoint();
966 ExitProcess( entry( peb ) );
968 __EXCEPT(UnhandledExceptionFilter)
970 TerminateThread( GetCurrentThread(), GetExceptionCode() );
972 __ENDTRY
976 /***********************************************************************
977 * __wine_kernel_init
979 * Wine initialisation: load and start the main exe file.
981 void __wine_kernel_init(void)
983 WCHAR *main_exe_name, *p;
984 char error[1024];
985 int file_exists;
986 PEB *peb = NtCurrentTeb()->Peb;
988 /* Initialize everything */
989 if (!process_init()) exit(1);
991 __wine_main_argv++; /* remove argv[0] (wine itself) */
992 __wine_main_argc--;
994 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
996 WCHAR buffer[MAX_PATH];
997 WCHAR exe_nameW[MAX_PATH];
999 if (!__wine_main_argv[0]) usage();
1000 if (__wine_main_argc == 1)
1002 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1003 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1006 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1007 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1009 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1010 ExitProcess(1);
1012 if (main_exe_file == INVALID_HANDLE_VALUE)
1014 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1015 ExitProcess(1);
1017 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1018 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1021 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1022 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1024 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1025 MODULE_get_dll_load_path(NULL) );
1027 if (!main_exe_file) /* no file handle -> Winelib app */
1029 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1030 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ) &&
1031 NtCurrentTeb()->Peb->ImageBaseAddress)
1032 goto found;
1033 MESSAGE( "wine: cannot open builtin exe for %s: %s\n",
1034 debugstr_w(main_exe_name), error );
1035 ExitProcess(1);
1038 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1040 case BINARY_PE_EXE:
1041 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1042 peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES );
1043 CloseHandle( main_exe_file );
1044 main_exe_file = 0;
1045 if (peb->ImageBaseAddress) goto found;
1046 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1047 ExitProcess(1);
1048 case BINARY_PE_DLL:
1049 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1050 ExitProcess(1);
1051 case BINARY_UNKNOWN:
1052 /* check for .com extension */
1053 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1055 MESSAGE( "wine: cannot determine executable type for %s\n",
1056 debugstr_w(main_exe_name) );
1057 ExitProcess(1);
1059 /* fall through */
1060 case BINARY_OS216:
1061 case BINARY_WIN16:
1062 case BINARY_DOS:
1063 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1064 CloseHandle( main_exe_file );
1065 main_exe_file = 0;
1066 __wine_main_argv--;
1067 __wine_main_argc++;
1068 __wine_main_argv[0] = "winevdm.exe";
1069 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1070 goto found;
1071 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1072 debugstr_w(main_exe_name), error );
1073 ExitProcess(1);
1074 case BINARY_UNIX_EXE:
1075 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1076 ExitProcess(1);
1077 case BINARY_UNIX_LIB:
1079 char *unix_name;
1081 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1082 CloseHandle( main_exe_file );
1083 main_exe_file = 0;
1084 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1085 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1087 static const WCHAR soW[] = {'.','s','o',0};
1088 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1090 *p = 0;
1091 /* update the unicode string */
1092 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1094 HeapFree( GetProcessHeap(), 0, unix_name );
1095 goto found;
1097 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1098 ExitProcess(1);
1102 found:
1103 /* build command line */
1104 set_library_wargv( __wine_main_argv );
1105 if (!build_command_line( __wine_main_wargv )) goto error;
1107 /* switch to the new stack */
1108 wine_switch_to_stack( start_process, NULL, init_stack() );
1110 error:
1111 ExitProcess( GetLastError() );
1115 /***********************************************************************
1116 * build_argv
1118 * Build an argv array from a command-line.
1119 * 'reserved' is the number of args to reserve before the first one.
1121 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1123 int argc;
1124 char** argv;
1125 char *arg,*s,*d,*cmdline;
1126 int in_quotes,bcount,len;
1128 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1129 if (!(cmdline = malloc(len))) return NULL;
1130 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1132 argc=reserved+1;
1133 bcount=0;
1134 in_quotes=0;
1135 s=cmdline;
1136 while (1) {
1137 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1138 /* space */
1139 argc++;
1140 /* skip the remaining spaces */
1141 while (*s==' ' || *s=='\t') {
1142 s++;
1144 if (*s=='\0')
1145 break;
1146 bcount=0;
1147 continue;
1148 } else if (*s=='\\') {
1149 /* '\', count them */
1150 bcount++;
1151 } else if ((*s=='"') && ((bcount & 1)==0)) {
1152 /* unescaped '"' */
1153 in_quotes=!in_quotes;
1154 bcount=0;
1155 } else {
1156 /* a regular character */
1157 bcount=0;
1159 s++;
1161 argv=malloc(argc*sizeof(*argv));
1162 if (!argv)
1163 return NULL;
1165 arg=d=s=cmdline;
1166 bcount=0;
1167 in_quotes=0;
1168 argc=reserved;
1169 while (*s) {
1170 if ((*s==' ' || *s=='\t') && !in_quotes) {
1171 /* Close the argument and copy it */
1172 *d=0;
1173 argv[argc++]=arg;
1175 /* skip the remaining spaces */
1176 do {
1177 s++;
1178 } while (*s==' ' || *s=='\t');
1180 /* Start with a new argument */
1181 arg=d=s;
1182 bcount=0;
1183 } else if (*s=='\\') {
1184 /* '\\' */
1185 *d++=*s++;
1186 bcount++;
1187 } else if (*s=='"') {
1188 /* '"' */
1189 if ((bcount & 1)==0) {
1190 /* Preceded by an even number of '\', this is half that
1191 * number of '\', plus a '"' which we discard.
1193 d-=bcount/2;
1194 s++;
1195 in_quotes=!in_quotes;
1196 } else {
1197 /* Preceded by an odd number of '\', this is half that
1198 * number of '\' followed by a '"'
1200 d=d-bcount/2-1;
1201 *d++='"';
1202 s++;
1204 bcount=0;
1205 } else {
1206 /* a regular character */
1207 *d++=*s++;
1208 bcount=0;
1211 if (*arg) {
1212 *d='\0';
1213 argv[argc++]=arg;
1215 argv[argc]=NULL;
1217 return argv;
1221 /***********************************************************************
1222 * alloc_env_string
1224 * Allocate an environment string; helper for build_envp
1226 static char *alloc_env_string( const char *name, const char *value )
1228 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1229 strcpy( ret, name );
1230 strcat( ret, value );
1231 return ret;
1234 /***********************************************************************
1235 * build_envp
1237 * Build the environment of a new child process.
1239 static char **build_envp( const WCHAR *envW )
1241 const WCHAR *end;
1242 char **envp;
1243 char *env, *p;
1244 int count = 0, length;
1246 for (end = envW; *end; count++) end += strlenW(end) + 1;
1247 end++;
1248 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1249 if (!(env = malloc( length ))) return NULL;
1250 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1252 count += 4;
1254 if ((envp = malloc( count * sizeof(*envp) )))
1256 char **envptr = envp;
1258 /* some variables must not be modified, so we get them directly from the unix env */
1259 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1260 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1261 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1262 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1263 /* now put the Windows environment strings */
1264 for (p = env; *p; p += strlen(p) + 1)
1266 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1267 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1268 if (is_special_env_var( p )) /* prefix it with "WINE" */
1269 *envptr++ = alloc_env_string( "WINE", p );
1270 else
1271 *envptr++ = p;
1273 *envptr = 0;
1275 return envp;
1279 /***********************************************************************
1280 * fork_and_exec
1282 * Fork and exec a new Unix binary, checking for errors.
1284 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1285 const WCHAR *env, const char *newdir )
1287 int fd[2];
1288 int pid, err;
1290 if (!env) env = GetEnvironmentStringsW();
1292 if (pipe(fd) == -1)
1294 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1295 return -1;
1297 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1298 if (!(pid = fork())) /* child */
1300 char **argv = build_argv( cmdline, 0 );
1301 char **envp = build_envp( env );
1302 close( fd[0] );
1304 /* Reset signals that we previously set to SIG_IGN */
1305 signal( SIGPIPE, SIG_DFL );
1306 signal( SIGCHLD, SIG_DFL );
1308 if (newdir) chdir(newdir);
1310 if (argv && envp) execve( filename, argv, envp );
1311 err = errno;
1312 write( fd[1], &err, sizeof(err) );
1313 _exit(1);
1315 close( fd[1] );
1316 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1318 errno = err;
1319 pid = -1;
1321 if (pid == -1) FILE_SetDosError();
1322 close( fd[0] );
1323 return pid;
1327 /***********************************************************************
1328 * create_user_params
1330 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1331 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1332 const STARTUPINFOW *startup )
1334 RTL_USER_PROCESS_PARAMETERS *params;
1335 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1336 NTSTATUS status;
1337 WCHAR buffer[MAX_PATH];
1339 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1340 lstrcpynW( buffer, filename, MAX_PATH );
1341 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1342 lstrcpynW( buffer, filename, MAX_PATH );
1343 RtlInitUnicodeString( &image_str, buffer );
1345 RtlInitUnicodeString( &cmdline_str, cmdline );
1346 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1347 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1348 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1349 if (startup->lpReserved2 && startup->cbReserved2)
1351 runtime.Length = 0;
1352 runtime.MaximumLength = startup->cbReserved2;
1353 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1356 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1357 cur_dir ? &curdir_str : NULL,
1358 &cmdline_str, env,
1359 startup->lpTitle ? &title : NULL,
1360 startup->lpDesktop ? &desktop : NULL,
1361 NULL,
1362 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1363 if (status != STATUS_SUCCESS)
1365 SetLastError( RtlNtStatusToDosError(status) );
1366 return NULL;
1369 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1370 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1372 params->hStdInput = startup->hStdInput;
1373 params->hStdOutput = startup->hStdOutput;
1374 params->hStdError = startup->hStdError;
1375 params->dwX = startup->dwX;
1376 params->dwY = startup->dwY;
1377 params->dwXSize = startup->dwXSize;
1378 params->dwYSize = startup->dwYSize;
1379 params->dwXCountChars = startup->dwXCountChars;
1380 params->dwYCountChars = startup->dwYCountChars;
1381 params->dwFillAttribute = startup->dwFillAttribute;
1382 params->dwFlags = startup->dwFlags;
1383 params->wShowWindow = startup->wShowWindow;
1384 return params;
1388 /***********************************************************************
1389 * create_process
1391 * Create a new process. If hFile is a valid handle we have an exe
1392 * file, otherwise it is a Winelib app.
1394 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1395 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1396 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1397 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1398 void *res_start, void *res_end )
1400 BOOL ret, success = FALSE;
1401 HANDLE process_info;
1402 WCHAR *env_end;
1403 char *winedebug = NULL;
1404 RTL_USER_PROCESS_PARAMETERS *params;
1405 int startfd[2];
1406 int execfd[2];
1407 pid_t pid;
1408 int err;
1409 char dummy = 0;
1410 char preloader_reserve[64];
1412 if (!env) RtlAcquirePebLock();
1414 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1416 if (!env) RtlReleasePebLock();
1417 return FALSE;
1419 env_end = params->Environment;
1420 while (*env_end)
1422 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1423 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1425 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1426 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1427 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1429 env_end += strlenW(env_end) + 1;
1431 env_end++;
1433 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1434 (unsigned long)res_start, (unsigned long)res_end, 0 );
1436 /* create the synchronization pipes */
1438 if (pipe( startfd ) == -1)
1440 if (!env) RtlReleasePebLock();
1441 HeapFree( GetProcessHeap(), 0, winedebug );
1442 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1443 RtlDestroyProcessParameters( params );
1444 return FALSE;
1446 if (pipe( execfd ) == -1)
1448 if (!env) RtlReleasePebLock();
1449 HeapFree( GetProcessHeap(), 0, winedebug );
1450 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1451 close( startfd[0] );
1452 close( startfd[1] );
1453 RtlDestroyProcessParameters( params );
1454 return FALSE;
1456 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1458 /* create the child process */
1460 if (!(pid = fork())) /* child */
1462 char **argv = build_argv( cmd_line, 1 );
1464 close( startfd[1] );
1465 close( execfd[0] );
1467 /* wait for parent to tell us to start */
1468 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1470 close( startfd[0] );
1471 /* Reset signals that we previously set to SIG_IGN */
1472 signal( SIGPIPE, SIG_DFL );
1473 signal( SIGCHLD, SIG_DFL );
1475 putenv( preloader_reserve );
1476 if (winedebug) putenv( winedebug );
1477 if (unixdir) chdir(unixdir);
1479 if (argv)
1481 /* first, try for a WINELOADER environment variable */
1482 const char *loader = getenv("WINELOADER");
1483 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1484 /* now use the standard search strategy */
1485 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1487 err = errno;
1488 write( execfd[1], &err, sizeof(err) );
1489 _exit(1);
1492 /* this is the parent */
1494 close( startfd[0] );
1495 close( execfd[1] );
1496 HeapFree( GetProcessHeap(), 0, winedebug );
1497 if (pid == -1)
1499 if (!env) RtlReleasePebLock();
1500 close( startfd[1] );
1501 close( execfd[0] );
1502 FILE_SetDosError();
1503 RtlDestroyProcessParameters( params );
1504 return FALSE;
1507 /* create the process on the server side */
1509 SERVER_START_REQ( new_process )
1511 req->inherit_all = inherit;
1512 req->create_flags = flags;
1513 req->unix_pid = pid;
1514 req->exe_file = hFile;
1515 if (startup->dwFlags & STARTF_USESTDHANDLES)
1517 req->hstdin = startup->hStdInput;
1518 req->hstdout = startup->hStdOutput;
1519 req->hstderr = startup->hStdError;
1521 else
1523 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1524 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1525 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1528 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1530 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1531 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1532 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1533 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1535 else
1537 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1538 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1539 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1542 wine_server_add_data( req, params, params->Size );
1543 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1544 ret = !wine_server_call_err( req );
1545 process_info = reply->info;
1547 SERVER_END_REQ;
1549 if (!env) RtlReleasePebLock();
1550 RtlDestroyProcessParameters( params );
1551 if (!ret)
1553 close( startfd[1] );
1554 close( execfd[0] );
1555 return FALSE;
1558 /* tell child to start and wait for it to exec */
1560 write( startfd[1], &dummy, 1 );
1561 close( startfd[1] );
1563 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1565 errno = err;
1566 FILE_SetDosError();
1567 close( execfd[0] );
1568 CloseHandle( process_info );
1569 return FALSE;
1571 close( execfd[0] );
1573 /* wait for the new process info to be ready */
1575 WaitForSingleObject( process_info, INFINITE );
1576 SERVER_START_REQ( get_new_process_info )
1578 req->info = process_info;
1579 req->process_access = PROCESS_ALL_ACCESS;
1580 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1581 req->thread_access = THREAD_ALL_ACCESS;
1582 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1583 if ((ret = !wine_server_call_err( req )))
1585 info->dwProcessId = (DWORD)reply->pid;
1586 info->dwThreadId = (DWORD)reply->tid;
1587 info->hProcess = reply->phandle;
1588 info->hThread = reply->thandle;
1589 success = reply->success;
1592 SERVER_END_REQ;
1594 if (ret && !success) /* new process failed to start */
1596 DWORD exitcode;
1597 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1598 CloseHandle( info->hThread );
1599 CloseHandle( info->hProcess );
1600 ret = FALSE;
1602 CloseHandle( process_info );
1603 return ret;
1607 /***********************************************************************
1608 * create_vdm_process
1610 * Create a new VDM process for a 16-bit or DOS application.
1612 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1613 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1614 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1615 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1617 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1619 BOOL ret;
1620 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1621 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1623 if (!new_cmd_line)
1625 SetLastError( ERROR_OUTOFMEMORY );
1626 return FALSE;
1628 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1629 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1630 flags, startup, info, unixdir, NULL, NULL );
1631 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1632 return ret;
1636 /***********************************************************************
1637 * create_cmd_process
1639 * Create a new cmd shell process for a .BAT file.
1641 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1642 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1643 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1644 LPPROCESS_INFORMATION info )
1647 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1648 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1649 WCHAR comspec[MAX_PATH];
1650 WCHAR *newcmdline;
1651 BOOL ret;
1653 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1654 return FALSE;
1655 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1656 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1657 return FALSE;
1659 strcpyW( newcmdline, comspec );
1660 strcatW( newcmdline, slashcW );
1661 strcatW( newcmdline, cmd_line );
1662 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1663 flags, env, cur_dir, startup, info );
1664 HeapFree( GetProcessHeap(), 0, newcmdline );
1665 return ret;
1669 /*************************************************************************
1670 * get_file_name
1672 * Helper for CreateProcess: retrieve the file name to load from the
1673 * app name and command line. Store the file name in buffer, and
1674 * return a possibly modified command line.
1675 * Also returns a handle to the opened file if it's a Windows binary.
1677 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1678 int buflen, HANDLE *handle )
1680 static const WCHAR quotesW[] = {'"','%','s','"',0};
1682 WCHAR *name, *pos, *ret = NULL;
1683 const WCHAR *p;
1684 BOOL got_space;
1686 /* if we have an app name, everything is easy */
1688 if (appname)
1690 /* use the unmodified app name as file name */
1691 lstrcpynW( buffer, appname, buflen );
1692 *handle = open_exe_file( buffer );
1693 if (!(ret = cmdline) || !cmdline[0])
1695 /* no command-line, create one */
1696 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1697 sprintfW( ret, quotesW, appname );
1699 return ret;
1702 if (!cmdline)
1704 SetLastError( ERROR_INVALID_PARAMETER );
1705 return NULL;
1708 /* first check for a quoted file name */
1710 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1712 int len = p - cmdline - 1;
1713 /* extract the quoted portion as file name */
1714 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1715 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1716 name[len] = 0;
1718 if (find_exe_file( name, buffer, buflen, handle ))
1719 ret = cmdline; /* no change necessary */
1720 goto done;
1723 /* now try the command-line word by word */
1725 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1726 return NULL;
1727 pos = name;
1728 p = cmdline;
1729 got_space = FALSE;
1731 while (*p)
1733 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1734 *pos = 0;
1735 if (find_exe_file( name, buffer, buflen, handle ))
1737 ret = cmdline;
1738 break;
1740 if (*p) got_space = TRUE;
1743 if (ret && got_space) /* now build a new command-line with quotes */
1745 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1746 goto done;
1747 sprintfW( ret, quotesW, name );
1748 strcatW( ret, p );
1751 done:
1752 HeapFree( GetProcessHeap(), 0, name );
1753 return ret;
1757 /**********************************************************************
1758 * CreateProcessA (KERNEL32.@)
1760 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1761 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1762 DWORD flags, LPVOID env, LPCSTR cur_dir,
1763 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1765 BOOL ret = FALSE;
1766 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1767 UNICODE_STRING desktopW, titleW;
1768 STARTUPINFOW infoW;
1770 desktopW.Buffer = NULL;
1771 titleW.Buffer = NULL;
1772 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1773 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1774 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1776 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1777 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1779 memcpy( &infoW, startup_info, sizeof(infoW) );
1780 infoW.lpDesktop = desktopW.Buffer;
1781 infoW.lpTitle = titleW.Buffer;
1783 if (startup_info->lpReserved)
1784 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1785 debugstr_a(startup_info->lpReserved));
1787 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1788 inherit, flags, env, cur_dirW, &infoW, info );
1789 done:
1790 HeapFree( GetProcessHeap(), 0, app_nameW );
1791 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1792 HeapFree( GetProcessHeap(), 0, cur_dirW );
1793 RtlFreeUnicodeString( &desktopW );
1794 RtlFreeUnicodeString( &titleW );
1795 return ret;
1799 /**********************************************************************
1800 * CreateProcessW (KERNEL32.@)
1802 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1803 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1804 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1805 LPPROCESS_INFORMATION info )
1807 BOOL retv = FALSE;
1808 HANDLE hFile = 0;
1809 char *unixdir = NULL;
1810 WCHAR name[MAX_PATH];
1811 WCHAR *tidy_cmdline, *p, *envW = env;
1812 void *res_start, *res_end;
1814 /* Process the AppName and/or CmdLine to get module name and path */
1816 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1818 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1819 return FALSE;
1820 if (hFile == INVALID_HANDLE_VALUE) goto done;
1822 /* Warn if unsupported features are used */
1824 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1825 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1826 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1827 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1828 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1830 if (cur_dir)
1832 unixdir = wine_get_unix_file_name( cur_dir );
1834 else
1836 WCHAR buf[MAX_PATH];
1837 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1840 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1842 char *p = env;
1843 DWORD lenW;
1845 while (*p) p += strlen(p) + 1;
1846 p++; /* final null */
1847 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1848 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1849 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1850 flags |= CREATE_UNICODE_ENVIRONMENT;
1853 info->hThread = info->hProcess = 0;
1854 info->dwProcessId = info->dwThreadId = 0;
1856 /* Determine executable type */
1858 if (!hFile) /* builtin exe */
1860 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1861 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1862 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1863 goto done;
1866 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1868 case BINARY_PE_EXE:
1869 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1870 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1871 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1872 break;
1873 case BINARY_OS216:
1874 case BINARY_WIN16:
1875 case BINARY_DOS:
1876 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1877 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1878 inherit, flags, startup_info, info, unixdir );
1879 break;
1880 case BINARY_PE_DLL:
1881 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1882 SetLastError( ERROR_BAD_EXE_FORMAT );
1883 break;
1884 case BINARY_UNIX_LIB:
1885 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1886 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1887 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1888 break;
1889 case BINARY_UNKNOWN:
1890 /* check for .com or .bat extension */
1891 if ((p = strrchrW( name, '.' )))
1893 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1895 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1896 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1897 inherit, flags, startup_info, info, unixdir );
1898 break;
1900 if (!strcmpiW( p, batW ))
1902 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1903 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1904 inherit, flags, startup_info, info );
1905 break;
1908 /* fall through */
1909 case BINARY_UNIX_EXE:
1911 /* unknown file, try as unix executable */
1912 char *unix_name;
1914 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1916 if ((unix_name = wine_get_unix_file_name( name )))
1918 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1919 HeapFree( GetProcessHeap(), 0, unix_name );
1922 break;
1924 CloseHandle( hFile );
1926 done:
1927 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1928 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1929 HeapFree( GetProcessHeap(), 0, unixdir );
1930 return retv;
1934 /***********************************************************************
1935 * wait_input_idle
1937 * Wrapper to call WaitForInputIdle USER function
1939 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1941 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1943 HMODULE mod = GetModuleHandleA( "user32.dll" );
1944 if (mod)
1946 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1947 if (ptr) return ptr( process, timeout );
1949 return 0;
1953 /***********************************************************************
1954 * WinExec (KERNEL32.@)
1956 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1958 PROCESS_INFORMATION info;
1959 STARTUPINFOA startup;
1960 char *cmdline;
1961 UINT ret;
1963 memset( &startup, 0, sizeof(startup) );
1964 startup.cb = sizeof(startup);
1965 startup.dwFlags = STARTF_USESHOWWINDOW;
1966 startup.wShowWindow = nCmdShow;
1968 /* cmdline needs to be writeable for CreateProcess */
1969 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1970 strcpy( cmdline, lpCmdLine );
1972 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1973 0, NULL, NULL, &startup, &info ))
1975 /* Give 30 seconds to the app to come up */
1976 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1977 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1978 ret = 33;
1979 /* Close off the handles */
1980 CloseHandle( info.hThread );
1981 CloseHandle( info.hProcess );
1983 else if ((ret = GetLastError()) >= 32)
1985 FIXME("Strange error set by CreateProcess: %d\n", ret );
1986 ret = 11;
1988 HeapFree( GetProcessHeap(), 0, cmdline );
1989 return ret;
1993 /**********************************************************************
1994 * LoadModule (KERNEL32.@)
1996 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1998 LOADPARMS32 *params = paramBlock;
1999 PROCESS_INFORMATION info;
2000 STARTUPINFOA startup;
2001 HINSTANCE hInstance;
2002 LPSTR cmdline, p;
2003 char filename[MAX_PATH];
2004 BYTE len;
2006 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2008 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2009 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2010 return (HINSTANCE)GetLastError();
2012 len = (BYTE)params->lpCmdLine[0];
2013 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2014 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2016 strcpy( cmdline, filename );
2017 p = cmdline + strlen(cmdline);
2018 *p++ = ' ';
2019 memcpy( p, params->lpCmdLine + 1, len );
2020 p[len] = 0;
2022 memset( &startup, 0, sizeof(startup) );
2023 startup.cb = sizeof(startup);
2024 if (params->lpCmdShow)
2026 startup.dwFlags = STARTF_USESHOWWINDOW;
2027 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2030 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2031 params->lpEnvAddress, NULL, &startup, &info ))
2033 /* Give 30 seconds to the app to come up */
2034 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2035 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2036 hInstance = (HINSTANCE)33;
2037 /* Close off the handles */
2038 CloseHandle( info.hThread );
2039 CloseHandle( info.hProcess );
2041 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2043 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2044 hInstance = (HINSTANCE)11;
2047 HeapFree( GetProcessHeap(), 0, cmdline );
2048 return hInstance;
2052 /******************************************************************************
2053 * TerminateProcess (KERNEL32.@)
2055 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2057 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2058 if (status) SetLastError( RtlNtStatusToDosError(status) );
2059 return !status;
2063 /***********************************************************************
2064 * ExitProcess (KERNEL32.@)
2066 void WINAPI ExitProcess( DWORD status )
2068 LdrShutdownProcess();
2069 NtTerminateProcess(GetCurrentProcess(), status);
2070 exit(status);
2074 /***********************************************************************
2075 * GetExitCodeProcess [KERNEL32.@]
2077 * Gets termination status of specified process.
2079 * PARAMS
2080 * hProcess [in] Handle to the process.
2081 * lpExitCode [out] Address to receive termination status.
2083 * RETURNS
2084 * Success: TRUE
2085 * Failure: FALSE
2087 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2089 NTSTATUS status;
2090 PROCESS_BASIC_INFORMATION pbi;
2092 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2093 sizeof(pbi), NULL);
2094 if (status == STATUS_SUCCESS)
2096 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2097 return TRUE;
2099 SetLastError( RtlNtStatusToDosError(status) );
2100 return FALSE;
2104 /***********************************************************************
2105 * SetErrorMode (KERNEL32.@)
2107 UINT WINAPI SetErrorMode( UINT mode )
2109 UINT old = process_error_mode;
2110 process_error_mode = mode;
2111 return old;
2115 /**********************************************************************
2116 * TlsAlloc [KERNEL32.@]
2118 * Allocates a thread local storage index.
2120 * RETURNS
2121 * Success: TLS index.
2122 * Failure: 0xFFFFFFFF
2124 DWORD WINAPI TlsAlloc( void )
2126 DWORD index;
2127 PEB * const peb = NtCurrentTeb()->Peb;
2129 RtlAcquirePebLock();
2130 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2131 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2132 else
2134 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2135 if (index != ~0U)
2137 if (!NtCurrentTeb()->TlsExpansionSlots &&
2138 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2139 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2141 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2142 index = ~0U;
2143 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2145 else
2147 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2148 index += TLS_MINIMUM_AVAILABLE;
2151 else SetLastError( ERROR_NO_MORE_ITEMS );
2153 RtlReleasePebLock();
2154 return index;
2158 /**********************************************************************
2159 * TlsFree [KERNEL32.@]
2161 * Releases a thread local storage index, making it available for reuse.
2163 * PARAMS
2164 * index [in] TLS index to free.
2166 * RETURNS
2167 * Success: TRUE
2168 * Failure: FALSE
2170 BOOL WINAPI TlsFree( DWORD index )
2172 BOOL ret;
2174 RtlAcquirePebLock();
2175 if (index >= TLS_MINIMUM_AVAILABLE)
2177 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2178 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2180 else
2182 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2183 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2185 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2186 else SetLastError( ERROR_INVALID_PARAMETER );
2187 RtlReleasePebLock();
2188 return TRUE;
2192 /**********************************************************************
2193 * TlsGetValue [KERNEL32.@]
2195 * Gets value in a thread's TLS slot.
2197 * PARAMS
2198 * index [in] TLS index to retrieve value for.
2200 * RETURNS
2201 * Success: Value stored in calling thread's TLS slot for index.
2202 * Failure: 0 and GetLastError() returns NO_ERROR.
2204 LPVOID WINAPI TlsGetValue( DWORD index )
2206 LPVOID ret;
2208 if (index < TLS_MINIMUM_AVAILABLE)
2210 ret = NtCurrentTeb()->TlsSlots[index];
2212 else
2214 index -= TLS_MINIMUM_AVAILABLE;
2215 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2217 SetLastError( ERROR_INVALID_PARAMETER );
2218 return NULL;
2220 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2221 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2223 SetLastError( ERROR_SUCCESS );
2224 return ret;
2228 /**********************************************************************
2229 * TlsSetValue [KERNEL32.@]
2231 * Stores a value in the thread's TLS slot.
2233 * PARAMS
2234 * index [in] TLS index to set value for.
2235 * value [in] Value to be stored.
2237 * RETURNS
2238 * Success: TRUE
2239 * Failure: FALSE
2241 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2243 if (index < TLS_MINIMUM_AVAILABLE)
2245 NtCurrentTeb()->TlsSlots[index] = value;
2247 else
2249 index -= TLS_MINIMUM_AVAILABLE;
2250 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2252 SetLastError( ERROR_INVALID_PARAMETER );
2253 return FALSE;
2255 if (!NtCurrentTeb()->TlsExpansionSlots &&
2256 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2257 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2259 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2260 return FALSE;
2262 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2264 return TRUE;
2268 /***********************************************************************
2269 * GetProcessFlags (KERNEL32.@)
2271 DWORD WINAPI GetProcessFlags( DWORD processid )
2273 IMAGE_NT_HEADERS *nt;
2274 DWORD flags = 0;
2276 if (processid && processid != GetCurrentProcessId()) return 0;
2278 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2280 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2281 flags |= PDB32_CONSOLE_PROC;
2283 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2284 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2285 return flags;
2289 /***********************************************************************
2290 * GetProcessDword (KERNEL.485)
2291 * GetProcessDword (KERNEL32.18)
2292 * 'Of course you cannot directly access Windows internal structures'
2294 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2296 DWORD x, y;
2297 STARTUPINFOW siw;
2299 TRACE("(%ld, %d)\n", dwProcessID, offset );
2301 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2303 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2304 return 0;
2307 switch ( offset )
2309 case GPD_APP_COMPAT_FLAGS:
2310 return GetAppCompatFlags16(0);
2311 case GPD_LOAD_DONE_EVENT:
2312 return 0;
2313 case GPD_HINSTANCE16:
2314 return GetTaskDS16();
2315 case GPD_WINDOWS_VERSION:
2316 return GetExeVersion16();
2317 case GPD_THDB:
2318 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2319 case GPD_PDB:
2320 return (DWORD)NtCurrentTeb()->Peb;
2321 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2322 GetStartupInfoW(&siw);
2323 return (DWORD)siw.hStdOutput;
2324 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2325 GetStartupInfoW(&siw);
2326 return (DWORD)siw.hStdInput;
2327 case GPD_STARTF_SHOWWINDOW:
2328 GetStartupInfoW(&siw);
2329 return siw.wShowWindow;
2330 case GPD_STARTF_SIZE:
2331 GetStartupInfoW(&siw);
2332 x = siw.dwXSize;
2333 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2334 y = siw.dwYSize;
2335 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2336 return MAKELONG( x, y );
2337 case GPD_STARTF_POSITION:
2338 GetStartupInfoW(&siw);
2339 x = siw.dwX;
2340 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2341 y = siw.dwY;
2342 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2343 return MAKELONG( x, y );
2344 case GPD_STARTF_FLAGS:
2345 GetStartupInfoW(&siw);
2346 return siw.dwFlags;
2347 case GPD_PARENT:
2348 return 0;
2349 case GPD_FLAGS:
2350 return GetProcessFlags(0);
2351 case GPD_USERDATA:
2352 return process_dword;
2353 default:
2354 ERR("Unknown offset %d\n", offset );
2355 return 0;
2359 /***********************************************************************
2360 * SetProcessDword (KERNEL.484)
2361 * 'Of course you cannot directly access Windows internal structures'
2363 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2365 TRACE("(%ld, %d)\n", dwProcessID, offset );
2367 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2369 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2370 return;
2373 switch ( offset )
2375 case GPD_APP_COMPAT_FLAGS:
2376 case GPD_LOAD_DONE_EVENT:
2377 case GPD_HINSTANCE16:
2378 case GPD_WINDOWS_VERSION:
2379 case GPD_THDB:
2380 case GPD_PDB:
2381 case GPD_STARTF_SHELLDATA:
2382 case GPD_STARTF_HOTKEY:
2383 case GPD_STARTF_SHOWWINDOW:
2384 case GPD_STARTF_SIZE:
2385 case GPD_STARTF_POSITION:
2386 case GPD_STARTF_FLAGS:
2387 case GPD_PARENT:
2388 case GPD_FLAGS:
2389 ERR("Not allowed to modify offset %d\n", offset );
2390 break;
2391 case GPD_USERDATA:
2392 process_dword = value;
2393 break;
2394 default:
2395 ERR("Unknown offset %d\n", offset );
2396 break;
2401 /***********************************************************************
2402 * ExitProcess (KERNEL.466)
2404 void WINAPI ExitProcess16( WORD status )
2406 DWORD count;
2407 ReleaseThunkLock( &count );
2408 ExitProcess( status );
2412 /*********************************************************************
2413 * OpenProcess (KERNEL32.@)
2415 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2417 NTSTATUS status;
2418 HANDLE handle;
2419 OBJECT_ATTRIBUTES attr;
2420 CLIENT_ID cid;
2422 cid.UniqueProcess = (HANDLE)id;
2423 cid.UniqueThread = 0; /* FIXME ? */
2425 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2426 attr.RootDirectory = NULL;
2427 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2428 attr.SecurityDescriptor = NULL;
2429 attr.SecurityQualityOfService = NULL;
2430 attr.ObjectName = NULL;
2432 status = NtOpenProcess(&handle, access, &attr, &cid);
2433 if (status != STATUS_SUCCESS)
2435 SetLastError( RtlNtStatusToDosError(status) );
2436 return NULL;
2438 return handle;
2442 /*********************************************************************
2443 * MapProcessHandle (KERNEL.483)
2444 * GetProcessId (KERNEL32.@)
2446 DWORD WINAPI GetProcessId( HANDLE hProcess )
2448 NTSTATUS status;
2449 PROCESS_BASIC_INFORMATION pbi;
2451 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2452 sizeof(pbi), NULL);
2453 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2454 SetLastError( RtlNtStatusToDosError(status) );
2455 return 0;
2459 /*********************************************************************
2460 * CloseW32Handle (KERNEL.474)
2461 * CloseHandle (KERNEL32.@)
2463 BOOL WINAPI CloseHandle( HANDLE handle )
2465 NTSTATUS status;
2467 /* stdio handles need special treatment */
2468 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2469 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2470 (handle == (HANDLE)STD_ERROR_HANDLE))
2471 handle = GetStdHandle( (DWORD)handle );
2473 if (is_console_handle(handle))
2474 return CloseConsoleHandle(handle);
2476 status = NtClose( handle );
2477 if (status) SetLastError( RtlNtStatusToDosError(status) );
2478 return !status;
2482 /*********************************************************************
2483 * GetHandleInformation (KERNEL32.@)
2485 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2487 OBJECT_DATA_INFORMATION info;
2488 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2490 if (status) SetLastError( RtlNtStatusToDosError(status) );
2491 else if (flags)
2493 *flags = 0;
2494 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2495 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2497 return !status;
2501 /*********************************************************************
2502 * SetHandleInformation (KERNEL32.@)
2504 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2506 OBJECT_DATA_INFORMATION info;
2507 NTSTATUS status;
2509 /* if not setting both fields, retrieve current value first */
2510 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2511 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2513 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2515 SetLastError( RtlNtStatusToDosError(status) );
2516 return FALSE;
2519 if (mask & HANDLE_FLAG_INHERIT)
2520 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2521 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2522 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2524 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2525 if (status) SetLastError( RtlNtStatusToDosError(status) );
2526 return !status;
2530 /*********************************************************************
2531 * DuplicateHandle (KERNEL32.@)
2533 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2534 HANDLE dest_process, HANDLE *dest,
2535 DWORD access, BOOL inherit, DWORD options )
2537 NTSTATUS status;
2539 if (is_console_handle(source))
2541 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2542 if (source_process != dest_process ||
2543 source_process != GetCurrentProcess())
2545 SetLastError(ERROR_INVALID_PARAMETER);
2546 return FALSE;
2548 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2549 return (*dest != INVALID_HANDLE_VALUE);
2551 status = NtDuplicateObject( source_process, source, dest_process, dest,
2552 access, inherit ? OBJ_INHERIT : 0, options );
2553 if (status) SetLastError( RtlNtStatusToDosError(status) );
2554 return !status;
2558 /***********************************************************************
2559 * ConvertToGlobalHandle (KERNEL.476)
2560 * ConvertToGlobalHandle (KERNEL32.@)
2562 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2564 HANDLE ret = INVALID_HANDLE_VALUE;
2565 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2566 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2567 return ret;
2571 /***********************************************************************
2572 * SetHandleContext (KERNEL32.@)
2574 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2576 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2577 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2578 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2579 return FALSE;
2583 /***********************************************************************
2584 * GetHandleContext (KERNEL32.@)
2586 DWORD WINAPI GetHandleContext(HANDLE hnd)
2588 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2589 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2590 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2591 return 0;
2595 /***********************************************************************
2596 * CreateSocketHandle (KERNEL32.@)
2598 HANDLE WINAPI CreateSocketHandle(void)
2600 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2601 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2602 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2603 return INVALID_HANDLE_VALUE;
2607 /***********************************************************************
2608 * SetPriorityClass (KERNEL32.@)
2610 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2612 NTSTATUS status;
2613 PROCESS_PRIORITY_CLASS ppc;
2615 ppc.Foreground = FALSE;
2616 switch (priorityclass)
2618 case IDLE_PRIORITY_CLASS:
2619 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2620 case BELOW_NORMAL_PRIORITY_CLASS:
2621 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2622 case NORMAL_PRIORITY_CLASS:
2623 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2624 case ABOVE_NORMAL_PRIORITY_CLASS:
2625 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2626 case HIGH_PRIORITY_CLASS:
2627 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2628 case REALTIME_PRIORITY_CLASS:
2629 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2630 default:
2631 SetLastError(ERROR_INVALID_PARAMETER);
2632 return FALSE;
2635 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2636 &ppc, sizeof(ppc));
2638 if (status != STATUS_SUCCESS)
2640 SetLastError( RtlNtStatusToDosError(status) );
2641 return FALSE;
2643 return TRUE;
2647 /***********************************************************************
2648 * GetPriorityClass (KERNEL32.@)
2650 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2652 NTSTATUS status;
2653 PROCESS_BASIC_INFORMATION pbi;
2655 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2656 sizeof(pbi), NULL);
2657 if (status != STATUS_SUCCESS)
2659 SetLastError( RtlNtStatusToDosError(status) );
2660 return 0;
2662 switch (pbi.BasePriority)
2664 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2665 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2666 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2667 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2668 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2669 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2671 SetLastError( ERROR_INVALID_PARAMETER );
2672 return 0;
2676 /***********************************************************************
2677 * SetProcessAffinityMask (KERNEL32.@)
2679 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2681 NTSTATUS status;
2683 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2684 &affmask, sizeof(DWORD_PTR));
2685 if (!status)
2687 SetLastError( RtlNtStatusToDosError(status) );
2688 return FALSE;
2690 return TRUE;
2694 /**********************************************************************
2695 * GetProcessAffinityMask (KERNEL32.@)
2697 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2698 PDWORD_PTR lpProcessAffinityMask,
2699 PDWORD_PTR lpSystemAffinityMask )
2701 PROCESS_BASIC_INFORMATION pbi;
2702 NTSTATUS status;
2704 status = NtQueryInformationProcess(hProcess,
2705 ProcessBasicInformation,
2706 &pbi, sizeof(pbi), NULL);
2707 if (status)
2709 SetLastError( RtlNtStatusToDosError(status) );
2710 return FALSE;
2712 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2713 /* FIXME */
2714 if (lpSystemAffinityMask) *lpSystemAffinityMask = 1;
2715 return TRUE;
2719 /***********************************************************************
2720 * GetProcessVersion (KERNEL32.@)
2722 DWORD WINAPI GetProcessVersion( DWORD processid )
2724 IMAGE_NT_HEADERS *nt;
2726 if (processid && processid != GetCurrentProcessId())
2728 FIXME("should use ReadProcessMemory\n");
2729 return 0;
2731 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2732 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2733 nt->OptionalHeader.MinorSubsystemVersion);
2734 return 0;
2738 /***********************************************************************
2739 * SetProcessWorkingSetSize [KERNEL32.@]
2740 * Sets the min/max working set sizes for a specified process.
2742 * PARAMS
2743 * hProcess [I] Handle to the process of interest
2744 * minset [I] Specifies minimum working set size
2745 * maxset [I] Specifies maximum working set size
2747 * RETURNS
2748 * Success: TRUE
2749 * Failure: FALSE
2751 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2752 SIZE_T maxset)
2754 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2755 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2756 /* Trim the working set to zero */
2757 /* Swap the process out of physical RAM */
2759 return TRUE;
2762 /***********************************************************************
2763 * GetProcessWorkingSetSize (KERNEL32.@)
2765 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2766 PSIZE_T maxset)
2768 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2769 /* 32 MB working set size */
2770 if (minset) *minset = 32*1024*1024;
2771 if (maxset) *maxset = 32*1024*1024;
2772 return TRUE;
2776 /***********************************************************************
2777 * SetProcessShutdownParameters (KERNEL32.@)
2779 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2781 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2782 shutdown_flags = flags;
2783 shutdown_priority = level;
2784 return TRUE;
2788 /***********************************************************************
2789 * GetProcessShutdownParameters (KERNEL32.@)
2792 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2794 *lpdwLevel = shutdown_priority;
2795 *lpdwFlags = shutdown_flags;
2796 return TRUE;
2800 /***********************************************************************
2801 * GetProcessPriorityBoost (KERNEL32.@)
2803 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2805 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2807 /* Report that no boost is present.. */
2808 *pDisablePriorityBoost = FALSE;
2810 return TRUE;
2813 /***********************************************************************
2814 * SetProcessPriorityBoost (KERNEL32.@)
2816 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2818 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2819 /* Say we can do it. I doubt the program will notice that we don't. */
2820 return TRUE;
2824 /***********************************************************************
2825 * ReadProcessMemory (KERNEL32.@)
2827 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2828 SIZE_T *bytes_read )
2830 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2831 if (status) SetLastError( RtlNtStatusToDosError(status) );
2832 return !status;
2836 /***********************************************************************
2837 * WriteProcessMemory (KERNEL32.@)
2839 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2840 SIZE_T *bytes_written )
2842 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2843 if (status) SetLastError( RtlNtStatusToDosError(status) );
2844 return !status;
2848 /****************************************************************************
2849 * FlushInstructionCache (KERNEL32.@)
2851 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2853 NTSTATUS status;
2854 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2855 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2856 if (status) SetLastError( RtlNtStatusToDosError(status) );
2857 return !status;
2861 /******************************************************************
2862 * GetProcessIoCounters (KERNEL32.@)
2864 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2866 NTSTATUS status;
2868 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2869 ioc, sizeof(*ioc), NULL);
2870 if (status) SetLastError( RtlNtStatusToDosError(status) );
2871 return !status;
2874 /***********************************************************************
2875 * ProcessIdToSessionId (KERNEL32.@)
2876 * This function is available on Terminal Server 4SP4 and Windows 2000
2878 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2880 /* According to MSDN, if the calling process is not in a terminal
2881 * services environment, then the sessionid returned is zero.
2883 *sessionid_ptr = 0;
2884 return TRUE;
2888 /***********************************************************************
2889 * RegisterServiceProcess (KERNEL.491)
2890 * RegisterServiceProcess (KERNEL32.@)
2892 * A service process calls this function to ensure that it continues to run
2893 * even after a user logged off.
2895 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2897 /* I don't think that Wine needs to do anything in this function */
2898 return 1; /* success */
2902 /***********************************************************************
2903 * GetCurrentProcess (KERNEL32.@)
2905 * Get a handle to the current process.
2907 * PARAMS
2908 * None.
2910 * RETURNS
2911 * A handle representing the current process.
2913 #undef GetCurrentProcess
2914 HANDLE WINAPI GetCurrentProcess(void)
2916 return (HANDLE)0xffffffff;