qmgr: Implement Skip and Reset for IEnumBackgroundCopyFiles.
[wine.git] / dlls / kernel32 / process.c
blobb3bf535d6f7795c43285a91221aa5b75d63728e0
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <time.h>
30 #ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
32 #endif
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
35 #endif
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
38 #endif
39 #ifdef HAVE_SYS_PRCTL_H
40 # include <sys/prctl.h>
41 #endif
42 #include <sys/types.h>
44 #include "ntstatus.h"
45 #define WIN32_NO_STATUS
46 #include "wine/winbase16.h"
47 #include "wine/winuser16.h"
48 #include "winternl.h"
49 #include "kernel_private.h"
50 #include "wine/exception.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 #ifdef HAVE_VALGRIND_MEMCHECK_H
56 #include <valgrind/memcheck.h>
57 #endif
59 WINE_DEFAULT_DEBUG_CHANNEL(process);
60 WINE_DECLARE_DEBUG_CHANNEL(file);
61 WINE_DECLARE_DEBUG_CHANNEL(relay);
63 typedef struct
65 LPSTR lpEnvAddress;
66 LPSTR lpCmdLine;
67 LPSTR lpCmdShow;
68 DWORD dwReserved;
69 } LOADPARMS32;
71 static UINT process_error_mode;
73 static DWORD shutdown_flags = 0;
74 static DWORD shutdown_priority = 0x280;
75 static DWORD process_dword;
77 HMODULE kernel32_handle = 0;
79 const WCHAR *DIR_Windows = NULL;
80 const WCHAR *DIR_System = NULL;
82 /* Process flags */
83 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
84 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
85 #define PDB32_DOS_PROC 0x0010 /* Dos process */
86 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
87 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
88 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
90 static const WCHAR comW[] = {'.','c','o','m',0};
91 static const WCHAR batW[] = {'.','b','a','t',0};
92 static const WCHAR cmdW[] = {'.','c','m','d',0};
93 static const WCHAR pifW[] = {'.','p','i','f',0};
94 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
96 static void exec_process( LPCWSTR name );
98 extern void SHELL_LoadRegistry(void);
101 /***********************************************************************
102 * contains_path
104 static inline int contains_path( LPCWSTR name )
106 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
110 /***********************************************************************
111 * is_special_env_var
113 * Check if an environment variable needs to be handled specially when
114 * passed through the Unix environment (i.e. prefixed with "WINE").
116 static inline int is_special_env_var( const char *var )
118 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
119 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
120 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
121 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
125 /***************************************************************************
126 * get_builtin_path
128 * Get the path of a builtin module when the native file does not exist.
130 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
132 WCHAR *file_part;
133 UINT len = strlenW( DIR_System );
135 if (contains_path( libname ))
137 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
138 filename, &file_part ) > size * sizeof(WCHAR))
139 return FALSE; /* too long */
141 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
142 return FALSE;
143 while (filename[len] == '\\') len++;
144 if (filename + len != file_part) return FALSE;
146 else
148 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
149 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
150 file_part = filename + len;
151 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
152 strcpyW( file_part, libname );
154 if (ext && !strchrW( file_part, '.' ))
156 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
157 return FALSE; /* too long */
158 strcatW( file_part, ext );
160 return TRUE;
164 /***********************************************************************
165 * open_builtin_exe_file
167 * Open an exe file for a builtin exe.
169 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
170 int test_only, int *file_exists )
172 char exename[MAX_PATH];
173 WCHAR *p;
174 UINT i, len;
176 *file_exists = 0;
177 if ((p = strrchrW( name, '/' ))) name = p + 1;
178 if ((p = strrchrW( name, '\\' ))) name = p + 1;
180 /* we don't want to depend on the current codepage here */
181 len = strlenW( name ) + 1;
182 if (len >= sizeof(exename)) return NULL;
183 for (i = 0; i < len; i++)
185 if (name[i] > 127) return NULL;
186 exename[i] = (char)name[i];
187 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
189 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
193 /***********************************************************************
194 * open_exe_file
196 * Open a specific exe file, taking load order into account.
197 * Returns the file handle or 0 for a builtin exe.
199 static HANDLE open_exe_file( const WCHAR *name )
201 HANDLE handle;
203 TRACE("looking for %s\n", debugstr_w(name) );
205 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
206 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
208 WCHAR buffer[MAX_PATH];
209 /* file doesn't exist, check for builtin */
210 if (!contains_path( name )) goto error;
211 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
212 handle = 0;
214 return handle;
216 error:
217 SetLastError( ERROR_FILE_NOT_FOUND );
218 return INVALID_HANDLE_VALUE;
222 /***********************************************************************
223 * find_exe_file
225 * Open an exe file, and return the full name and file handle.
226 * Returns FALSE if file could not be found.
227 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
228 * If file is a builtin exe, returns TRUE and sets handle to 0.
230 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
232 static const WCHAR exeW[] = {'.','e','x','e',0};
233 int file_exists;
235 TRACE("looking for %s\n", debugstr_w(name) );
237 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
238 !get_builtin_path( name, exeW, buffer, buflen ))
240 /* no builtin found, try native without extension in case it is a Unix app */
242 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
244 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
245 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
246 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
247 return TRUE;
249 return FALSE;
252 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
253 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
254 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
255 return TRUE;
257 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
258 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
259 if (file_exists)
261 *handle = 0;
262 return TRUE;
265 return FALSE;
269 /***********************************************************************
270 * build_initial_environment
272 * Build the Win32 environment from the Unix environment
274 static BOOL build_initial_environment( char **environ )
276 SIZE_T size = 1;
277 char **e;
278 WCHAR *p, *endptr;
279 void *ptr;
281 /* Compute the total size of the Unix environment */
282 for (e = environ; *e; e++)
284 if (is_special_env_var( *e )) continue;
285 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
287 size *= sizeof(WCHAR);
289 /* Now allocate the environment */
290 ptr = NULL;
291 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
292 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
293 return FALSE;
295 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
296 endptr = p + size / sizeof(WCHAR);
298 /* And fill it with the Unix environment */
299 for (e = environ; *e; e++)
301 char *str = *e;
303 /* skip Unix special variables and use the Wine variants instead */
304 if (!strncmp( str, "WINE", 4 ))
306 if (is_special_env_var( str + 4 )) str += 4;
307 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
309 else if (is_special_env_var( str )) continue; /* skip it */
311 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
312 p += strlenW(p) + 1;
314 *p = 0;
315 return TRUE;
319 /***********************************************************************
320 * set_registry_variables
322 * Set environment variables by enumerating the values of a key;
323 * helper for set_registry_environment().
324 * Note that Windows happily truncates the value if it's too big.
326 static void set_registry_variables( HANDLE hkey, ULONG type )
328 UNICODE_STRING env_name, env_value;
329 NTSTATUS status;
330 DWORD size;
331 int index;
332 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
333 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
335 for (index = 0; ; index++)
337 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
338 buffer, sizeof(buffer), &size );
339 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
340 break;
341 if (info->Type != type)
342 continue;
343 env_name.Buffer = info->Name;
344 env_name.Length = env_name.MaximumLength = info->NameLength;
345 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
346 env_value.Length = env_value.MaximumLength = info->DataLength;
347 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
348 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
349 if (info->Type == REG_EXPAND_SZ)
351 WCHAR buf_expanded[1024];
352 UNICODE_STRING env_expanded;
353 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
354 env_expanded.Buffer=buf_expanded;
355 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
356 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
357 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
359 else
361 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
367 /***********************************************************************
368 * set_registry_environment
370 * Set the environment variables specified in the registry.
372 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
373 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
374 * on the order in which the variables are processed. But on Windows it
375 * does not really matter since they only use %SystemDrive% and
376 * %SystemRoot% which are predefined. But Wine defines these in the
377 * registry, so we need two passes.
379 static void set_registry_environment(void)
381 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
382 'S','y','s','t','e','m','\\',
383 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
384 'C','o','n','t','r','o','l','\\',
385 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
386 'E','n','v','i','r','o','n','m','e','n','t',0};
387 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
389 OBJECT_ATTRIBUTES attr;
390 UNICODE_STRING nameW;
391 HANDLE hkey;
393 attr.Length = sizeof(attr);
394 attr.RootDirectory = 0;
395 attr.ObjectName = &nameW;
396 attr.Attributes = 0;
397 attr.SecurityDescriptor = NULL;
398 attr.SecurityQualityOfService = NULL;
400 /* first the system environment variables */
401 RtlInitUnicodeString( &nameW, env_keyW );
402 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
404 set_registry_variables( hkey, REG_SZ );
405 set_registry_variables( hkey, REG_EXPAND_SZ );
406 NtClose( hkey );
409 /* then the ones for the current user */
410 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return;
411 RtlInitUnicodeString( &nameW, envW );
412 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
414 set_registry_variables( hkey, REG_SZ );
415 set_registry_variables( hkey, REG_EXPAND_SZ );
416 NtClose( hkey );
418 NtClose( attr.RootDirectory );
421 /***********************************************************************
422 * set_additional_environment
424 * Set some additional environment variables not specified in the registry.
426 static void set_additional_environment(void)
428 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
429 const char *name = wine_get_user_name();
430 DWORD len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
431 if (len)
433 LPWSTR nameW = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
434 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, nameW, len );
435 SetEnvironmentVariableW( usernameW, nameW );
436 HeapFree( GetProcessHeap(), 0, nameW );
440 /***********************************************************************
441 * set_library_wargv
443 * Set the Wine library Unicode argv global variables.
445 static void set_library_wargv( char **argv )
447 int argc;
448 char *q;
449 WCHAR *p;
450 WCHAR **wargv;
451 DWORD total = 0;
453 for (argc = 0; argv[argc]; argc++)
454 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
456 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
457 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
458 p = (WCHAR *)(wargv + argc + 1);
459 for (argc = 0; argv[argc]; argc++)
461 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
462 wargv[argc] = p;
463 p += reslen;
464 total -= reslen;
466 wargv[argc] = NULL;
468 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
470 for (argc = 0; wargv[argc]; argc++)
471 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
473 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
474 q = (char *)(argv + argc + 1);
475 for (argc = 0; wargv[argc]; argc++)
477 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
478 argv[argc] = q;
479 q += reslen;
480 total -= reslen;
482 argv[argc] = NULL;
484 __wine_main_argc = argc;
485 __wine_main_argv = argv;
486 __wine_main_wargv = wargv;
490 /***********************************************************************
491 * build_command_line
493 * Build the command line of a process from the argv array.
495 * Note that it does NOT necessarily include the file name.
496 * Sometimes we don't even have any command line options at all.
498 * We must quote and escape characters so that the argv array can be rebuilt
499 * from the command line:
500 * - spaces and tabs must be quoted
501 * 'a b' -> '"a b"'
502 * - quotes must be escaped
503 * '"' -> '\"'
504 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
505 * resulting in an odd number of '\' followed by a '"'
506 * '\"' -> '\\\"'
507 * '\\"' -> '\\\\\"'
508 * - '\'s that are not followed by a '"' can be left as is
509 * 'a\b' == 'a\b'
510 * 'a\\b' == 'a\\b'
512 static BOOL build_command_line( WCHAR **argv )
514 int len;
515 WCHAR **arg;
516 LPWSTR p;
517 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
519 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
521 len = 0;
522 for (arg = argv; *arg; arg++)
524 int has_space,bcount;
525 WCHAR* a;
527 has_space=0;
528 bcount=0;
529 a=*arg;
530 if( !*a ) has_space=1;
531 while (*a!='\0') {
532 if (*a=='\\') {
533 bcount++;
534 } else {
535 if (*a==' ' || *a=='\t') {
536 has_space=1;
537 } else if (*a=='"') {
538 /* doubling of '\' preceding a '"',
539 * plus escaping of said '"'
541 len+=2*bcount+1;
543 bcount=0;
545 a++;
547 len+=(a-*arg)+1 /* for the separating space */;
548 if (has_space)
549 len+=2; /* for the quotes */
552 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
553 return FALSE;
555 p = rupp->CommandLine.Buffer;
556 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
557 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
558 for (arg = argv; *arg; arg++)
560 int has_space,has_quote;
561 WCHAR* a;
563 /* Check for quotes and spaces in this argument */
564 has_space=has_quote=0;
565 a=*arg;
566 if( !*a ) has_space=1;
567 while (*a!='\0') {
568 if (*a==' ' || *a=='\t') {
569 has_space=1;
570 if (has_quote)
571 break;
572 } else if (*a=='"') {
573 has_quote=1;
574 if (has_space)
575 break;
577 a++;
580 /* Now transfer it to the command line */
581 if (has_space)
582 *p++='"';
583 if (has_quote) {
584 int bcount;
585 WCHAR* a;
587 bcount=0;
588 a=*arg;
589 while (*a!='\0') {
590 if (*a=='\\') {
591 *p++=*a;
592 bcount++;
593 } else {
594 if (*a=='"') {
595 int i;
597 /* Double all the '\\' preceding this '"', plus one */
598 for (i=0;i<=bcount;i++)
599 *p++='\\';
600 *p++='"';
601 } else {
602 *p++=*a;
604 bcount=0;
606 a++;
608 } else {
609 WCHAR* x = *arg;
610 while ((*p=*x++)) p++;
612 if (has_space)
613 *p++='"';
614 *p++=' ';
616 if (p > rupp->CommandLine.Buffer)
617 p--; /* remove last space */
618 *p = '\0';
620 return TRUE;
624 /***********************************************************************
625 * init_current_directory
627 * Initialize the current directory from the Unix cwd or the parent info.
629 static void init_current_directory( CURDIR *cur_dir )
631 UNICODE_STRING dir_str;
632 char *cwd;
633 int size;
635 /* if we received a cur dir from the parent, try this first */
637 if (cur_dir->DosPath.Length)
639 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
642 /* now try to get it from the Unix cwd */
644 for (size = 256; ; size *= 2)
646 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
647 if (getcwd( cwd, size )) break;
648 HeapFree( GetProcessHeap(), 0, cwd );
649 if (errno == ERANGE) continue;
650 cwd = NULL;
651 break;
654 if (cwd)
656 WCHAR *dirW;
657 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
658 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
660 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
661 RtlInitUnicodeString( &dir_str, dirW );
662 RtlSetCurrentDirectory_U( &dir_str );
663 RtlFreeUnicodeString( &dir_str );
667 if (!cur_dir->DosPath.Length) /* still not initialized */
669 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
670 "starting in the Windows directory.\n", cwd ? cwd : "" );
671 RtlInitUnicodeString( &dir_str, DIR_Windows );
672 RtlSetCurrentDirectory_U( &dir_str );
674 HeapFree( GetProcessHeap(), 0, cwd );
676 done:
677 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
678 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
682 /***********************************************************************
683 * init_windows_dirs
685 * Initialize the windows and system directories from the environment.
687 static void init_windows_dirs(void)
689 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
691 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
692 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
693 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
694 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
696 DWORD len;
697 WCHAR *buffer;
699 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
701 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
702 GetEnvironmentVariableW( windirW, buffer, len );
703 DIR_Windows = buffer;
705 else DIR_Windows = default_windirW;
707 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
709 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
710 GetEnvironmentVariableW( winsysdirW, buffer, len );
711 DIR_System = buffer;
713 else
715 len = strlenW( DIR_Windows );
716 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
717 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
718 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
719 DIR_System = buffer;
722 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
723 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
724 debugstr_w(DIR_Windows) );
725 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
726 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
727 debugstr_w(DIR_System) );
729 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
730 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
732 /* set the directories in ntdll too */
733 __wine_init_windows_dir( DIR_Windows, DIR_System );
737 /***********************************************************************
738 * process_init
740 * Main process initialisation code
742 static BOOL process_init(void)
744 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
745 PEB *peb = NtCurrentTeb()->Peb;
746 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
748 PTHREAD_Init();
750 setbuf(stdout,NULL);
751 setbuf(stderr,NULL);
753 kernel32_handle = GetModuleHandleW(kernel32W);
755 LOCALE_Init();
757 if (!params->Environment)
759 /* Copy the parent environment */
760 if (!build_initial_environment( __wine_main_environ )) return FALSE;
762 /* convert old configuration to new format */
763 convert_old_config();
765 set_registry_environment();
766 set_additional_environment();
769 init_windows_dirs();
770 init_current_directory( &params->CurrentDirectory );
772 return TRUE;
776 /***********************************************************************
777 * start_wineboot
779 * Start the wineboot process if necessary. Return the event to wait on.
781 static HANDLE start_wineboot(void)
783 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
784 HANDLE event;
786 if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
788 ERR( "failed to create wineboot event, expect trouble\n" );
789 return 0;
791 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
793 static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
794 STARTUPINFOW si;
795 PROCESS_INFORMATION pi;
796 WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];
798 memset( &si, 0, sizeof(si) );
799 si.cb = sizeof(si);
800 si.dwFlags = STARTF_USESTDHANDLES;
801 si.hStdInput = 0;
802 si.hStdOutput = 0;
803 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
805 GetSystemDirectoryW( cmdline, MAX_PATH );
806 lstrcatW( cmdline, command_line );
807 if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
809 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
810 CloseHandle( pi.hThread );
811 CloseHandle( pi.hProcess );
814 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
816 return event;
820 /***********************************************************************
821 * init_stack
823 * Allocate the stack of new process.
825 static void *init_stack(void)
827 void *base;
828 SIZE_T stack_size, page_size = getpagesize();
829 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
831 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
832 stack_size += page_size; /* for the guard page */
833 stack_size = (stack_size + 0xffff) & ~0xffff; /* round to 64K boundary */
834 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
836 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
838 ERR( "failed to allocate main process stack\n" );
839 ExitProcess( 1 );
842 /* note: limit is lower than base since the stack grows down */
843 NtCurrentTeb()->DeallocationStack = base;
844 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
845 NtCurrentTeb()->Tib.StackLimit = (char *)base + page_size;
847 #ifdef VALGRIND_STACK_REGISTER
848 /* no need to de-register the stack as it's the one of the main thread */
849 VALGRIND_STACK_REGISTER(NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase);
850 #endif
852 /* setup guard page */
853 VirtualProtect( base, page_size, PAGE_NOACCESS, NULL );
854 return NtCurrentTeb()->Tib.StackBase;
858 /***********************************************************************
859 * start_process
861 * Startup routine of a new process. Runs on the new process stack.
863 static void start_process( void *arg )
865 __TRY
867 PEB *peb = NtCurrentTeb()->Peb;
868 IMAGE_NT_HEADERS *nt;
869 LPTHREAD_START_ROUTINE entry;
871 LdrInitializeThunk( 0, 0, 0, 0 );
873 nt = RtlImageNtHeader( peb->ImageBaseAddress );
874 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
875 nt->OptionalHeader.AddressOfEntryPoint);
877 if (TRACE_ON(relay))
878 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
879 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
881 SetLastError( 0 ); /* clear error code */
882 if (peb->BeingDebugged) DbgBreakPoint();
883 ExitThread( entry( peb ) );
885 __EXCEPT(UnhandledExceptionFilter)
887 TerminateThread( GetCurrentThread(), GetExceptionCode() );
889 __ENDTRY
893 /***********************************************************************
894 * set_process_name
896 * Change the process name in the ps output.
898 static void set_process_name( int argc, char *argv[] )
900 #ifdef HAVE_SETPROCTITLE
901 setproctitle("-%s", argv[1]);
902 #endif
904 #ifdef HAVE_PRCTL
905 int i, offset;
906 char *p, *prctl_name = argv[1];
907 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
909 #ifndef PR_SET_NAME
910 # define PR_SET_NAME 15
911 #endif
913 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
914 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
916 if (prctl( PR_SET_NAME, prctl_name ) != -1)
918 offset = argv[1] - argv[0];
919 memmove( argv[1] - offset, argv[1], end - argv[1] );
920 memset( end - offset, 0, offset );
921 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
922 argv[i-1] = NULL;
924 else
925 #endif /* HAVE_PRCTL */
927 /* remove argv[0] */
928 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
933 /***********************************************************************
934 * __wine_kernel_init
936 * Wine initialisation: load and start the main exe file.
938 void __wine_kernel_init(void)
940 static const WCHAR dotW[] = {'.',0};
941 static const WCHAR exeW[] = {'.','e','x','e',0};
943 WCHAR *p, main_exe_name[MAX_PATH+1];
944 PEB *peb = NtCurrentTeb()->Peb;
945 HANDLE boot_event = 0;
947 /* Initialize everything */
948 if (!process_init()) exit(1);
949 set_process_name( __wine_main_argc, __wine_main_argv );
950 set_library_wargv( __wine_main_argv );
952 if (peb->ProcessParameters->ImagePathName.Buffer)
954 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
956 else
958 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
959 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
961 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
962 ExitProcess( GetLastError() );
964 if (!build_command_line( __wine_main_wargv )) goto error;
965 boot_event = start_wineboot();
968 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
969 p = strrchrW( main_exe_name, '.' );
970 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
972 TRACE( "starting process name=%s argv[0]=%s\n",
973 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
975 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
976 MODULE_get_dll_load_path(main_exe_name) );
978 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
980 char msg[1024];
981 DWORD error = GetLastError();
983 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
984 if (error == ERROR_BAD_EXE_FORMAT ||
985 error == ERROR_INVALID_ADDRESS ||
986 error == ERROR_NOT_ENOUGH_MEMORY)
988 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
989 /* if we get back here, it failed */
992 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
993 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
994 ExitProcess( error );
997 if (boot_event)
999 if (WaitForSingleObject( boot_event, 30000 )) WARN( "boot event wait timed out\n" );
1000 CloseHandle( boot_event );
1003 /* switch to the new stack */
1004 wine_switch_to_stack( start_process, NULL, init_stack() );
1006 error:
1007 ExitProcess( GetLastError() );
1011 /***********************************************************************
1012 * build_argv
1014 * Build an argv array from a command-line.
1015 * 'reserved' is the number of args to reserve before the first one.
1017 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1019 int argc;
1020 char** argv;
1021 char *arg,*s,*d,*cmdline;
1022 int in_quotes,bcount,len;
1024 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1025 if (!(cmdline = malloc(len))) return NULL;
1026 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1028 argc=reserved+1;
1029 bcount=0;
1030 in_quotes=0;
1031 s=cmdline;
1032 while (1) {
1033 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1034 /* space */
1035 argc++;
1036 /* skip the remaining spaces */
1037 while (*s==' ' || *s=='\t') {
1038 s++;
1040 if (*s=='\0')
1041 break;
1042 bcount=0;
1043 continue;
1044 } else if (*s=='\\') {
1045 /* '\', count them */
1046 bcount++;
1047 } else if ((*s=='"') && ((bcount & 1)==0)) {
1048 /* unescaped '"' */
1049 in_quotes=!in_quotes;
1050 bcount=0;
1051 } else {
1052 /* a regular character */
1053 bcount=0;
1055 s++;
1057 argv=malloc(argc*sizeof(*argv));
1058 if (!argv)
1059 return NULL;
1061 arg=d=s=cmdline;
1062 bcount=0;
1063 in_quotes=0;
1064 argc=reserved;
1065 while (*s) {
1066 if ((*s==' ' || *s=='\t') && !in_quotes) {
1067 /* Close the argument and copy it */
1068 *d=0;
1069 argv[argc++]=arg;
1071 /* skip the remaining spaces */
1072 do {
1073 s++;
1074 } while (*s==' ' || *s=='\t');
1076 /* Start with a new argument */
1077 arg=d=s;
1078 bcount=0;
1079 } else if (*s=='\\') {
1080 /* '\\' */
1081 *d++=*s++;
1082 bcount++;
1083 } else if (*s=='"') {
1084 /* '"' */
1085 if ((bcount & 1)==0) {
1086 /* Preceded by an even number of '\', this is half that
1087 * number of '\', plus a '"' which we discard.
1089 d-=bcount/2;
1090 s++;
1091 in_quotes=!in_quotes;
1092 } else {
1093 /* Preceded by an odd number of '\', this is half that
1094 * number of '\' followed by a '"'
1096 d=d-bcount/2-1;
1097 *d++='"';
1098 s++;
1100 bcount=0;
1101 } else {
1102 /* a regular character */
1103 *d++=*s++;
1104 bcount=0;
1107 if (*arg) {
1108 *d='\0';
1109 argv[argc++]=arg;
1111 argv[argc]=NULL;
1113 return argv;
1117 /***********************************************************************
1118 * alloc_env_string
1120 * Allocate an environment string; helper for build_envp
1122 static char *alloc_env_string( const char *name, const char *value )
1124 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1125 strcpy( ret, name );
1126 strcat( ret, value );
1127 return ret;
1130 /***********************************************************************
1131 * build_envp
1133 * Build the environment of a new child process.
1135 static char **build_envp( const WCHAR *envW )
1137 const WCHAR *end;
1138 char **envp;
1139 char *env, *p;
1140 int count = 0, length;
1142 for (end = envW; *end; count++) end += strlenW(end) + 1;
1143 end++;
1144 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1145 if (!(env = malloc( length ))) return NULL;
1146 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1148 count += 4;
1150 if ((envp = malloc( count * sizeof(*envp) )))
1152 char **envptr = envp;
1154 /* some variables must not be modified, so we get them directly from the unix env */
1155 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1156 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1157 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1158 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1159 /* now put the Windows environment strings */
1160 for (p = env; *p; p += strlen(p) + 1)
1162 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1163 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1164 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1165 if (is_special_env_var( p )) /* prefix it with "WINE" */
1166 *envptr++ = alloc_env_string( "WINE", p );
1167 else
1168 *envptr++ = p;
1170 *envptr = 0;
1172 return envp;
1176 /***********************************************************************
1177 * fork_and_exec
1179 * Fork and exec a new Unix binary, checking for errors.
1181 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1182 const WCHAR *env, const char *newdir, DWORD flags )
1184 int fd[2];
1185 int pid, err;
1187 if (!env) env = GetEnvironmentStringsW();
1189 if (pipe(fd) == -1)
1191 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1192 return -1;
1194 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1195 if (!(pid = fork())) /* child */
1197 char **argv = build_argv( cmdline, 0 );
1198 char **envp = build_envp( env );
1199 close( fd[0] );
1201 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1203 int pid;
1204 if (!(pid = fork()))
1206 int fd = open( "/dev/null", O_RDWR );
1207 setsid();
1208 /* close stdin and stdout */
1209 if (fd != -1)
1211 dup2( fd, 0 );
1212 dup2( fd, 1 );
1213 close( fd );
1216 else if (pid != -1) _exit(0); /* parent */
1219 /* Reset signals that we previously set to SIG_IGN */
1220 signal( SIGPIPE, SIG_DFL );
1221 signal( SIGCHLD, SIG_DFL );
1223 if (newdir) chdir(newdir);
1225 if (argv && envp) execve( filename, argv, envp );
1226 err = errno;
1227 write( fd[1], &err, sizeof(err) );
1228 _exit(1);
1230 close( fd[1] );
1231 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1233 errno = err;
1234 pid = -1;
1236 if (pid == -1) FILE_SetDosError();
1237 close( fd[0] );
1238 return pid;
1242 /***********************************************************************
1243 * create_user_params
1245 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1246 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1247 const STARTUPINFOW *startup )
1249 RTL_USER_PROCESS_PARAMETERS *params;
1250 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1251 NTSTATUS status;
1252 WCHAR buffer[MAX_PATH];
1254 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1255 lstrcpynW( buffer, filename, MAX_PATH );
1256 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1257 lstrcpynW( buffer, filename, MAX_PATH );
1258 RtlInitUnicodeString( &image_str, buffer );
1260 RtlInitUnicodeString( &cmdline_str, cmdline );
1261 newdir.Buffer = NULL;
1262 if (cur_dir)
1264 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1266 /* skip \??\ prefix */
1267 curdir_str.Buffer = newdir.Buffer + 4;
1268 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1269 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1271 else cur_dir = NULL;
1273 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1274 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1275 if (startup->lpReserved2 && startup->cbReserved2)
1277 runtime.Length = 0;
1278 runtime.MaximumLength = startup->cbReserved2;
1279 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1282 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1283 cur_dir ? &curdir_str : NULL,
1284 &cmdline_str, env,
1285 startup->lpTitle ? &title : NULL,
1286 startup->lpDesktop ? &desktop : NULL,
1287 NULL,
1288 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1289 RtlFreeUnicodeString( &newdir );
1290 if (status != STATUS_SUCCESS)
1292 SetLastError( RtlNtStatusToDosError(status) );
1293 return NULL;
1296 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1297 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1299 if (startup->dwFlags & STARTF_USESTDHANDLES)
1301 params->hStdInput = startup->hStdInput;
1302 params->hStdOutput = startup->hStdOutput;
1303 params->hStdError = startup->hStdError;
1305 else
1307 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1308 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1309 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1311 params->dwX = startup->dwX;
1312 params->dwY = startup->dwY;
1313 params->dwXSize = startup->dwXSize;
1314 params->dwYSize = startup->dwYSize;
1315 params->dwXCountChars = startup->dwXCountChars;
1316 params->dwYCountChars = startup->dwYCountChars;
1317 params->dwFillAttribute = startup->dwFillAttribute;
1318 params->dwFlags = startup->dwFlags;
1319 params->wShowWindow = startup->wShowWindow;
1320 return params;
1324 /***********************************************************************
1325 * create_process
1327 * Create a new process. If hFile is a valid handle we have an exe
1328 * file, otherwise it is a Winelib app.
1330 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1331 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1332 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1333 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1334 void *res_start, void *res_end, int exec_only )
1336 BOOL ret, success = FALSE;
1337 HANDLE process_info;
1338 WCHAR *env_end;
1339 char *winedebug = NULL;
1340 RTL_USER_PROCESS_PARAMETERS *params;
1341 int socketfd[2];
1342 pid_t pid;
1343 int err;
1345 if (!env) RtlAcquirePebLock();
1347 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1349 if (!env) RtlReleasePebLock();
1350 return FALSE;
1352 env_end = params->Environment;
1353 while (*env_end)
1355 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1356 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1358 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1359 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1360 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1362 env_end += strlenW(env_end) + 1;
1364 env_end++;
1366 /* create the socket for the new process */
1368 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1370 if (!env) RtlReleasePebLock();
1371 HeapFree( GetProcessHeap(), 0, winedebug );
1372 RtlDestroyProcessParameters( params );
1373 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1374 return FALSE;
1376 wine_server_send_fd( socketfd[1] );
1377 close( socketfd[1] );
1379 /* create the process on the server side */
1381 SERVER_START_REQ( new_process )
1383 req->inherit_all = inherit;
1384 req->create_flags = flags;
1385 req->socket_fd = socketfd[1];
1386 req->exe_file = hFile;
1387 req->process_access = PROCESS_ALL_ACCESS;
1388 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1389 req->thread_access = THREAD_ALL_ACCESS;
1390 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1391 req->hstdin = params->hStdInput;
1392 req->hstdout = params->hStdOutput;
1393 req->hstderr = params->hStdError;
1395 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1397 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1398 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1399 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1400 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1402 else
1404 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1405 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1406 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1409 wine_server_add_data( req, params, params->Size );
1410 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1411 if ((ret = !wine_server_call_err( req )))
1413 info->dwProcessId = (DWORD)reply->pid;
1414 info->dwThreadId = (DWORD)reply->tid;
1415 info->hProcess = reply->phandle;
1416 info->hThread = reply->thandle;
1418 process_info = reply->info;
1420 SERVER_END_REQ;
1422 if (!env) RtlReleasePebLock();
1423 RtlDestroyProcessParameters( params );
1424 if (!ret)
1426 close( socketfd[0] );
1427 HeapFree( GetProcessHeap(), 0, winedebug );
1428 return FALSE;
1431 /* create the child process */
1433 if (exec_only || !(pid = fork())) /* child */
1435 char preloader_reserve[64], socket_env[64];
1436 char **argv = build_argv( cmd_line, 1 );
1438 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1440 if (!(pid = fork()))
1442 int fd = open( "/dev/null", O_RDWR );
1443 setsid();
1444 /* close stdin and stdout */
1445 if (fd != -1)
1447 dup2( fd, 0 );
1448 dup2( fd, 1 );
1449 close( fd );
1452 else if (pid != -1) _exit(0); /* parent */
1455 /* Reset signals that we previously set to SIG_IGN */
1456 signal( SIGPIPE, SIG_DFL );
1457 signal( SIGCHLD, SIG_DFL );
1459 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1460 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1461 (unsigned long)res_start, (unsigned long)res_end );
1463 putenv( preloader_reserve );
1464 putenv( socket_env );
1465 if (winedebug) putenv( winedebug );
1466 if (unixdir) chdir(unixdir);
1468 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1469 _exit(1);
1472 /* this is the parent */
1474 close( socketfd[0] );
1475 HeapFree( GetProcessHeap(), 0, winedebug );
1476 if (pid == -1)
1478 FILE_SetDosError();
1479 goto error;
1482 /* wait for the new process info to be ready */
1484 WaitForSingleObject( process_info, INFINITE );
1485 SERVER_START_REQ( get_new_process_info )
1487 req->info = process_info;
1488 wine_server_call( req );
1489 success = reply->success;
1490 err = reply->exit_code;
1492 SERVER_END_REQ;
1494 if (!success)
1496 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1497 goto error;
1499 CloseHandle( process_info );
1500 return success;
1502 error:
1503 CloseHandle( process_info );
1504 CloseHandle( info->hProcess );
1505 CloseHandle( info->hThread );
1506 info->hProcess = info->hThread = 0;
1507 info->dwProcessId = info->dwThreadId = 0;
1508 return FALSE;
1512 /***********************************************************************
1513 * create_vdm_process
1515 * Create a new VDM process for a 16-bit or DOS application.
1517 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1518 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1519 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1520 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1522 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1524 BOOL ret;
1525 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1526 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1528 if (!new_cmd_line)
1530 SetLastError( ERROR_OUTOFMEMORY );
1531 return FALSE;
1533 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1534 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1535 flags, startup, info, unixdir, NULL, NULL, exec_only );
1536 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1537 return ret;
1541 /***********************************************************************
1542 * create_cmd_process
1544 * Create a new cmd shell process for a .BAT file.
1546 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1547 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1548 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1549 LPPROCESS_INFORMATION info )
1552 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1553 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1554 WCHAR comspec[MAX_PATH];
1555 WCHAR *newcmdline;
1556 BOOL ret;
1558 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1559 return FALSE;
1560 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1561 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1562 return FALSE;
1564 strcpyW( newcmdline, comspec );
1565 strcatW( newcmdline, slashcW );
1566 strcatW( newcmdline, cmd_line );
1567 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1568 flags, env, cur_dir, startup, info );
1569 HeapFree( GetProcessHeap(), 0, newcmdline );
1570 return ret;
1574 /*************************************************************************
1575 * get_file_name
1577 * Helper for CreateProcess: retrieve the file name to load from the
1578 * app name and command line. Store the file name in buffer, and
1579 * return a possibly modified command line.
1580 * Also returns a handle to the opened file if it's a Windows binary.
1582 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1583 int buflen, HANDLE *handle )
1585 static const WCHAR quotesW[] = {'"','%','s','"',0};
1587 WCHAR *name, *pos, *ret = NULL;
1588 const WCHAR *p;
1589 BOOL got_space;
1591 /* if we have an app name, everything is easy */
1593 if (appname)
1595 /* use the unmodified app name as file name */
1596 lstrcpynW( buffer, appname, buflen );
1597 *handle = open_exe_file( buffer );
1598 if (!(ret = cmdline) || !cmdline[0])
1600 /* no command-line, create one */
1601 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1602 sprintfW( ret, quotesW, appname );
1604 return ret;
1607 if (!cmdline)
1609 SetLastError( ERROR_INVALID_PARAMETER );
1610 return NULL;
1613 /* first check for a quoted file name */
1615 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1617 int len = p - cmdline - 1;
1618 /* extract the quoted portion as file name */
1619 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1620 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1621 name[len] = 0;
1623 if (find_exe_file( name, buffer, buflen, handle ))
1624 ret = cmdline; /* no change necessary */
1625 goto done;
1628 /* now try the command-line word by word */
1630 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1631 return NULL;
1632 pos = name;
1633 p = cmdline;
1634 got_space = FALSE;
1636 while (*p)
1638 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1639 *pos = 0;
1640 if (find_exe_file( name, buffer, buflen, handle ))
1642 ret = cmdline;
1643 break;
1645 if (*p) got_space = TRUE;
1648 if (ret && got_space) /* now build a new command-line with quotes */
1650 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1651 goto done;
1652 sprintfW( ret, quotesW, name );
1653 strcatW( ret, p );
1656 done:
1657 HeapFree( GetProcessHeap(), 0, name );
1658 return ret;
1662 /**********************************************************************
1663 * CreateProcessA (KERNEL32.@)
1665 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1666 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1667 DWORD flags, LPVOID env, LPCSTR cur_dir,
1668 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1670 BOOL ret = FALSE;
1671 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1672 UNICODE_STRING desktopW, titleW;
1673 STARTUPINFOW infoW;
1675 desktopW.Buffer = NULL;
1676 titleW.Buffer = NULL;
1677 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1678 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1679 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1681 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1682 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1684 memcpy( &infoW, startup_info, sizeof(infoW) );
1685 infoW.lpDesktop = desktopW.Buffer;
1686 infoW.lpTitle = titleW.Buffer;
1688 if (startup_info->lpReserved)
1689 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1690 debugstr_a(startup_info->lpReserved));
1692 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1693 inherit, flags, env, cur_dirW, &infoW, info );
1694 done:
1695 HeapFree( GetProcessHeap(), 0, app_nameW );
1696 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1697 HeapFree( GetProcessHeap(), 0, cur_dirW );
1698 RtlFreeUnicodeString( &desktopW );
1699 RtlFreeUnicodeString( &titleW );
1700 return ret;
1704 /**********************************************************************
1705 * CreateProcessW (KERNEL32.@)
1707 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1708 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1709 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1710 LPPROCESS_INFORMATION info )
1712 BOOL retv = FALSE;
1713 HANDLE hFile = 0;
1714 char *unixdir = NULL;
1715 WCHAR name[MAX_PATH];
1716 WCHAR *tidy_cmdline, *p, *envW = env;
1717 void *res_start, *res_end;
1719 /* Process the AppName and/or CmdLine to get module name and path */
1721 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1723 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1724 return FALSE;
1725 if (hFile == INVALID_HANDLE_VALUE) goto done;
1727 /* Warn if unsupported features are used */
1729 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1730 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1731 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1732 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1733 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1735 if (cur_dir)
1737 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1739 SetLastError(ERROR_DIRECTORY);
1740 goto done;
1743 else
1745 WCHAR buf[MAX_PATH];
1746 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1749 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1751 char *p = env;
1752 DWORD lenW;
1754 while (*p) p += strlen(p) + 1;
1755 p++; /* final null */
1756 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1757 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1758 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1759 flags |= CREATE_UNICODE_ENVIRONMENT;
1762 info->hThread = info->hProcess = 0;
1763 info->dwProcessId = info->dwThreadId = 0;
1765 /* Determine executable type */
1767 if (!hFile) /* builtin exe */
1769 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1770 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1771 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1772 goto done;
1775 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1777 case BINARY_PE_EXE:
1778 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1779 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1780 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1781 break;
1782 case BINARY_OS216:
1783 case BINARY_WIN16:
1784 case BINARY_DOS:
1785 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1786 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1787 inherit, flags, startup_info, info, unixdir, FALSE );
1788 break;
1789 case BINARY_PE_DLL:
1790 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1791 SetLastError( ERROR_BAD_EXE_FORMAT );
1792 break;
1793 case BINARY_UNIX_LIB:
1794 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1795 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1796 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1797 break;
1798 case BINARY_UNKNOWN:
1799 /* check for .com or .bat extension */
1800 if ((p = strrchrW( name, '.' )))
1802 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1804 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1805 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1806 inherit, flags, startup_info, info, unixdir, FALSE );
1807 break;
1809 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1811 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1812 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1813 inherit, flags, startup_info, info );
1814 break;
1817 /* fall through */
1818 case BINARY_UNIX_EXE:
1820 /* unknown file, try as unix executable */
1821 char *unix_name;
1823 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1825 if ((unix_name = wine_get_unix_file_name( name )))
1827 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags ) != -1);
1828 HeapFree( GetProcessHeap(), 0, unix_name );
1831 break;
1833 CloseHandle( hFile );
1835 done:
1836 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1837 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1838 HeapFree( GetProcessHeap(), 0, unixdir );
1839 return retv;
1843 /**********************************************************************
1844 * exec_process
1846 static void exec_process( LPCWSTR name )
1848 HANDLE hFile;
1849 WCHAR *p;
1850 void *res_start, *res_end;
1851 STARTUPINFOW startup_info;
1852 PROCESS_INFORMATION info;
1854 hFile = open_exe_file( name );
1855 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
1857 memset( &startup_info, 0, sizeof(startup_info) );
1858 startup_info.cb = sizeof(startup_info);
1860 /* Determine executable type */
1862 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1864 case BINARY_PE_EXE:
1865 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1866 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1867 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
1868 break;
1869 case BINARY_UNIX_LIB:
1870 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1871 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1872 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
1873 break;
1874 case BINARY_UNKNOWN:
1875 /* check for .com or .pif extension */
1876 if (!(p = strrchrW( name, '.' ))) break;
1877 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
1878 /* fall through */
1879 case BINARY_OS216:
1880 case BINARY_WIN16:
1881 case BINARY_DOS:
1882 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1883 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1884 FALSE, 0, &startup_info, &info, NULL, TRUE );
1885 break;
1886 default:
1887 break;
1889 CloseHandle( hFile );
1893 /***********************************************************************
1894 * wait_input_idle
1896 * Wrapper to call WaitForInputIdle USER function
1898 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1900 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1902 HMODULE mod = GetModuleHandleA( "user32.dll" );
1903 if (mod)
1905 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1906 if (ptr) return ptr( process, timeout );
1908 return 0;
1912 /***********************************************************************
1913 * WinExec (KERNEL32.@)
1915 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1917 PROCESS_INFORMATION info;
1918 STARTUPINFOA startup;
1919 char *cmdline;
1920 UINT ret;
1922 memset( &startup, 0, sizeof(startup) );
1923 startup.cb = sizeof(startup);
1924 startup.dwFlags = STARTF_USESHOWWINDOW;
1925 startup.wShowWindow = nCmdShow;
1927 /* cmdline needs to be writable for CreateProcess */
1928 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1929 strcpy( cmdline, lpCmdLine );
1931 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1932 0, NULL, NULL, &startup, &info ))
1934 /* Give 30 seconds to the app to come up */
1935 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1936 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1937 ret = 33;
1938 /* Close off the handles */
1939 CloseHandle( info.hThread );
1940 CloseHandle( info.hProcess );
1942 else if ((ret = GetLastError()) >= 32)
1944 FIXME("Strange error set by CreateProcess: %d\n", ret );
1945 ret = 11;
1947 HeapFree( GetProcessHeap(), 0, cmdline );
1948 return ret;
1952 /**********************************************************************
1953 * LoadModule (KERNEL32.@)
1955 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1957 LOADPARMS32 *params = paramBlock;
1958 PROCESS_INFORMATION info;
1959 STARTUPINFOA startup;
1960 HINSTANCE hInstance;
1961 LPSTR cmdline, p;
1962 char filename[MAX_PATH];
1963 BYTE len;
1965 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1967 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1968 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1969 return ULongToHandle(GetLastError());
1971 len = (BYTE)params->lpCmdLine[0];
1972 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1973 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1975 strcpy( cmdline, filename );
1976 p = cmdline + strlen(cmdline);
1977 *p++ = ' ';
1978 memcpy( p, params->lpCmdLine + 1, len );
1979 p[len] = 0;
1981 memset( &startup, 0, sizeof(startup) );
1982 startup.cb = sizeof(startup);
1983 if (params->lpCmdShow)
1985 startup.dwFlags = STARTF_USESHOWWINDOW;
1986 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1989 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1990 params->lpEnvAddress, NULL, &startup, &info ))
1992 /* Give 30 seconds to the app to come up */
1993 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1994 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1995 hInstance = (HINSTANCE)33;
1996 /* Close off the handles */
1997 CloseHandle( info.hThread );
1998 CloseHandle( info.hProcess );
2000 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2002 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2003 hInstance = (HINSTANCE)11;
2006 HeapFree( GetProcessHeap(), 0, cmdline );
2007 return hInstance;
2011 /******************************************************************************
2012 * TerminateProcess (KERNEL32.@)
2014 * Terminates a process.
2016 * PARAMS
2017 * handle [I] Process to terminate.
2018 * exit_code [I] Exit code.
2020 * RETURNS
2021 * Success: TRUE.
2022 * Failure: FALSE, check GetLastError().
2024 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2026 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2027 if (status) SetLastError( RtlNtStatusToDosError(status) );
2028 return !status;
2032 /***********************************************************************
2033 * ExitProcess (KERNEL32.@)
2035 * Exits the current process.
2037 * PARAMS
2038 * status [I] Status code to exit with.
2040 * RETURNS
2041 * Nothing.
2043 void WINAPI ExitProcess( DWORD status )
2045 LdrShutdownProcess();
2046 NtTerminateProcess(GetCurrentProcess(), status);
2047 exit(status);
2051 /***********************************************************************
2052 * GetExitCodeProcess [KERNEL32.@]
2054 * Gets termination status of specified process.
2056 * PARAMS
2057 * hProcess [in] Handle to the process.
2058 * lpExitCode [out] Address to receive termination status.
2060 * RETURNS
2061 * Success: TRUE
2062 * Failure: FALSE
2064 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2066 NTSTATUS status;
2067 PROCESS_BASIC_INFORMATION pbi;
2069 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2070 sizeof(pbi), NULL);
2071 if (status == STATUS_SUCCESS)
2073 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2074 return TRUE;
2076 SetLastError( RtlNtStatusToDosError(status) );
2077 return FALSE;
2081 /***********************************************************************
2082 * SetErrorMode (KERNEL32.@)
2084 UINT WINAPI SetErrorMode( UINT mode )
2086 UINT old = process_error_mode;
2087 process_error_mode = mode;
2088 return old;
2092 /**********************************************************************
2093 * TlsAlloc [KERNEL32.@]
2095 * Allocates a thread local storage index.
2097 * RETURNS
2098 * Success: TLS index.
2099 * Failure: 0xFFFFFFFF
2101 DWORD WINAPI TlsAlloc( void )
2103 DWORD index;
2104 PEB * const peb = NtCurrentTeb()->Peb;
2106 RtlAcquirePebLock();
2107 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2108 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2109 else
2111 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2112 if (index != ~0U)
2114 if (!NtCurrentTeb()->TlsExpansionSlots &&
2115 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2116 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2118 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2119 index = ~0U;
2120 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2122 else
2124 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2125 index += TLS_MINIMUM_AVAILABLE;
2128 else SetLastError( ERROR_NO_MORE_ITEMS );
2130 RtlReleasePebLock();
2131 return index;
2135 /**********************************************************************
2136 * TlsFree [KERNEL32.@]
2138 * Releases a thread local storage index, making it available for reuse.
2140 * PARAMS
2141 * index [in] TLS index to free.
2143 * RETURNS
2144 * Success: TRUE
2145 * Failure: FALSE
2147 BOOL WINAPI TlsFree( DWORD index )
2149 BOOL ret;
2151 RtlAcquirePebLock();
2152 if (index >= TLS_MINIMUM_AVAILABLE)
2154 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2155 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2157 else
2159 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2160 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2162 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2163 else SetLastError( ERROR_INVALID_PARAMETER );
2164 RtlReleasePebLock();
2165 return TRUE;
2169 /**********************************************************************
2170 * TlsGetValue [KERNEL32.@]
2172 * Gets value in a thread's TLS slot.
2174 * PARAMS
2175 * index [in] TLS index to retrieve value for.
2177 * RETURNS
2178 * Success: Value stored in calling thread's TLS slot for index.
2179 * Failure: 0 and GetLastError() returns NO_ERROR.
2181 LPVOID WINAPI TlsGetValue( DWORD index )
2183 LPVOID ret;
2185 if (index < TLS_MINIMUM_AVAILABLE)
2187 ret = NtCurrentTeb()->TlsSlots[index];
2189 else
2191 index -= TLS_MINIMUM_AVAILABLE;
2192 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2194 SetLastError( ERROR_INVALID_PARAMETER );
2195 return NULL;
2197 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2198 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2200 SetLastError( ERROR_SUCCESS );
2201 return ret;
2205 /**********************************************************************
2206 * TlsSetValue [KERNEL32.@]
2208 * Stores a value in the thread's TLS slot.
2210 * PARAMS
2211 * index [in] TLS index to set value for.
2212 * value [in] Value to be stored.
2214 * RETURNS
2215 * Success: TRUE
2216 * Failure: FALSE
2218 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2220 if (index < TLS_MINIMUM_AVAILABLE)
2222 NtCurrentTeb()->TlsSlots[index] = value;
2224 else
2226 index -= TLS_MINIMUM_AVAILABLE;
2227 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2229 SetLastError( ERROR_INVALID_PARAMETER );
2230 return FALSE;
2232 if (!NtCurrentTeb()->TlsExpansionSlots &&
2233 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2234 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2236 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2237 return FALSE;
2239 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2241 return TRUE;
2245 /***********************************************************************
2246 * GetProcessFlags (KERNEL32.@)
2248 DWORD WINAPI GetProcessFlags( DWORD processid )
2250 IMAGE_NT_HEADERS *nt;
2251 DWORD flags = 0;
2253 if (processid && processid != GetCurrentProcessId()) return 0;
2255 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2257 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2258 flags |= PDB32_CONSOLE_PROC;
2260 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2261 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2262 return flags;
2266 /***********************************************************************
2267 * GetProcessDword (KERNEL.485)
2268 * GetProcessDword (KERNEL32.18)
2269 * 'Of course you cannot directly access Windows internal structures'
2271 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2273 DWORD x, y;
2274 STARTUPINFOW siw;
2276 TRACE("(%d, %d)\n", dwProcessID, offset );
2278 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2280 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2281 return 0;
2284 switch ( offset )
2286 case GPD_APP_COMPAT_FLAGS:
2287 return GetAppCompatFlags16(0);
2288 case GPD_LOAD_DONE_EVENT:
2289 return 0;
2290 case GPD_HINSTANCE16:
2291 return GetTaskDS16();
2292 case GPD_WINDOWS_VERSION:
2293 return GetExeVersion16();
2294 case GPD_THDB:
2295 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2296 case GPD_PDB:
2297 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2298 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2299 GetStartupInfoW(&siw);
2300 return HandleToULong(siw.hStdOutput);
2301 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2302 GetStartupInfoW(&siw);
2303 return HandleToULong(siw.hStdInput);
2304 case GPD_STARTF_SHOWWINDOW:
2305 GetStartupInfoW(&siw);
2306 return siw.wShowWindow;
2307 case GPD_STARTF_SIZE:
2308 GetStartupInfoW(&siw);
2309 x = siw.dwXSize;
2310 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2311 y = siw.dwYSize;
2312 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2313 return MAKELONG( x, y );
2314 case GPD_STARTF_POSITION:
2315 GetStartupInfoW(&siw);
2316 x = siw.dwX;
2317 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2318 y = siw.dwY;
2319 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2320 return MAKELONG( x, y );
2321 case GPD_STARTF_FLAGS:
2322 GetStartupInfoW(&siw);
2323 return siw.dwFlags;
2324 case GPD_PARENT:
2325 return 0;
2326 case GPD_FLAGS:
2327 return GetProcessFlags(0);
2328 case GPD_USERDATA:
2329 return process_dword;
2330 default:
2331 ERR("Unknown offset %d\n", offset );
2332 return 0;
2336 /***********************************************************************
2337 * SetProcessDword (KERNEL.484)
2338 * 'Of course you cannot directly access Windows internal structures'
2340 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2342 TRACE("(%d, %d)\n", dwProcessID, offset );
2344 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2346 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2347 return;
2350 switch ( offset )
2352 case GPD_APP_COMPAT_FLAGS:
2353 case GPD_LOAD_DONE_EVENT:
2354 case GPD_HINSTANCE16:
2355 case GPD_WINDOWS_VERSION:
2356 case GPD_THDB:
2357 case GPD_PDB:
2358 case GPD_STARTF_SHELLDATA:
2359 case GPD_STARTF_HOTKEY:
2360 case GPD_STARTF_SHOWWINDOW:
2361 case GPD_STARTF_SIZE:
2362 case GPD_STARTF_POSITION:
2363 case GPD_STARTF_FLAGS:
2364 case GPD_PARENT:
2365 case GPD_FLAGS:
2366 ERR("Not allowed to modify offset %d\n", offset );
2367 break;
2368 case GPD_USERDATA:
2369 process_dword = value;
2370 break;
2371 default:
2372 ERR("Unknown offset %d\n", offset );
2373 break;
2378 /***********************************************************************
2379 * ExitProcess (KERNEL.466)
2381 void WINAPI ExitProcess16( WORD status )
2383 DWORD count;
2384 ReleaseThunkLock( &count );
2385 ExitProcess( status );
2389 /*********************************************************************
2390 * OpenProcess (KERNEL32.@)
2392 * Opens a handle to a process.
2394 * PARAMS
2395 * access [I] Desired access rights assigned to the returned handle.
2396 * inherit [I] Determines whether or not child processes will inherit the handle.
2397 * id [I] Process identifier of the process to get a handle to.
2399 * RETURNS
2400 * Success: Valid handle to the specified process.
2401 * Failure: NULL, check GetLastError().
2403 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2405 NTSTATUS status;
2406 HANDLE handle;
2407 OBJECT_ATTRIBUTES attr;
2408 CLIENT_ID cid;
2410 cid.UniqueProcess = ULongToHandle(id);
2411 cid.UniqueThread = 0; /* FIXME ? */
2413 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2414 attr.RootDirectory = NULL;
2415 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2416 attr.SecurityDescriptor = NULL;
2417 attr.SecurityQualityOfService = NULL;
2418 attr.ObjectName = NULL;
2420 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2422 status = NtOpenProcess(&handle, access, &attr, &cid);
2423 if (status != STATUS_SUCCESS)
2425 SetLastError( RtlNtStatusToDosError(status) );
2426 return NULL;
2428 return handle;
2432 /*********************************************************************
2433 * MapProcessHandle (KERNEL.483)
2434 * GetProcessId (KERNEL32.@)
2436 * Gets the a unique identifier of a process.
2438 * PARAMS
2439 * hProcess [I] Handle to the process.
2441 * RETURNS
2442 * Success: TRUE.
2443 * Failure: FALSE, check GetLastError().
2445 * NOTES
2447 * The identifier is unique only on the machine and only until the process
2448 * exits (including system shutdown).
2450 DWORD WINAPI GetProcessId( HANDLE hProcess )
2452 NTSTATUS status;
2453 PROCESS_BASIC_INFORMATION pbi;
2455 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2456 sizeof(pbi), NULL);
2457 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2458 SetLastError( RtlNtStatusToDosError(status) );
2459 return 0;
2463 /*********************************************************************
2464 * CloseW32Handle (KERNEL.474)
2465 * CloseHandle (KERNEL32.@)
2467 * Closes a handle.
2469 * PARAMS
2470 * handle [I] Handle to close.
2472 * RETURNS
2473 * Success: TRUE.
2474 * Failure: FALSE, check GetLastError().
2476 BOOL WINAPI CloseHandle( HANDLE handle )
2478 NTSTATUS status;
2480 /* stdio handles need special treatment */
2481 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2482 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2483 (handle == (HANDLE)STD_ERROR_HANDLE))
2484 handle = GetStdHandle( HandleToULong(handle) );
2486 if (is_console_handle(handle))
2487 return CloseConsoleHandle(handle);
2489 status = NtClose( handle );
2490 if (status) SetLastError( RtlNtStatusToDosError(status) );
2491 return !status;
2495 /*********************************************************************
2496 * GetHandleInformation (KERNEL32.@)
2498 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2500 OBJECT_DATA_INFORMATION info;
2501 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2503 if (status) SetLastError( RtlNtStatusToDosError(status) );
2504 else if (flags)
2506 *flags = 0;
2507 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2508 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2510 return !status;
2514 /*********************************************************************
2515 * SetHandleInformation (KERNEL32.@)
2517 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2519 OBJECT_DATA_INFORMATION info;
2520 NTSTATUS status;
2522 /* if not setting both fields, retrieve current value first */
2523 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2524 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2526 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2528 SetLastError( RtlNtStatusToDosError(status) );
2529 return FALSE;
2532 if (mask & HANDLE_FLAG_INHERIT)
2533 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2534 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2535 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2537 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2538 if (status) SetLastError( RtlNtStatusToDosError(status) );
2539 return !status;
2543 /*********************************************************************
2544 * DuplicateHandle (KERNEL32.@)
2546 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2547 HANDLE dest_process, HANDLE *dest,
2548 DWORD access, BOOL inherit, DWORD options )
2550 NTSTATUS status;
2552 if (is_console_handle(source))
2554 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2555 if (source_process != dest_process ||
2556 source_process != GetCurrentProcess())
2558 SetLastError(ERROR_INVALID_PARAMETER);
2559 return FALSE;
2561 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2562 return (*dest != INVALID_HANDLE_VALUE);
2564 status = NtDuplicateObject( source_process, source, dest_process, dest,
2565 access, inherit ? OBJ_INHERIT : 0, options );
2566 if (status) SetLastError( RtlNtStatusToDosError(status) );
2567 return !status;
2571 /***********************************************************************
2572 * ConvertToGlobalHandle (KERNEL.476)
2573 * ConvertToGlobalHandle (KERNEL32.@)
2575 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2577 HANDLE ret = INVALID_HANDLE_VALUE;
2578 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2579 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2580 return ret;
2584 /***********************************************************************
2585 * SetHandleContext (KERNEL32.@)
2587 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2589 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2590 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2591 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2592 return FALSE;
2596 /***********************************************************************
2597 * GetHandleContext (KERNEL32.@)
2599 DWORD WINAPI GetHandleContext(HANDLE hnd)
2601 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2602 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2603 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2604 return 0;
2608 /***********************************************************************
2609 * CreateSocketHandle (KERNEL32.@)
2611 HANDLE WINAPI CreateSocketHandle(void)
2613 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2614 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2615 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2616 return INVALID_HANDLE_VALUE;
2620 /***********************************************************************
2621 * SetPriorityClass (KERNEL32.@)
2623 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2625 NTSTATUS status;
2626 PROCESS_PRIORITY_CLASS ppc;
2628 ppc.Foreground = FALSE;
2629 switch (priorityclass)
2631 case IDLE_PRIORITY_CLASS:
2632 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2633 case BELOW_NORMAL_PRIORITY_CLASS:
2634 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2635 case NORMAL_PRIORITY_CLASS:
2636 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2637 case ABOVE_NORMAL_PRIORITY_CLASS:
2638 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2639 case HIGH_PRIORITY_CLASS:
2640 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2641 case REALTIME_PRIORITY_CLASS:
2642 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2643 default:
2644 SetLastError(ERROR_INVALID_PARAMETER);
2645 return FALSE;
2648 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2649 &ppc, sizeof(ppc));
2651 if (status != STATUS_SUCCESS)
2653 SetLastError( RtlNtStatusToDosError(status) );
2654 return FALSE;
2656 return TRUE;
2660 /***********************************************************************
2661 * GetPriorityClass (KERNEL32.@)
2663 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2665 NTSTATUS status;
2666 PROCESS_BASIC_INFORMATION pbi;
2668 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2669 sizeof(pbi), NULL);
2670 if (status != STATUS_SUCCESS)
2672 SetLastError( RtlNtStatusToDosError(status) );
2673 return 0;
2675 switch (pbi.BasePriority)
2677 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2678 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2679 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2680 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2681 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2682 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2684 SetLastError( ERROR_INVALID_PARAMETER );
2685 return 0;
2689 /***********************************************************************
2690 * SetProcessAffinityMask (KERNEL32.@)
2692 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2694 NTSTATUS status;
2696 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2697 &affmask, sizeof(DWORD_PTR));
2698 if (!status)
2700 SetLastError( RtlNtStatusToDosError(status) );
2701 return FALSE;
2703 return TRUE;
2707 /**********************************************************************
2708 * GetProcessAffinityMask (KERNEL32.@)
2710 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2711 PDWORD_PTR lpProcessAffinityMask,
2712 PDWORD_PTR lpSystemAffinityMask )
2714 PROCESS_BASIC_INFORMATION pbi;
2715 NTSTATUS status;
2717 status = NtQueryInformationProcess(hProcess,
2718 ProcessBasicInformation,
2719 &pbi, sizeof(pbi), NULL);
2720 if (status)
2722 SetLastError( RtlNtStatusToDosError(status) );
2723 return FALSE;
2725 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2726 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2727 return TRUE;
2731 /***********************************************************************
2732 * GetProcessVersion (KERNEL32.@)
2734 DWORD WINAPI GetProcessVersion( DWORD processid )
2736 IMAGE_NT_HEADERS *nt;
2738 if (processid && processid != GetCurrentProcessId())
2740 FIXME("should use ReadProcessMemory\n");
2741 return 0;
2743 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2744 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2745 nt->OptionalHeader.MinorSubsystemVersion);
2746 return 0;
2750 /***********************************************************************
2751 * SetProcessWorkingSetSize [KERNEL32.@]
2752 * Sets the min/max working set sizes for a specified process.
2754 * PARAMS
2755 * hProcess [I] Handle to the process of interest
2756 * minset [I] Specifies minimum working set size
2757 * maxset [I] Specifies maximum working set size
2759 * RETURNS
2760 * Success: TRUE
2761 * Failure: FALSE
2763 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2764 SIZE_T maxset)
2766 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2767 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2768 /* Trim the working set to zero */
2769 /* Swap the process out of physical RAM */
2771 return TRUE;
2774 /***********************************************************************
2775 * GetProcessWorkingSetSize (KERNEL32.@)
2777 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2778 PSIZE_T maxset)
2780 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2781 /* 32 MB working set size */
2782 if (minset) *minset = 32*1024*1024;
2783 if (maxset) *maxset = 32*1024*1024;
2784 return TRUE;
2788 /***********************************************************************
2789 * SetProcessShutdownParameters (KERNEL32.@)
2791 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2793 FIXME("(%08x, %08x): partial stub.\n", level, flags);
2794 shutdown_flags = flags;
2795 shutdown_priority = level;
2796 return TRUE;
2800 /***********************************************************************
2801 * GetProcessShutdownParameters (KERNEL32.@)
2804 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2806 *lpdwLevel = shutdown_priority;
2807 *lpdwFlags = shutdown_flags;
2808 return TRUE;
2812 /***********************************************************************
2813 * GetProcessPriorityBoost (KERNEL32.@)
2815 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2817 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2819 /* Report that no boost is present.. */
2820 *pDisablePriorityBoost = FALSE;
2822 return TRUE;
2825 /***********************************************************************
2826 * SetProcessPriorityBoost (KERNEL32.@)
2828 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2830 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2831 /* Say we can do it. I doubt the program will notice that we don't. */
2832 return TRUE;
2836 /***********************************************************************
2837 * ReadProcessMemory (KERNEL32.@)
2839 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2840 SIZE_T *bytes_read )
2842 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2843 if (status) SetLastError( RtlNtStatusToDosError(status) );
2844 return !status;
2848 /***********************************************************************
2849 * WriteProcessMemory (KERNEL32.@)
2851 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2852 SIZE_T *bytes_written )
2854 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2855 if (status) SetLastError( RtlNtStatusToDosError(status) );
2856 return !status;
2860 /****************************************************************************
2861 * FlushInstructionCache (KERNEL32.@)
2863 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2865 NTSTATUS status;
2866 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2867 if (status) SetLastError( RtlNtStatusToDosError(status) );
2868 return !status;
2872 /******************************************************************
2873 * GetProcessIoCounters (KERNEL32.@)
2875 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2877 NTSTATUS status;
2879 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2880 ioc, sizeof(*ioc), NULL);
2881 if (status) SetLastError( RtlNtStatusToDosError(status) );
2882 return !status;
2885 /******************************************************************
2886 * GetProcessHandleCount (KERNEL32.@)
2888 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
2890 NTSTATUS status;
2892 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
2893 cnt, sizeof(*cnt), NULL);
2894 if (status) SetLastError( RtlNtStatusToDosError(status) );
2895 return !status;
2898 /***********************************************************************
2899 * ProcessIdToSessionId (KERNEL32.@)
2900 * This function is available on Terminal Server 4SP4 and Windows 2000
2902 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2904 /* According to MSDN, if the calling process is not in a terminal
2905 * services environment, then the sessionid returned is zero.
2907 *sessionid_ptr = 0;
2908 return TRUE;
2912 /***********************************************************************
2913 * RegisterServiceProcess (KERNEL.491)
2914 * RegisterServiceProcess (KERNEL32.@)
2916 * A service process calls this function to ensure that it continues to run
2917 * even after a user logged off.
2919 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2921 /* I don't think that Wine needs to do anything in this function */
2922 return 1; /* success */
2926 /**********************************************************************
2927 * IsWow64Process (KERNEL32.@)
2929 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
2931 FIXME("(%p %p) stub!\n", hProcess, Wow64Process);
2932 *Wow64Process = FALSE;
2933 return TRUE;
2937 /***********************************************************************
2938 * GetCurrentProcess (KERNEL32.@)
2940 * Get a handle to the current process.
2942 * PARAMS
2943 * None.
2945 * RETURNS
2946 * A handle representing the current process.
2948 #undef GetCurrentProcess
2949 HANDLE WINAPI GetCurrentProcess(void)
2951 return (HANDLE)0xffffffff;
2954 /***********************************************************************
2955 * CmdBatNotification (KERNEL32.@)
2957 * Notifies the system that a batch file has started or finished.
2959 * PARAMS
2960 * bBatchRunning [I] TRUE if a batch file has started or
2961 * FALSE if a batch file has finished executing.
2963 * RETURNS
2964 * Unknown.
2966 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
2968 FIXME("%d\n", bBatchRunning);
2969 return FALSE;
2973 /***********************************************************************
2974 * RegisterApplicationRestart (KERNEL32.@)
2976 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
2978 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);
2980 return S_OK;