push ef737496cee0c8b8fe068a5599386f0bf80a0714
[wine/hacks.git] / dlls / kernel32 / process.c
blob8e5999fb2678083d139462b51fedc886069dd9c6
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 "winioctl.h"
49 #include "winternl.h"
50 #include "kernel_private.h"
51 #include "wine/exception.h"
52 #include "wine/server.h"
53 #include "wine/unicode.h"
54 #include "wine/debug.h"
56 #ifdef HAVE_VALGRIND_MEMCHECK_H
57 #include <valgrind/memcheck.h>
58 #endif
60 WINE_DEFAULT_DEBUG_CHANNEL(process);
61 WINE_DECLARE_DEBUG_CHANNEL(file);
62 WINE_DECLARE_DEBUG_CHANNEL(relay);
64 typedef struct
66 LPSTR lpEnvAddress;
67 LPSTR lpCmdLine;
68 LPSTR lpCmdShow;
69 DWORD dwReserved;
70 } LOADPARMS32;
72 static UINT process_error_mode;
74 static DWORD shutdown_flags = 0;
75 static DWORD shutdown_priority = 0x280;
76 static DWORD process_dword;
78 HMODULE kernel32_handle = 0;
80 const WCHAR *DIR_Windows = NULL;
81 const WCHAR *DIR_System = NULL;
83 /* Process flags */
84 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
85 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
86 #define PDB32_DOS_PROC 0x0010 /* Dos process */
87 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
88 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
89 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
91 static const WCHAR comW[] = {'.','c','o','m',0};
92 static const WCHAR batW[] = {'.','b','a','t',0};
93 static const WCHAR cmdW[] = {'.','c','m','d',0};
94 static const WCHAR pifW[] = {'.','p','i','f',0};
95 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
97 static void exec_process( LPCWSTR name );
99 extern void SHELL_LoadRegistry(void);
102 /***********************************************************************
103 * contains_path
105 static inline int contains_path( LPCWSTR name )
107 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
111 /***********************************************************************
112 * is_special_env_var
114 * Check if an environment variable needs to be handled specially when
115 * passed through the Unix environment (i.e. prefixed with "WINE").
117 static inline int is_special_env_var( const char *var )
119 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
120 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
121 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
122 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
126 /***************************************************************************
127 * get_builtin_path
129 * Get the path of a builtin module when the native file does not exist.
131 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
133 WCHAR *file_part;
134 UINT len = strlenW( DIR_System );
136 if (contains_path( libname ))
138 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
139 filename, &file_part ) > size * sizeof(WCHAR))
140 return FALSE; /* too long */
142 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
143 return FALSE;
144 while (filename[len] == '\\') len++;
145 if (filename + len != file_part) return FALSE;
147 else
149 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
150 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
151 file_part = filename + len;
152 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
153 strcpyW( file_part, libname );
155 if (ext && !strchrW( file_part, '.' ))
157 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
158 return FALSE; /* too long */
159 strcatW( file_part, ext );
161 return TRUE;
165 /***********************************************************************
166 * open_builtin_exe_file
168 * Open an exe file for a builtin exe.
170 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
171 int test_only, int *file_exists )
173 char exename[MAX_PATH];
174 WCHAR *p;
175 UINT i, len;
177 *file_exists = 0;
178 if ((p = strrchrW( name, '/' ))) name = p + 1;
179 if ((p = strrchrW( name, '\\' ))) name = p + 1;
181 /* we don't want to depend on the current codepage here */
182 len = strlenW( name ) + 1;
183 if (len >= sizeof(exename)) return NULL;
184 for (i = 0; i < len; i++)
186 if (name[i] > 127) return NULL;
187 exename[i] = (char)name[i];
188 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
190 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
194 /***********************************************************************
195 * open_exe_file
197 * Open a specific exe file, taking load order into account.
198 * Returns the file handle or 0 for a builtin exe.
200 static HANDLE open_exe_file( const WCHAR *name )
202 HANDLE handle;
204 TRACE("looking for %s\n", debugstr_w(name) );
206 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
207 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
209 WCHAR buffer[MAX_PATH];
210 /* file doesn't exist, check for builtin */
211 if (!contains_path( name )) goto error;
212 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
213 handle = 0;
215 return handle;
217 error:
218 SetLastError( ERROR_FILE_NOT_FOUND );
219 return INVALID_HANDLE_VALUE;
223 /***********************************************************************
224 * find_exe_file
226 * Open an exe file, and return the full name and file handle.
227 * Returns FALSE if file could not be found.
228 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
229 * If file is a builtin exe, returns TRUE and sets handle to 0.
231 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
233 static const WCHAR exeW[] = {'.','e','x','e',0};
234 int file_exists;
236 TRACE("looking for %s\n", debugstr_w(name) );
238 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
239 !get_builtin_path( name, exeW, buffer, buflen ))
241 /* no builtin found, try native without extension in case it is a Unix app */
243 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
245 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
246 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
247 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
248 return TRUE;
250 return FALSE;
253 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
254 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
255 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
256 return TRUE;
258 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
259 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
260 if (file_exists)
262 *handle = 0;
263 return TRUE;
266 return FALSE;
270 /***********************************************************************
271 * build_initial_environment
273 * Build the Win32 environment from the Unix environment
275 static BOOL build_initial_environment( char **environ )
277 SIZE_T size = 1;
278 char **e;
279 WCHAR *p, *endptr;
280 void *ptr;
282 /* Compute the total size of the Unix environment */
283 for (e = environ; *e; e++)
285 if (is_special_env_var( *e )) continue;
286 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
288 size *= sizeof(WCHAR);
290 /* Now allocate the environment */
291 ptr = NULL;
292 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
293 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
294 return FALSE;
296 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
297 endptr = p + size / sizeof(WCHAR);
299 /* And fill it with the Unix environment */
300 for (e = environ; *e; e++)
302 char *str = *e;
304 /* skip Unix special variables and use the Wine variants instead */
305 if (!strncmp( str, "WINE", 4 ))
307 if (is_special_env_var( str + 4 )) str += 4;
308 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
310 else if (is_special_env_var( str )) continue; /* skip it */
312 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
313 p += strlenW(p) + 1;
315 *p = 0;
316 return TRUE;
320 /***********************************************************************
321 * set_registry_variables
323 * Set environment variables by enumerating the values of a key;
324 * helper for set_registry_environment().
325 * Note that Windows happily truncates the value if it's too big.
327 static void set_registry_variables( HANDLE hkey, ULONG type )
329 UNICODE_STRING env_name, env_value;
330 NTSTATUS status;
331 DWORD size;
332 int index;
333 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
334 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
336 for (index = 0; ; index++)
338 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
339 buffer, sizeof(buffer), &size );
340 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
341 break;
342 if (info->Type != type)
343 continue;
344 env_name.Buffer = info->Name;
345 env_name.Length = env_name.MaximumLength = info->NameLength;
346 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
347 env_value.Length = env_value.MaximumLength = info->DataLength;
348 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
349 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
350 if (info->Type == REG_EXPAND_SZ)
352 WCHAR buf_expanded[1024];
353 UNICODE_STRING env_expanded;
354 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
355 env_expanded.Buffer=buf_expanded;
356 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
357 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
358 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
360 else
362 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
368 /***********************************************************************
369 * set_registry_environment
371 * Set the environment variables specified in the registry.
373 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
374 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
375 * on the order in which the variables are processed. But on Windows it
376 * does not really matter since they only use %SystemDrive% and
377 * %SystemRoot% which are predefined. But Wine defines these in the
378 * registry, so we need two passes.
380 static void set_registry_environment(void)
382 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
383 'S','y','s','t','e','m','\\',
384 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
385 'C','o','n','t','r','o','l','\\',
386 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
387 'E','n','v','i','r','o','n','m','e','n','t',0};
388 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
390 OBJECT_ATTRIBUTES attr;
391 UNICODE_STRING nameW;
392 HANDLE hkey;
394 attr.Length = sizeof(attr);
395 attr.RootDirectory = 0;
396 attr.ObjectName = &nameW;
397 attr.Attributes = 0;
398 attr.SecurityDescriptor = NULL;
399 attr.SecurityQualityOfService = NULL;
401 /* first the system environment variables */
402 RtlInitUnicodeString( &nameW, env_keyW );
403 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
405 set_registry_variables( hkey, REG_SZ );
406 set_registry_variables( hkey, REG_EXPAND_SZ );
407 NtClose( hkey );
410 /* then the ones for the current user */
411 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return;
412 RtlInitUnicodeString( &nameW, envW );
413 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
415 set_registry_variables( hkey, REG_SZ );
416 set_registry_variables( hkey, REG_EXPAND_SZ );
417 NtClose( hkey );
419 NtClose( attr.RootDirectory );
423 /***********************************************************************
424 * set_library_wargv
426 * Set the Wine library Unicode argv global variables.
428 static void set_library_wargv( char **argv )
430 int argc;
431 char *q;
432 WCHAR *p;
433 WCHAR **wargv;
434 DWORD total = 0;
436 for (argc = 0; argv[argc]; argc++)
437 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
439 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
440 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
441 p = (WCHAR *)(wargv + argc + 1);
442 for (argc = 0; argv[argc]; argc++)
444 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
445 wargv[argc] = p;
446 p += reslen;
447 total -= reslen;
449 wargv[argc] = NULL;
451 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
453 for (argc = 0; wargv[argc]; argc++)
454 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
456 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
457 q = (char *)(argv + argc + 1);
458 for (argc = 0; wargv[argc]; argc++)
460 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
461 argv[argc] = q;
462 q += reslen;
463 total -= reslen;
465 argv[argc] = NULL;
467 __wine_main_argc = argc;
468 __wine_main_argv = argv;
469 __wine_main_wargv = wargv;
473 /***********************************************************************
474 * build_command_line
476 * Build the command line of a process from the argv array.
478 * Note that it does NOT necessarily include the file name.
479 * Sometimes we don't even have any command line options at all.
481 * We must quote and escape characters so that the argv array can be rebuilt
482 * from the command line:
483 * - spaces and tabs must be quoted
484 * 'a b' -> '"a b"'
485 * - quotes must be escaped
486 * '"' -> '\"'
487 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
488 * resulting in an odd number of '\' followed by a '"'
489 * '\"' -> '\\\"'
490 * '\\"' -> '\\\\\"'
491 * - '\'s that are not followed by a '"' can be left as is
492 * 'a\b' == 'a\b'
493 * 'a\\b' == 'a\\b'
495 static BOOL build_command_line( WCHAR **argv )
497 int len;
498 WCHAR **arg;
499 LPWSTR p;
500 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
502 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
504 len = 0;
505 for (arg = argv; *arg; arg++)
507 int has_space,bcount;
508 WCHAR* a;
510 has_space=0;
511 bcount=0;
512 a=*arg;
513 if( !*a ) has_space=1;
514 while (*a!='\0') {
515 if (*a=='\\') {
516 bcount++;
517 } else {
518 if (*a==' ' || *a=='\t') {
519 has_space=1;
520 } else if (*a=='"') {
521 /* doubling of '\' preceding a '"',
522 * plus escaping of said '"'
524 len+=2*bcount+1;
526 bcount=0;
528 a++;
530 len+=(a-*arg)+1 /* for the separating space */;
531 if (has_space)
532 len+=2; /* for the quotes */
535 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
536 return FALSE;
538 p = rupp->CommandLine.Buffer;
539 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
540 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
541 for (arg = argv; *arg; arg++)
543 int has_space,has_quote;
544 WCHAR* a;
546 /* Check for quotes and spaces in this argument */
547 has_space=has_quote=0;
548 a=*arg;
549 if( !*a ) has_space=1;
550 while (*a!='\0') {
551 if (*a==' ' || *a=='\t') {
552 has_space=1;
553 if (has_quote)
554 break;
555 } else if (*a=='"') {
556 has_quote=1;
557 if (has_space)
558 break;
560 a++;
563 /* Now transfer it to the command line */
564 if (has_space)
565 *p++='"';
566 if (has_quote) {
567 int bcount;
568 WCHAR* a;
570 bcount=0;
571 a=*arg;
572 while (*a!='\0') {
573 if (*a=='\\') {
574 *p++=*a;
575 bcount++;
576 } else {
577 if (*a=='"') {
578 int i;
580 /* Double all the '\\' preceding this '"', plus one */
581 for (i=0;i<=bcount;i++)
582 *p++='\\';
583 *p++='"';
584 } else {
585 *p++=*a;
587 bcount=0;
589 a++;
591 } else {
592 WCHAR* x = *arg;
593 while ((*p=*x++)) p++;
595 if (has_space)
596 *p++='"';
597 *p++=' ';
599 if (p > rupp->CommandLine.Buffer)
600 p--; /* remove last space */
601 *p = '\0';
603 return TRUE;
607 /***********************************************************************
608 * init_current_directory
610 * Initialize the current directory from the Unix cwd or the parent info.
612 static void init_current_directory( CURDIR *cur_dir )
614 UNICODE_STRING dir_str;
615 char *cwd;
616 int size;
618 /* if we received a cur dir from the parent, try this first */
620 if (cur_dir->DosPath.Length)
622 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
625 /* now try to get it from the Unix cwd */
627 for (size = 256; ; size *= 2)
629 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
630 if (getcwd( cwd, size )) break;
631 HeapFree( GetProcessHeap(), 0, cwd );
632 if (errno == ERANGE) continue;
633 cwd = NULL;
634 break;
637 if (cwd)
639 WCHAR *dirW;
640 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
641 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
643 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
644 RtlInitUnicodeString( &dir_str, dirW );
645 RtlSetCurrentDirectory_U( &dir_str );
646 RtlFreeUnicodeString( &dir_str );
650 if (!cur_dir->DosPath.Length) /* still not initialized */
652 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
653 "starting in the Windows directory.\n", cwd ? cwd : "" );
654 RtlInitUnicodeString( &dir_str, DIR_Windows );
655 RtlSetCurrentDirectory_U( &dir_str );
657 HeapFree( GetProcessHeap(), 0, cwd );
659 done:
660 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
661 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
665 /***********************************************************************
666 * init_windows_dirs
668 * Initialize the windows and system directories from the environment.
670 static void init_windows_dirs(void)
672 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
674 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
675 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
676 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
677 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
679 DWORD len;
680 WCHAR *buffer;
682 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
684 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
685 GetEnvironmentVariableW( windirW, buffer, len );
686 DIR_Windows = buffer;
688 else DIR_Windows = default_windirW;
690 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
692 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
693 GetEnvironmentVariableW( winsysdirW, buffer, len );
694 DIR_System = buffer;
696 else
698 len = strlenW( DIR_Windows );
699 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
700 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
701 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
702 DIR_System = buffer;
705 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
706 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
707 debugstr_w(DIR_Windows) );
708 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
709 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
710 debugstr_w(DIR_System) );
712 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
713 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
715 /* set the directories in ntdll too */
716 __wine_init_windows_dir( DIR_Windows, DIR_System );
720 /***********************************************************************
721 * process_init
723 * Main process initialisation code
725 static BOOL process_init(void)
727 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
728 PEB *peb = NtCurrentTeb()->Peb;
729 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
731 PTHREAD_Init();
733 setbuf(stdout,NULL);
734 setbuf(stderr,NULL);
736 kernel32_handle = GetModuleHandleW(kernel32W);
738 LOCALE_Init();
740 if (!params->Environment)
742 /* Copy the parent environment */
743 if (!build_initial_environment( __wine_main_environ )) return FALSE;
745 /* convert old configuration to new format */
746 convert_old_config();
748 set_registry_environment();
751 init_windows_dirs();
752 init_current_directory( &params->CurrentDirectory );
754 return TRUE;
758 /***********************************************************************
759 * init_stack
761 * Allocate the stack of new process.
763 static void *init_stack(void)
765 void *base;
766 SIZE_T stack_size, page_size = getpagesize();
767 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
769 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
770 stack_size += page_size; /* for the guard page */
771 stack_size = (stack_size + 0xffff) & ~0xffff; /* round to 64K boundary */
772 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
774 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
776 ERR( "failed to allocate main process stack\n" );
777 ExitProcess( 1 );
780 /* note: limit is lower than base since the stack grows down */
781 NtCurrentTeb()->DeallocationStack = base;
782 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
783 NtCurrentTeb()->Tib.StackLimit = (char *)base + page_size;
785 #ifdef VALGRIND_STACK_REGISTER
786 /* no need to de-register the stack as it's the one of the main thread */
787 VALGRIND_STACK_REGISTER(NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase);
788 #endif
790 /* setup guard page */
791 VirtualProtect( base, page_size, PAGE_NOACCESS, NULL );
792 return NtCurrentTeb()->Tib.StackBase;
796 /***********************************************************************
797 * start_process
799 * Startup routine of a new process. Runs on the new process stack.
801 static void start_process( void *arg )
803 __TRY
805 PEB *peb = NtCurrentTeb()->Peb;
806 IMAGE_NT_HEADERS *nt;
807 LPTHREAD_START_ROUTINE entry;
809 LdrInitializeThunk( 0, 0, 0, 0 );
811 nt = RtlImageNtHeader( peb->ImageBaseAddress );
812 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
813 nt->OptionalHeader.AddressOfEntryPoint);
815 if (TRACE_ON(relay))
816 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
817 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
819 SetLastError( 0 ); /* clear error code */
820 if (peb->BeingDebugged) DbgBreakPoint();
821 ExitThread( entry( peb ) );
823 __EXCEPT(UnhandledExceptionFilter)
825 TerminateThread( GetCurrentThread(), GetExceptionCode() );
827 __ENDTRY
831 /***********************************************************************
832 * set_process_name
834 * Change the process name in the ps output.
836 static void set_process_name( int argc, char *argv[] )
838 #ifdef HAVE_PRCTL
839 int i, offset;
840 char *p, *prctl_name = argv[1];
841 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
843 #ifndef PR_SET_NAME
844 # define PR_SET_NAME 15
845 #endif
847 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
848 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
850 if (prctl( PR_SET_NAME, prctl_name ) != -1)
852 offset = argv[1] - argv[0];
853 memmove( argv[1] - offset, argv[1], end - argv[1] );
854 memset( end - offset, 0, offset );
855 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
856 argv[i-1] = NULL;
858 else
859 #endif /* HAVE_PRCTL */
861 /* remove argv[0] */
862 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
867 /***********************************************************************
868 * __wine_kernel_init
870 * Wine initialisation: load and start the main exe file.
872 void __wine_kernel_init(void)
874 static const WCHAR dotW[] = {'.',0};
875 static const WCHAR exeW[] = {'.','e','x','e',0};
877 WCHAR *p, main_exe_name[MAX_PATH+1];
878 PEB *peb = NtCurrentTeb()->Peb;
880 /* Initialize everything */
881 if (!process_init()) exit(1);
882 set_process_name( __wine_main_argc, __wine_main_argv );
883 set_library_wargv( __wine_main_argv );
885 if (peb->ProcessParameters->ImagePathName.Buffer)
887 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
889 else
891 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
892 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
894 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
895 ExitProcess( GetLastError() );
897 if (!build_command_line( __wine_main_wargv )) goto error;
900 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
901 p = strrchrW( main_exe_name, '.' );
902 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
904 TRACE( "starting process name=%s argv[0]=%s\n",
905 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
907 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
908 MODULE_get_dll_load_path(main_exe_name) );
910 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
912 char msg[1024];
913 DWORD error = GetLastError();
915 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
916 if (error == ERROR_BAD_EXE_FORMAT ||
917 error == ERROR_INVALID_ADDRESS ||
918 error == ERROR_NOT_ENOUGH_MEMORY)
920 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
921 /* if we get back here, it failed */
924 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
925 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
926 ExitProcess( error );
929 /* switch to the new stack */
930 wine_switch_to_stack( start_process, NULL, init_stack() );
932 error:
933 ExitProcess( GetLastError() );
937 /***********************************************************************
938 * build_argv
940 * Build an argv array from a command-line.
941 * 'reserved' is the number of args to reserve before the first one.
943 static char **build_argv( const WCHAR *cmdlineW, int reserved )
945 int argc;
946 char** argv;
947 char *arg,*s,*d,*cmdline;
948 int in_quotes,bcount,len;
950 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
951 if (!(cmdline = malloc(len))) return NULL;
952 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
954 argc=reserved+1;
955 bcount=0;
956 in_quotes=0;
957 s=cmdline;
958 while (1) {
959 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
960 /* space */
961 argc++;
962 /* skip the remaining spaces */
963 while (*s==' ' || *s=='\t') {
964 s++;
966 if (*s=='\0')
967 break;
968 bcount=0;
969 continue;
970 } else if (*s=='\\') {
971 /* '\', count them */
972 bcount++;
973 } else if ((*s=='"') && ((bcount & 1)==0)) {
974 /* unescaped '"' */
975 in_quotes=!in_quotes;
976 bcount=0;
977 } else {
978 /* a regular character */
979 bcount=0;
981 s++;
983 argv=malloc(argc*sizeof(*argv));
984 if (!argv)
985 return NULL;
987 arg=d=s=cmdline;
988 bcount=0;
989 in_quotes=0;
990 argc=reserved;
991 while (*s) {
992 if ((*s==' ' || *s=='\t') && !in_quotes) {
993 /* Close the argument and copy it */
994 *d=0;
995 argv[argc++]=arg;
997 /* skip the remaining spaces */
998 do {
999 s++;
1000 } while (*s==' ' || *s=='\t');
1002 /* Start with a new argument */
1003 arg=d=s;
1004 bcount=0;
1005 } else if (*s=='\\') {
1006 /* '\\' */
1007 *d++=*s++;
1008 bcount++;
1009 } else if (*s=='"') {
1010 /* '"' */
1011 if ((bcount & 1)==0) {
1012 /* Preceded by an even number of '\', this is half that
1013 * number of '\', plus a '"' which we discard.
1015 d-=bcount/2;
1016 s++;
1017 in_quotes=!in_quotes;
1018 } else {
1019 /* Preceded by an odd number of '\', this is half that
1020 * number of '\' followed by a '"'
1022 d=d-bcount/2-1;
1023 *d++='"';
1024 s++;
1026 bcount=0;
1027 } else {
1028 /* a regular character */
1029 *d++=*s++;
1030 bcount=0;
1033 if (*arg) {
1034 *d='\0';
1035 argv[argc++]=arg;
1037 argv[argc]=NULL;
1039 return argv;
1043 /***********************************************************************
1044 * alloc_env_string
1046 * Allocate an environment string; helper for build_envp
1048 static char *alloc_env_string( const char *name, const char *value )
1050 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1051 strcpy( ret, name );
1052 strcat( ret, value );
1053 return ret;
1056 /***********************************************************************
1057 * build_envp
1059 * Build the environment of a new child process.
1061 static char **build_envp( const WCHAR *envW )
1063 const WCHAR *end;
1064 char **envp;
1065 char *env, *p;
1066 int count = 0, length;
1068 for (end = envW; *end; count++) end += strlenW(end) + 1;
1069 end++;
1070 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1071 if (!(env = malloc( length ))) return NULL;
1072 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1074 count += 4;
1076 if ((envp = malloc( count * sizeof(*envp) )))
1078 char **envptr = envp;
1080 /* some variables must not be modified, so we get them directly from the unix env */
1081 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1082 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1083 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1084 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1085 /* now put the Windows environment strings */
1086 for (p = env; *p; p += strlen(p) + 1)
1088 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1089 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1090 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1091 if (is_special_env_var( p )) /* prefix it with "WINE" */
1092 *envptr++ = alloc_env_string( "WINE", p );
1093 else
1094 *envptr++ = p;
1096 *envptr = 0;
1098 return envp;
1102 /***********************************************************************
1103 * fork_and_exec
1105 * Fork and exec a new Unix binary, checking for errors.
1107 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1108 const WCHAR *env, const char *newdir, DWORD flags )
1110 int fd[2];
1111 int pid, err;
1113 if (!env) env = GetEnvironmentStringsW();
1115 if (pipe(fd) == -1)
1117 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1118 return -1;
1120 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1121 if (!(pid = fork())) /* child */
1123 char **argv = build_argv( cmdline, 0 );
1124 char **envp = build_envp( env );
1125 close( fd[0] );
1127 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)) setsid();
1129 /* Reset signals that we previously set to SIG_IGN */
1130 signal( SIGPIPE, SIG_DFL );
1131 signal( SIGCHLD, SIG_DFL );
1133 if (newdir) chdir(newdir);
1135 if (argv && envp) execve( filename, argv, envp );
1136 err = errno;
1137 write( fd[1], &err, sizeof(err) );
1138 _exit(1);
1140 close( fd[1] );
1141 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1143 errno = err;
1144 pid = -1;
1146 if (pid == -1) FILE_SetDosError();
1147 close( fd[0] );
1148 return pid;
1152 /***********************************************************************
1153 * create_user_params
1155 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1156 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1157 const STARTUPINFOW *startup )
1159 RTL_USER_PROCESS_PARAMETERS *params;
1160 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1161 NTSTATUS status;
1162 WCHAR buffer[MAX_PATH];
1164 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1165 lstrcpynW( buffer, filename, MAX_PATH );
1166 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1167 lstrcpynW( buffer, filename, MAX_PATH );
1168 RtlInitUnicodeString( &image_str, buffer );
1170 RtlInitUnicodeString( &cmdline_str, cmdline );
1171 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1172 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1173 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1174 if (startup->lpReserved2 && startup->cbReserved2)
1176 runtime.Length = 0;
1177 runtime.MaximumLength = startup->cbReserved2;
1178 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1181 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1182 cur_dir ? &curdir_str : NULL,
1183 &cmdline_str, env,
1184 startup->lpTitle ? &title : NULL,
1185 startup->lpDesktop ? &desktop : NULL,
1186 NULL,
1187 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1188 if (status != STATUS_SUCCESS)
1190 SetLastError( RtlNtStatusToDosError(status) );
1191 return NULL;
1194 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1195 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1197 if (startup->dwFlags & STARTF_USESTDHANDLES)
1199 params->hStdInput = startup->hStdInput;
1200 params->hStdOutput = startup->hStdOutput;
1201 params->hStdError = startup->hStdError;
1203 else
1205 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1206 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1207 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1209 params->dwX = startup->dwX;
1210 params->dwY = startup->dwY;
1211 params->dwXSize = startup->dwXSize;
1212 params->dwYSize = startup->dwYSize;
1213 params->dwXCountChars = startup->dwXCountChars;
1214 params->dwYCountChars = startup->dwYCountChars;
1215 params->dwFillAttribute = startup->dwFillAttribute;
1216 params->dwFlags = startup->dwFlags;
1217 params->wShowWindow = startup->wShowWindow;
1218 return params;
1222 /***********************************************************************
1223 * create_process
1225 * Create a new process. If hFile is a valid handle we have an exe
1226 * file, otherwise it is a Winelib app.
1228 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1229 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1230 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1231 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1232 void *res_start, void *res_end, int exec_only )
1234 BOOL ret, success = FALSE;
1235 HANDLE process_info;
1236 WCHAR *env_end;
1237 char *winedebug = NULL;
1238 RTL_USER_PROCESS_PARAMETERS *params;
1239 int socketfd[2];
1240 pid_t pid;
1241 int err;
1243 if (!env) RtlAcquirePebLock();
1245 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1247 if (!env) RtlReleasePebLock();
1248 return FALSE;
1250 env_end = params->Environment;
1251 while (*env_end)
1253 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1254 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1256 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1257 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1258 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1260 env_end += strlenW(env_end) + 1;
1262 env_end++;
1264 /* create the socket for the new process */
1266 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1268 if (!env) RtlReleasePebLock();
1269 HeapFree( GetProcessHeap(), 0, winedebug );
1270 RtlDestroyProcessParameters( params );
1271 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1272 return FALSE;
1274 wine_server_send_fd( socketfd[1] );
1275 close( socketfd[1] );
1277 /* create the process on the server side */
1279 SERVER_START_REQ( new_process )
1281 req->inherit_all = inherit;
1282 req->create_flags = flags;
1283 req->socket_fd = socketfd[1];
1284 req->exe_file = hFile;
1285 req->process_access = PROCESS_ALL_ACCESS;
1286 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1287 req->thread_access = THREAD_ALL_ACCESS;
1288 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1289 req->hstdin = params->hStdInput;
1290 req->hstdout = params->hStdOutput;
1291 req->hstderr = params->hStdError;
1293 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1295 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1296 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1297 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1298 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1300 else
1302 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1303 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1304 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1307 wine_server_add_data( req, params, params->Size );
1308 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1309 if ((ret = !wine_server_call_err( req )))
1311 info->dwProcessId = (DWORD)reply->pid;
1312 info->dwThreadId = (DWORD)reply->tid;
1313 info->hProcess = reply->phandle;
1314 info->hThread = reply->thandle;
1316 process_info = reply->info;
1318 SERVER_END_REQ;
1320 if (!env) RtlReleasePebLock();
1321 RtlDestroyProcessParameters( params );
1322 if (!ret)
1324 close( socketfd[0] );
1325 HeapFree( GetProcessHeap(), 0, winedebug );
1326 return FALSE;
1329 /* create the child process */
1331 if (exec_only || !(pid = fork())) /* child */
1333 char preloader_reserve[64], socket_env[64];
1334 char **argv = build_argv( cmd_line, 1 );
1336 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)) setsid();
1338 /* Reset signals that we previously set to SIG_IGN */
1339 signal( SIGPIPE, SIG_DFL );
1340 signal( SIGCHLD, SIG_DFL );
1342 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1343 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1344 (unsigned long)res_start, (unsigned long)res_end );
1346 putenv( preloader_reserve );
1347 putenv( socket_env );
1348 if (winedebug) putenv( winedebug );
1349 if (unixdir) chdir(unixdir);
1351 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1352 _exit(1);
1355 /* this is the parent */
1357 close( socketfd[0] );
1358 HeapFree( GetProcessHeap(), 0, winedebug );
1359 if (pid == -1)
1361 FILE_SetDosError();
1362 goto error;
1365 /* wait for the new process info to be ready */
1367 WaitForSingleObject( process_info, INFINITE );
1368 SERVER_START_REQ( get_new_process_info )
1370 req->info = process_info;
1371 wine_server_call( req );
1372 success = reply->success;
1373 err = reply->exit_code;
1375 SERVER_END_REQ;
1377 if (!success)
1379 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1380 goto error;
1382 CloseHandle( process_info );
1383 return success;
1385 error:
1386 CloseHandle( process_info );
1387 CloseHandle( info->hProcess );
1388 CloseHandle( info->hThread );
1389 info->hProcess = info->hThread = 0;
1390 info->dwProcessId = info->dwThreadId = 0;
1391 return FALSE;
1395 /***********************************************************************
1396 * create_vdm_process
1398 * Create a new VDM process for a 16-bit or DOS application.
1400 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1401 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1402 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1403 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1405 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1407 BOOL ret;
1408 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1409 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1411 if (!new_cmd_line)
1413 SetLastError( ERROR_OUTOFMEMORY );
1414 return FALSE;
1416 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1417 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1418 flags, startup, info, unixdir, NULL, NULL, exec_only );
1419 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1420 return ret;
1424 /***********************************************************************
1425 * create_cmd_process
1427 * Create a new cmd shell process for a .BAT file.
1429 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1430 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1431 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1432 LPPROCESS_INFORMATION info )
1435 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1436 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1437 WCHAR comspec[MAX_PATH];
1438 WCHAR *newcmdline;
1439 BOOL ret;
1441 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1442 return FALSE;
1443 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1444 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1445 return FALSE;
1447 strcpyW( newcmdline, comspec );
1448 strcatW( newcmdline, slashcW );
1449 strcatW( newcmdline, cmd_line );
1450 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1451 flags, env, cur_dir, startup, info );
1452 HeapFree( GetProcessHeap(), 0, newcmdline );
1453 return ret;
1457 /*************************************************************************
1458 * get_file_name
1460 * Helper for CreateProcess: retrieve the file name to load from the
1461 * app name and command line. Store the file name in buffer, and
1462 * return a possibly modified command line.
1463 * Also returns a handle to the opened file if it's a Windows binary.
1465 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1466 int buflen, HANDLE *handle )
1468 static const WCHAR quotesW[] = {'"','%','s','"',0};
1470 WCHAR *name, *pos, *ret = NULL;
1471 const WCHAR *p;
1472 BOOL got_space;
1474 /* if we have an app name, everything is easy */
1476 if (appname)
1478 /* use the unmodified app name as file name */
1479 lstrcpynW( buffer, appname, buflen );
1480 *handle = open_exe_file( buffer );
1481 if (!(ret = cmdline) || !cmdline[0])
1483 /* no command-line, create one */
1484 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1485 sprintfW( ret, quotesW, appname );
1487 return ret;
1490 if (!cmdline)
1492 SetLastError( ERROR_INVALID_PARAMETER );
1493 return NULL;
1496 /* first check for a quoted file name */
1498 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1500 int len = p - cmdline - 1;
1501 /* extract the quoted portion as file name */
1502 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1503 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1504 name[len] = 0;
1506 if (find_exe_file( name, buffer, buflen, handle ))
1507 ret = cmdline; /* no change necessary */
1508 goto done;
1511 /* now try the command-line word by word */
1513 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1514 return NULL;
1515 pos = name;
1516 p = cmdline;
1517 got_space = FALSE;
1519 while (*p)
1521 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1522 *pos = 0;
1523 if (find_exe_file( name, buffer, buflen, handle ))
1525 ret = cmdline;
1526 break;
1528 if (*p) got_space = TRUE;
1531 if (ret && got_space) /* now build a new command-line with quotes */
1533 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1534 goto done;
1535 sprintfW( ret, quotesW, name );
1536 strcatW( ret, p );
1539 done:
1540 HeapFree( GetProcessHeap(), 0, name );
1541 return ret;
1545 /**********************************************************************
1546 * CreateProcessA (KERNEL32.@)
1548 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1549 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1550 DWORD flags, LPVOID env, LPCSTR cur_dir,
1551 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1553 BOOL ret = FALSE;
1554 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1555 UNICODE_STRING desktopW, titleW;
1556 STARTUPINFOW infoW;
1558 desktopW.Buffer = NULL;
1559 titleW.Buffer = NULL;
1560 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1561 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1562 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1564 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1565 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1567 memcpy( &infoW, startup_info, sizeof(infoW) );
1568 infoW.lpDesktop = desktopW.Buffer;
1569 infoW.lpTitle = titleW.Buffer;
1571 if (startup_info->lpReserved)
1572 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1573 debugstr_a(startup_info->lpReserved));
1575 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1576 inherit, flags, env, cur_dirW, &infoW, info );
1577 done:
1578 HeapFree( GetProcessHeap(), 0, app_nameW );
1579 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1580 HeapFree( GetProcessHeap(), 0, cur_dirW );
1581 RtlFreeUnicodeString( &desktopW );
1582 RtlFreeUnicodeString( &titleW );
1583 return ret;
1587 /**********************************************************************
1588 * CreateProcessW (KERNEL32.@)
1590 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1591 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1592 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1593 LPPROCESS_INFORMATION info )
1595 BOOL retv = FALSE;
1596 HANDLE hFile = 0;
1597 char *unixdir = NULL;
1598 WCHAR name[MAX_PATH];
1599 WCHAR *tidy_cmdline, *p, *envW = env;
1600 void *res_start, *res_end;
1602 /* Process the AppName and/or CmdLine to get module name and path */
1604 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1606 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1607 return FALSE;
1608 if (hFile == INVALID_HANDLE_VALUE) goto done;
1610 /* Warn if unsupported features are used */
1612 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1613 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1614 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1615 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1616 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1618 if (cur_dir)
1620 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1622 SetLastError(ERROR_DIRECTORY);
1623 goto done;
1626 else
1628 WCHAR buf[MAX_PATH];
1629 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1632 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1634 char *p = env;
1635 DWORD lenW;
1637 while (*p) p += strlen(p) + 1;
1638 p++; /* final null */
1639 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1640 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1641 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1642 flags |= CREATE_UNICODE_ENVIRONMENT;
1645 info->hThread = info->hProcess = 0;
1646 info->dwProcessId = info->dwThreadId = 0;
1648 /* Determine executable type */
1650 if (!hFile) /* builtin exe */
1652 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1653 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1654 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1655 goto done;
1658 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1660 case BINARY_PE_EXE:
1661 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1662 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1663 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1664 break;
1665 case BINARY_OS216:
1666 case BINARY_WIN16:
1667 case BINARY_DOS:
1668 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1669 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1670 inherit, flags, startup_info, info, unixdir, FALSE );
1671 break;
1672 case BINARY_PE_DLL:
1673 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1674 SetLastError( ERROR_BAD_EXE_FORMAT );
1675 break;
1676 case BINARY_UNIX_LIB:
1677 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1678 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1679 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1680 break;
1681 case BINARY_UNKNOWN:
1682 /* check for .com or .bat extension */
1683 if ((p = strrchrW( name, '.' )))
1685 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1687 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1688 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1689 inherit, flags, startup_info, info, unixdir, FALSE );
1690 break;
1692 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1694 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1695 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1696 inherit, flags, startup_info, info );
1697 break;
1700 /* fall through */
1701 case BINARY_UNIX_EXE:
1703 /* unknown file, try as unix executable */
1704 char *unix_name;
1706 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1708 if ((unix_name = wine_get_unix_file_name( name )))
1710 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags ) != -1);
1711 HeapFree( GetProcessHeap(), 0, unix_name );
1714 break;
1716 CloseHandle( hFile );
1718 done:
1719 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1720 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1721 HeapFree( GetProcessHeap(), 0, unixdir );
1722 return retv;
1726 /**********************************************************************
1727 * exec_process
1729 static void exec_process( LPCWSTR name )
1731 HANDLE hFile;
1732 WCHAR *p;
1733 void *res_start, *res_end;
1734 STARTUPINFOW startup_info;
1735 PROCESS_INFORMATION info;
1737 hFile = open_exe_file( name );
1738 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
1740 memset( &startup_info, 0, sizeof(startup_info) );
1741 startup_info.cb = sizeof(startup_info);
1743 /* Determine executable type */
1745 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1747 case BINARY_PE_EXE:
1748 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1749 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1750 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
1751 break;
1752 case BINARY_UNIX_LIB:
1753 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1754 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1755 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
1756 break;
1757 case BINARY_UNKNOWN:
1758 /* check for .com or .pif extension */
1759 if (!(p = strrchrW( name, '.' ))) break;
1760 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
1761 /* fall through */
1762 case BINARY_OS216:
1763 case BINARY_WIN16:
1764 case BINARY_DOS:
1765 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1766 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1767 FALSE, 0, &startup_info, &info, NULL, TRUE );
1768 break;
1769 default:
1770 break;
1772 CloseHandle( hFile );
1776 /***********************************************************************
1777 * wait_input_idle
1779 * Wrapper to call WaitForInputIdle USER function
1781 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1783 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1785 HMODULE mod = GetModuleHandleA( "user32.dll" );
1786 if (mod)
1788 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1789 if (ptr) return ptr( process, timeout );
1791 return 0;
1795 /***********************************************************************
1796 * WinExec (KERNEL32.@)
1798 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1800 PROCESS_INFORMATION info;
1801 STARTUPINFOA startup;
1802 char *cmdline;
1803 UINT ret;
1805 memset( &startup, 0, sizeof(startup) );
1806 startup.cb = sizeof(startup);
1807 startup.dwFlags = STARTF_USESHOWWINDOW;
1808 startup.wShowWindow = nCmdShow;
1810 /* cmdline needs to be writable for CreateProcess */
1811 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1812 strcpy( cmdline, lpCmdLine );
1814 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1815 0, NULL, NULL, &startup, &info ))
1817 /* Give 30 seconds to the app to come up */
1818 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1819 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1820 ret = 33;
1821 /* Close off the handles */
1822 CloseHandle( info.hThread );
1823 CloseHandle( info.hProcess );
1825 else if ((ret = GetLastError()) >= 32)
1827 FIXME("Strange error set by CreateProcess: %d\n", ret );
1828 ret = 11;
1830 HeapFree( GetProcessHeap(), 0, cmdline );
1831 return ret;
1835 /**********************************************************************
1836 * LoadModule (KERNEL32.@)
1838 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1840 LOADPARMS32 *params = paramBlock;
1841 PROCESS_INFORMATION info;
1842 STARTUPINFOA startup;
1843 HINSTANCE hInstance;
1844 LPSTR cmdline, p;
1845 char filename[MAX_PATH];
1846 BYTE len;
1848 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1850 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1851 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1852 return (HINSTANCE)GetLastError();
1854 len = (BYTE)params->lpCmdLine[0];
1855 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1856 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1858 strcpy( cmdline, filename );
1859 p = cmdline + strlen(cmdline);
1860 *p++ = ' ';
1861 memcpy( p, params->lpCmdLine + 1, len );
1862 p[len] = 0;
1864 memset( &startup, 0, sizeof(startup) );
1865 startup.cb = sizeof(startup);
1866 if (params->lpCmdShow)
1868 startup.dwFlags = STARTF_USESHOWWINDOW;
1869 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1872 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1873 params->lpEnvAddress, NULL, &startup, &info ))
1875 /* Give 30 seconds to the app to come up */
1876 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1877 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1878 hInstance = (HINSTANCE)33;
1879 /* Close off the handles */
1880 CloseHandle( info.hThread );
1881 CloseHandle( info.hProcess );
1883 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1885 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1886 hInstance = (HINSTANCE)11;
1889 HeapFree( GetProcessHeap(), 0, cmdline );
1890 return hInstance;
1894 /******************************************************************************
1895 * TerminateProcess (KERNEL32.@)
1897 * Terminates a process.
1899 * PARAMS
1900 * handle [I] Process to terminate.
1901 * exit_code [I] Exit code.
1903 * RETURNS
1904 * Success: TRUE.
1905 * Failure: FALSE, check GetLastError().
1907 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1909 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1910 if (status) SetLastError( RtlNtStatusToDosError(status) );
1911 return !status;
1915 /***********************************************************************
1916 * ExitProcess (KERNEL32.@)
1918 * Exits the current process.
1920 * PARAMS
1921 * status [I] Status code to exit with.
1923 * RETURNS
1924 * Nothing.
1926 void WINAPI ExitProcess( DWORD status )
1928 LdrShutdownProcess();
1929 NtTerminateProcess(GetCurrentProcess(), status);
1930 exit(status);
1934 /***********************************************************************
1935 * GetExitCodeProcess [KERNEL32.@]
1937 * Gets termination status of specified process.
1939 * PARAMS
1940 * hProcess [in] Handle to the process.
1941 * lpExitCode [out] Address to receive termination status.
1943 * RETURNS
1944 * Success: TRUE
1945 * Failure: FALSE
1947 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
1949 NTSTATUS status;
1950 PROCESS_BASIC_INFORMATION pbi;
1952 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
1953 sizeof(pbi), NULL);
1954 if (status == STATUS_SUCCESS)
1956 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
1957 return TRUE;
1959 SetLastError( RtlNtStatusToDosError(status) );
1960 return FALSE;
1964 /***********************************************************************
1965 * SetErrorMode (KERNEL32.@)
1967 UINT WINAPI SetErrorMode( UINT mode )
1969 UINT old = process_error_mode;
1970 process_error_mode = mode;
1971 return old;
1975 /**********************************************************************
1976 * TlsAlloc [KERNEL32.@]
1978 * Allocates a thread local storage index.
1980 * RETURNS
1981 * Success: TLS index.
1982 * Failure: 0xFFFFFFFF
1984 DWORD WINAPI TlsAlloc( void )
1986 DWORD index;
1987 PEB * const peb = NtCurrentTeb()->Peb;
1989 RtlAcquirePebLock();
1990 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
1991 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
1992 else
1994 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
1995 if (index != ~0U)
1997 if (!NtCurrentTeb()->TlsExpansionSlots &&
1998 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
1999 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2001 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2002 index = ~0U;
2003 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2005 else
2007 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2008 index += TLS_MINIMUM_AVAILABLE;
2011 else SetLastError( ERROR_NO_MORE_ITEMS );
2013 RtlReleasePebLock();
2014 return index;
2018 /**********************************************************************
2019 * TlsFree [KERNEL32.@]
2021 * Releases a thread local storage index, making it available for reuse.
2023 * PARAMS
2024 * index [in] TLS index to free.
2026 * RETURNS
2027 * Success: TRUE
2028 * Failure: FALSE
2030 BOOL WINAPI TlsFree( DWORD index )
2032 BOOL ret;
2034 RtlAcquirePebLock();
2035 if (index >= TLS_MINIMUM_AVAILABLE)
2037 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2038 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2040 else
2042 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2043 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2045 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2046 else SetLastError( ERROR_INVALID_PARAMETER );
2047 RtlReleasePebLock();
2048 return TRUE;
2052 /**********************************************************************
2053 * TlsGetValue [KERNEL32.@]
2055 * Gets value in a thread's TLS slot.
2057 * PARAMS
2058 * index [in] TLS index to retrieve value for.
2060 * RETURNS
2061 * Success: Value stored in calling thread's TLS slot for index.
2062 * Failure: 0 and GetLastError() returns NO_ERROR.
2064 LPVOID WINAPI TlsGetValue( DWORD index )
2066 LPVOID ret;
2068 if (index < TLS_MINIMUM_AVAILABLE)
2070 ret = NtCurrentTeb()->TlsSlots[index];
2072 else
2074 index -= TLS_MINIMUM_AVAILABLE;
2075 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2077 SetLastError( ERROR_INVALID_PARAMETER );
2078 return NULL;
2080 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2081 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2083 SetLastError( ERROR_SUCCESS );
2084 return ret;
2088 /**********************************************************************
2089 * TlsSetValue [KERNEL32.@]
2091 * Stores a value in the thread's TLS slot.
2093 * PARAMS
2094 * index [in] TLS index to set value for.
2095 * value [in] Value to be stored.
2097 * RETURNS
2098 * Success: TRUE
2099 * Failure: FALSE
2101 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2103 if (index < TLS_MINIMUM_AVAILABLE)
2105 NtCurrentTeb()->TlsSlots[index] = value;
2107 else
2109 index -= TLS_MINIMUM_AVAILABLE;
2110 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2112 SetLastError( ERROR_INVALID_PARAMETER );
2113 return FALSE;
2115 if (!NtCurrentTeb()->TlsExpansionSlots &&
2116 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2117 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2119 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2120 return FALSE;
2122 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2124 return TRUE;
2128 /***********************************************************************
2129 * GetProcessFlags (KERNEL32.@)
2131 DWORD WINAPI GetProcessFlags( DWORD processid )
2133 IMAGE_NT_HEADERS *nt;
2134 DWORD flags = 0;
2136 if (processid && processid != GetCurrentProcessId()) return 0;
2138 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2140 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2141 flags |= PDB32_CONSOLE_PROC;
2143 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2144 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2145 return flags;
2149 /***********************************************************************
2150 * GetProcessDword (KERNEL.485)
2151 * GetProcessDword (KERNEL32.18)
2152 * 'Of course you cannot directly access Windows internal structures'
2154 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2156 DWORD x, y;
2157 STARTUPINFOW siw;
2159 TRACE("(%d, %d)\n", dwProcessID, offset );
2161 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2163 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2164 return 0;
2167 switch ( offset )
2169 case GPD_APP_COMPAT_FLAGS:
2170 return GetAppCompatFlags16(0);
2171 case GPD_LOAD_DONE_EVENT:
2172 return 0;
2173 case GPD_HINSTANCE16:
2174 return GetTaskDS16();
2175 case GPD_WINDOWS_VERSION:
2176 return GetExeVersion16();
2177 case GPD_THDB:
2178 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2179 case GPD_PDB:
2180 return (DWORD)NtCurrentTeb()->Peb;
2181 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2182 GetStartupInfoW(&siw);
2183 return (DWORD)siw.hStdOutput;
2184 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2185 GetStartupInfoW(&siw);
2186 return (DWORD)siw.hStdInput;
2187 case GPD_STARTF_SHOWWINDOW:
2188 GetStartupInfoW(&siw);
2189 return siw.wShowWindow;
2190 case GPD_STARTF_SIZE:
2191 GetStartupInfoW(&siw);
2192 x = siw.dwXSize;
2193 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2194 y = siw.dwYSize;
2195 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2196 return MAKELONG( x, y );
2197 case GPD_STARTF_POSITION:
2198 GetStartupInfoW(&siw);
2199 x = siw.dwX;
2200 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2201 y = siw.dwY;
2202 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2203 return MAKELONG( x, y );
2204 case GPD_STARTF_FLAGS:
2205 GetStartupInfoW(&siw);
2206 return siw.dwFlags;
2207 case GPD_PARENT:
2208 return 0;
2209 case GPD_FLAGS:
2210 return GetProcessFlags(0);
2211 case GPD_USERDATA:
2212 return process_dword;
2213 default:
2214 ERR("Unknown offset %d\n", offset );
2215 return 0;
2219 /***********************************************************************
2220 * SetProcessDword (KERNEL.484)
2221 * 'Of course you cannot directly access Windows internal structures'
2223 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2225 TRACE("(%d, %d)\n", dwProcessID, offset );
2227 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2229 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2230 return;
2233 switch ( offset )
2235 case GPD_APP_COMPAT_FLAGS:
2236 case GPD_LOAD_DONE_EVENT:
2237 case GPD_HINSTANCE16:
2238 case GPD_WINDOWS_VERSION:
2239 case GPD_THDB:
2240 case GPD_PDB:
2241 case GPD_STARTF_SHELLDATA:
2242 case GPD_STARTF_HOTKEY:
2243 case GPD_STARTF_SHOWWINDOW:
2244 case GPD_STARTF_SIZE:
2245 case GPD_STARTF_POSITION:
2246 case GPD_STARTF_FLAGS:
2247 case GPD_PARENT:
2248 case GPD_FLAGS:
2249 ERR("Not allowed to modify offset %d\n", offset );
2250 break;
2251 case GPD_USERDATA:
2252 process_dword = value;
2253 break;
2254 default:
2255 ERR("Unknown offset %d\n", offset );
2256 break;
2261 /***********************************************************************
2262 * ExitProcess (KERNEL.466)
2264 void WINAPI ExitProcess16( WORD status )
2266 DWORD count;
2267 ReleaseThunkLock( &count );
2268 ExitProcess( status );
2272 /*********************************************************************
2273 * OpenProcess (KERNEL32.@)
2275 * Opens a handle to a process.
2277 * PARAMS
2278 * access [I] Desired access rights assigned to the returned handle.
2279 * inherit [I] Determines whether or not child processes will inherit the handle.
2280 * id [I] Process identifier of the process to get a handle to.
2282 * RETURNS
2283 * Success: Valid handle to the specified process.
2284 * Failure: NULL, check GetLastError().
2286 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2288 NTSTATUS status;
2289 HANDLE handle;
2290 OBJECT_ATTRIBUTES attr;
2291 CLIENT_ID cid;
2293 cid.UniqueProcess = (HANDLE)id;
2294 cid.UniqueThread = 0; /* FIXME ? */
2296 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2297 attr.RootDirectory = NULL;
2298 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2299 attr.SecurityDescriptor = NULL;
2300 attr.SecurityQualityOfService = NULL;
2301 attr.ObjectName = NULL;
2303 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2305 status = NtOpenProcess(&handle, access, &attr, &cid);
2306 if (status != STATUS_SUCCESS)
2308 SetLastError( RtlNtStatusToDosError(status) );
2309 return NULL;
2311 return handle;
2315 /*********************************************************************
2316 * MapProcessHandle (KERNEL.483)
2317 * GetProcessId (KERNEL32.@)
2319 * Gets the a unique identifier of a process.
2321 * PARAMS
2322 * hProcess [I] Handle to the process.
2324 * RETURNS
2325 * Success: TRUE.
2326 * Failure: FALSE, check GetLastError().
2328 * NOTES
2330 * The identifier is unique only on the machine and only until the process
2331 * exits (including system shutdown).
2333 DWORD WINAPI GetProcessId( HANDLE hProcess )
2335 NTSTATUS status;
2336 PROCESS_BASIC_INFORMATION pbi;
2338 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2339 sizeof(pbi), NULL);
2340 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2341 SetLastError( RtlNtStatusToDosError(status) );
2342 return 0;
2346 /*********************************************************************
2347 * CloseW32Handle (KERNEL.474)
2348 * CloseHandle (KERNEL32.@)
2350 * Closes a handle.
2352 * PARAMS
2353 * handle [I] Handle to close.
2355 * RETURNS
2356 * Success: TRUE.
2357 * Failure: FALSE, check GetLastError().
2359 BOOL WINAPI CloseHandle( HANDLE handle )
2361 NTSTATUS status;
2363 /* stdio handles need special treatment */
2364 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2365 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2366 (handle == (HANDLE)STD_ERROR_HANDLE))
2367 handle = GetStdHandle( (DWORD)handle );
2369 if (is_console_handle(handle))
2370 return CloseConsoleHandle(handle);
2372 status = NtClose( handle );
2373 if (status) SetLastError( RtlNtStatusToDosError(status) );
2374 return !status;
2378 /*********************************************************************
2379 * GetHandleInformation (KERNEL32.@)
2381 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2383 OBJECT_DATA_INFORMATION info;
2384 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2386 if (status) SetLastError( RtlNtStatusToDosError(status) );
2387 else if (flags)
2389 *flags = 0;
2390 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2391 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2393 return !status;
2397 /*********************************************************************
2398 * SetHandleInformation (KERNEL32.@)
2400 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2402 OBJECT_DATA_INFORMATION info;
2403 NTSTATUS status;
2405 /* if not setting both fields, retrieve current value first */
2406 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2407 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2409 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2411 SetLastError( RtlNtStatusToDosError(status) );
2412 return FALSE;
2415 if (mask & HANDLE_FLAG_INHERIT)
2416 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2417 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2418 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2420 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2421 if (status) SetLastError( RtlNtStatusToDosError(status) );
2422 return !status;
2426 /*********************************************************************
2427 * DuplicateHandle (KERNEL32.@)
2429 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2430 HANDLE dest_process, HANDLE *dest,
2431 DWORD access, BOOL inherit, DWORD options )
2433 NTSTATUS status;
2435 if (is_console_handle(source))
2437 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2438 if (source_process != dest_process ||
2439 source_process != GetCurrentProcess())
2441 SetLastError(ERROR_INVALID_PARAMETER);
2442 return FALSE;
2444 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2445 return (*dest != INVALID_HANDLE_VALUE);
2447 status = NtDuplicateObject( source_process, source, dest_process, dest,
2448 access, inherit ? OBJ_INHERIT : 0, options );
2449 if (status) SetLastError( RtlNtStatusToDosError(status) );
2450 return !status;
2454 /***********************************************************************
2455 * ConvertToGlobalHandle (KERNEL.476)
2456 * ConvertToGlobalHandle (KERNEL32.@)
2458 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2460 HANDLE ret = INVALID_HANDLE_VALUE;
2461 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2462 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2463 return ret;
2467 /***********************************************************************
2468 * SetHandleContext (KERNEL32.@)
2470 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2472 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2473 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2474 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2475 return FALSE;
2479 /***********************************************************************
2480 * GetHandleContext (KERNEL32.@)
2482 DWORD WINAPI GetHandleContext(HANDLE hnd)
2484 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2485 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2486 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2487 return 0;
2491 /***********************************************************************
2492 * CreateSocketHandle (KERNEL32.@)
2494 HANDLE WINAPI CreateSocketHandle(void)
2496 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2497 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2498 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2499 return INVALID_HANDLE_VALUE;
2503 /***********************************************************************
2504 * SetPriorityClass (KERNEL32.@)
2506 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2508 NTSTATUS status;
2509 PROCESS_PRIORITY_CLASS ppc;
2511 ppc.Foreground = FALSE;
2512 switch (priorityclass)
2514 case IDLE_PRIORITY_CLASS:
2515 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2516 case BELOW_NORMAL_PRIORITY_CLASS:
2517 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2518 case NORMAL_PRIORITY_CLASS:
2519 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2520 case ABOVE_NORMAL_PRIORITY_CLASS:
2521 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2522 case HIGH_PRIORITY_CLASS:
2523 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2524 case REALTIME_PRIORITY_CLASS:
2525 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2526 default:
2527 SetLastError(ERROR_INVALID_PARAMETER);
2528 return FALSE;
2531 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2532 &ppc, sizeof(ppc));
2534 if (status != STATUS_SUCCESS)
2536 SetLastError( RtlNtStatusToDosError(status) );
2537 return FALSE;
2539 return TRUE;
2543 /***********************************************************************
2544 * GetPriorityClass (KERNEL32.@)
2546 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2548 NTSTATUS status;
2549 PROCESS_BASIC_INFORMATION pbi;
2551 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2552 sizeof(pbi), NULL);
2553 if (status != STATUS_SUCCESS)
2555 SetLastError( RtlNtStatusToDosError(status) );
2556 return 0;
2558 switch (pbi.BasePriority)
2560 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2561 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2562 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2563 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2564 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2565 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2567 SetLastError( ERROR_INVALID_PARAMETER );
2568 return 0;
2572 /***********************************************************************
2573 * SetProcessAffinityMask (KERNEL32.@)
2575 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2577 NTSTATUS status;
2579 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2580 &affmask, sizeof(DWORD_PTR));
2581 if (!status)
2583 SetLastError( RtlNtStatusToDosError(status) );
2584 return FALSE;
2586 return TRUE;
2590 /**********************************************************************
2591 * GetProcessAffinityMask (KERNEL32.@)
2593 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2594 PDWORD_PTR lpProcessAffinityMask,
2595 PDWORD_PTR lpSystemAffinityMask )
2597 PROCESS_BASIC_INFORMATION pbi;
2598 NTSTATUS status;
2600 status = NtQueryInformationProcess(hProcess,
2601 ProcessBasicInformation,
2602 &pbi, sizeof(pbi), NULL);
2603 if (status)
2605 SetLastError( RtlNtStatusToDosError(status) );
2606 return FALSE;
2608 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2609 /* FIXME */
2610 if (lpSystemAffinityMask) *lpSystemAffinityMask = 1;
2611 return TRUE;
2615 /***********************************************************************
2616 * GetProcessVersion (KERNEL32.@)
2618 DWORD WINAPI GetProcessVersion( DWORD processid )
2620 IMAGE_NT_HEADERS *nt;
2622 if (processid && processid != GetCurrentProcessId())
2624 FIXME("should use ReadProcessMemory\n");
2625 return 0;
2627 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2628 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2629 nt->OptionalHeader.MinorSubsystemVersion);
2630 return 0;
2634 /***********************************************************************
2635 * SetProcessWorkingSetSize [KERNEL32.@]
2636 * Sets the min/max working set sizes for a specified process.
2638 * PARAMS
2639 * hProcess [I] Handle to the process of interest
2640 * minset [I] Specifies minimum working set size
2641 * maxset [I] Specifies maximum working set size
2643 * RETURNS
2644 * Success: TRUE
2645 * Failure: FALSE
2647 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2648 SIZE_T maxset)
2650 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2651 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2652 /* Trim the working set to zero */
2653 /* Swap the process out of physical RAM */
2655 return TRUE;
2658 /***********************************************************************
2659 * GetProcessWorkingSetSize (KERNEL32.@)
2661 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2662 PSIZE_T maxset)
2664 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2665 /* 32 MB working set size */
2666 if (minset) *minset = 32*1024*1024;
2667 if (maxset) *maxset = 32*1024*1024;
2668 return TRUE;
2672 /***********************************************************************
2673 * SetProcessShutdownParameters (KERNEL32.@)
2675 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2677 FIXME("(%08x, %08x): partial stub.\n", level, flags);
2678 shutdown_flags = flags;
2679 shutdown_priority = level;
2680 return TRUE;
2684 /***********************************************************************
2685 * GetProcessShutdownParameters (KERNEL32.@)
2688 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2690 *lpdwLevel = shutdown_priority;
2691 *lpdwFlags = shutdown_flags;
2692 return TRUE;
2696 /***********************************************************************
2697 * GetProcessPriorityBoost (KERNEL32.@)
2699 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2701 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2703 /* Report that no boost is present.. */
2704 *pDisablePriorityBoost = FALSE;
2706 return TRUE;
2709 /***********************************************************************
2710 * SetProcessPriorityBoost (KERNEL32.@)
2712 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2714 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2715 /* Say we can do it. I doubt the program will notice that we don't. */
2716 return TRUE;
2720 /***********************************************************************
2721 * ReadProcessMemory (KERNEL32.@)
2723 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2724 SIZE_T *bytes_read )
2726 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2727 if (status) SetLastError( RtlNtStatusToDosError(status) );
2728 return !status;
2732 /***********************************************************************
2733 * WriteProcessMemory (KERNEL32.@)
2735 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2736 SIZE_T *bytes_written )
2738 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2739 if (status) SetLastError( RtlNtStatusToDosError(status) );
2740 return !status;
2744 /****************************************************************************
2745 * FlushInstructionCache (KERNEL32.@)
2747 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2749 NTSTATUS status;
2750 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2751 if (status) SetLastError( RtlNtStatusToDosError(status) );
2752 return !status;
2756 /******************************************************************
2757 * GetProcessIoCounters (KERNEL32.@)
2759 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2761 NTSTATUS status;
2763 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2764 ioc, sizeof(*ioc), NULL);
2765 if (status) SetLastError( RtlNtStatusToDosError(status) );
2766 return !status;
2769 /***********************************************************************
2770 * ProcessIdToSessionId (KERNEL32.@)
2771 * This function is available on Terminal Server 4SP4 and Windows 2000
2773 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2775 /* According to MSDN, if the calling process is not in a terminal
2776 * services environment, then the sessionid returned is zero.
2778 *sessionid_ptr = 0;
2779 return TRUE;
2783 /***********************************************************************
2784 * RegisterServiceProcess (KERNEL.491)
2785 * RegisterServiceProcess (KERNEL32.@)
2787 * A service process calls this function to ensure that it continues to run
2788 * even after a user logged off.
2790 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2792 /* I don't think that Wine needs to do anything in this function */
2793 return 1; /* success */
2797 /**********************************************************************
2798 * IsWow64Process (KERNEL32.@)
2800 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
2802 FIXME("(%p %p) stub!\n", hProcess, Wow64Process);
2803 *Wow64Process = FALSE;
2804 return TRUE;
2808 /***********************************************************************
2809 * GetCurrentProcess (KERNEL32.@)
2811 * Get a handle to the current process.
2813 * PARAMS
2814 * None.
2816 * RETURNS
2817 * A handle representing the current process.
2819 #undef GetCurrentProcess
2820 HANDLE WINAPI GetCurrentProcess(void)
2822 return (HANDLE)0xffffffff;
2825 /***********************************************************************
2826 * CmdBatNotification (KERNEL32.@)
2828 * Notifies the system that a batch file has started or finished.
2830 * PARAMS
2831 * bBatchRunning [I] TRUE if a batch file has started or
2832 * FALSE if a batch file has finished executing.
2834 * RETURNS
2835 * Unknown.
2837 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
2839 FIXME("%d\n", bBatchRunning);
2840 return FALSE;