kernel32: Better workaround for the lack of locale environment variables on MacOS.
[wine/hacks.git] / dlls / kernel32 / process.c
blob48c678710570ed8354ea24547529eb9c19d7a81a
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 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 inline static 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 inline static 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--; /* 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 );
422 /***********************************************************************
423 * set_library_wargv
425 * Set the Wine library Unicode argv global variables.
427 static void set_library_wargv( char **argv )
429 int argc;
430 char *q;
431 WCHAR *p;
432 WCHAR **wargv;
433 DWORD total = 0;
435 for (argc = 0; argv[argc]; argc++)
436 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
438 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
439 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
440 p = (WCHAR *)(wargv + argc + 1);
441 for (argc = 0; argv[argc]; argc++)
443 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
444 wargv[argc] = p;
445 p += reslen;
446 total -= reslen;
448 wargv[argc] = NULL;
450 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
452 for (argc = 0; wargv[argc]; argc++)
453 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
455 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
456 q = (char *)(argv + argc + 1);
457 for (argc = 0; wargv[argc]; argc++)
459 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
460 argv[argc] = q;
461 q += reslen;
462 total -= reslen;
464 argv[argc] = NULL;
466 __wine_main_argc = argc;
467 __wine_main_argv = argv;
468 __wine_main_wargv = wargv;
472 /***********************************************************************
473 * build_command_line
475 * Build the command line of a process from the argv array.
477 * Note that it does NOT necessarily include the file name.
478 * Sometimes we don't even have any command line options at all.
480 * We must quote and escape characters so that the argv array can be rebuilt
481 * from the command line:
482 * - spaces and tabs must be quoted
483 * 'a b' -> '"a b"'
484 * - quotes must be escaped
485 * '"' -> '\"'
486 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
487 * resulting in an odd number of '\' followed by a '"'
488 * '\"' -> '\\\"'
489 * '\\"' -> '\\\\\"'
490 * - '\'s that are not followed by a '"' can be left as is
491 * 'a\b' == 'a\b'
492 * 'a\\b' == 'a\\b'
494 static BOOL build_command_line( WCHAR **argv )
496 int len;
497 WCHAR **arg;
498 LPWSTR p;
499 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
501 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
503 len = 0;
504 for (arg = argv; *arg; arg++)
506 int has_space,bcount;
507 WCHAR* a;
509 has_space=0;
510 bcount=0;
511 a=*arg;
512 if( !*a ) has_space=1;
513 while (*a!='\0') {
514 if (*a=='\\') {
515 bcount++;
516 } else {
517 if (*a==' ' || *a=='\t') {
518 has_space=1;
519 } else if (*a=='"') {
520 /* doubling of '\' preceding a '"',
521 * plus escaping of said '"'
523 len+=2*bcount+1;
525 bcount=0;
527 a++;
529 len+=(a-*arg)+1 /* for the separating space */;
530 if (has_space)
531 len+=2; /* for the quotes */
534 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
535 return FALSE;
537 p = rupp->CommandLine.Buffer;
538 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
539 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
540 for (arg = argv; *arg; arg++)
542 int has_space,has_quote;
543 WCHAR* a;
545 /* Check for quotes and spaces in this argument */
546 has_space=has_quote=0;
547 a=*arg;
548 if( !*a ) has_space=1;
549 while (*a!='\0') {
550 if (*a==' ' || *a=='\t') {
551 has_space=1;
552 if (has_quote)
553 break;
554 } else if (*a=='"') {
555 has_quote=1;
556 if (has_space)
557 break;
559 a++;
562 /* Now transfer it to the command line */
563 if (has_space)
564 *p++='"';
565 if (has_quote) {
566 int bcount;
567 WCHAR* a;
569 bcount=0;
570 a=*arg;
571 while (*a!='\0') {
572 if (*a=='\\') {
573 *p++=*a;
574 bcount++;
575 } else {
576 if (*a=='"') {
577 int i;
579 /* Double all the '\\' preceding this '"', plus one */
580 for (i=0;i<=bcount;i++)
581 *p++='\\';
582 *p++='"';
583 } else {
584 *p++=*a;
586 bcount=0;
588 a++;
590 } else {
591 WCHAR* x = *arg;
592 while ((*p=*x++)) p++;
594 if (has_space)
595 *p++='"';
596 *p++=' ';
598 if (p > rupp->CommandLine.Buffer)
599 p--; /* remove last space */
600 *p = '\0';
602 return TRUE;
606 /***********************************************************************
607 * init_current_directory
609 * Initialize the current directory from the Unix cwd or the parent info.
611 static void init_current_directory( CURDIR *cur_dir )
613 UNICODE_STRING dir_str;
614 char *cwd;
615 int size;
617 /* if we received a cur dir from the parent, try this first */
619 if (cur_dir->DosPath.Length)
621 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
624 /* now try to get it from the Unix cwd */
626 for (size = 256; ; size *= 2)
628 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
629 if (getcwd( cwd, size )) break;
630 HeapFree( GetProcessHeap(), 0, cwd );
631 if (errno == ERANGE) continue;
632 cwd = NULL;
633 break;
636 if (cwd)
638 WCHAR *dirW;
639 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
640 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
642 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
643 RtlInitUnicodeString( &dir_str, dirW );
644 RtlSetCurrentDirectory_U( &dir_str );
645 RtlFreeUnicodeString( &dir_str );
649 if (!cur_dir->DosPath.Length) /* still not initialized */
651 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
652 "starting in the Windows directory.\n", cwd ? cwd : "" );
653 RtlInitUnicodeString( &dir_str, DIR_Windows );
654 RtlSetCurrentDirectory_U( &dir_str );
656 HeapFree( GetProcessHeap(), 0, cwd );
658 done:
659 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
660 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
664 /***********************************************************************
665 * init_windows_dirs
667 * Initialize the windows and system directories from the environment.
669 static void init_windows_dirs(void)
671 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
673 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
674 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
675 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
676 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
678 DWORD len;
679 WCHAR *buffer;
681 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
683 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
684 GetEnvironmentVariableW( windirW, buffer, len );
685 DIR_Windows = buffer;
687 else DIR_Windows = default_windirW;
689 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
691 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
692 GetEnvironmentVariableW( winsysdirW, buffer, len );
693 DIR_System = buffer;
695 else
697 len = strlenW( DIR_Windows );
698 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
699 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
700 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
701 DIR_System = buffer;
704 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
705 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
706 debugstr_w(DIR_Windows) );
707 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
708 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
709 debugstr_w(DIR_System) );
711 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
712 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
714 /* set the directories in ntdll too */
715 __wine_init_windows_dir( DIR_Windows, DIR_System );
719 /***********************************************************************
720 * process_init
722 * Main process initialisation code
724 static BOOL process_init(void)
726 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
727 PEB *peb = NtCurrentTeb()->Peb;
728 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
730 PTHREAD_Init();
732 setbuf(stdout,NULL);
733 setbuf(stderr,NULL);
735 kernel32_handle = GetModuleHandleW(kernel32W);
737 LOCALE_Init();
739 if (!params->Environment)
741 /* Copy the parent environment */
742 if (!build_initial_environment( __wine_main_environ )) return FALSE;
744 /* convert old configuration to new format */
745 convert_old_config();
747 set_registry_environment();
750 init_windows_dirs();
751 init_current_directory( &params->CurrentDirectory );
753 return TRUE;
757 /***********************************************************************
758 * init_stack
760 * Allocate the stack of new process.
762 static void *init_stack(void)
764 void *base;
765 SIZE_T stack_size, page_size = getpagesize();
766 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
768 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
769 stack_size += page_size; /* for the guard page */
770 stack_size = (stack_size + 0xffff) & ~0xffff; /* round to 64K boundary */
771 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
773 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
775 ERR( "failed to allocate main process stack\n" );
776 ExitProcess( 1 );
779 /* note: limit is lower than base since the stack grows down */
780 NtCurrentTeb()->DeallocationStack = base;
781 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
782 NtCurrentTeb()->Tib.StackLimit = (char *)base + page_size;
784 #ifdef VALGRIND_STACK_REGISTER
785 /* no need to de-register the stack as it's the one of the main thread */
786 VALGRIND_STACK_REGISTER(NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase);
787 #endif
789 /* setup guard page */
790 VirtualProtect( base, page_size, PAGE_NOACCESS, NULL );
791 return NtCurrentTeb()->Tib.StackBase;
795 /***********************************************************************
796 * start_process
798 * Startup routine of a new process. Runs on the new process stack.
800 static void start_process( void *arg )
802 __TRY
804 PEB *peb = NtCurrentTeb()->Peb;
805 IMAGE_NT_HEADERS *nt;
806 LPTHREAD_START_ROUTINE entry;
808 LdrInitializeThunk( 0, 0, 0, 0 );
810 nt = RtlImageNtHeader( peb->ImageBaseAddress );
811 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
812 nt->OptionalHeader.AddressOfEntryPoint);
814 if (TRACE_ON(relay))
815 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
816 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
818 SetLastError( 0 ); /* clear error code */
819 if (peb->BeingDebugged) DbgBreakPoint();
820 ExitThread( entry( peb ) );
822 __EXCEPT(UnhandledExceptionFilter)
824 TerminateThread( GetCurrentThread(), GetExceptionCode() );
826 __ENDTRY
830 /***********************************************************************
831 * set_process_name
833 * Change the process name in the ps output.
835 static void set_process_name( int argc, char *argv[] )
837 #ifdef HAVE_PRCTL
838 int i, offset;
839 char *p, *prctl_name = argv[1];
840 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
842 #ifndef PR_SET_NAME
843 # define PR_SET_NAME 15
844 #endif
846 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
847 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
849 if (prctl( PR_SET_NAME, prctl_name ) != -1)
851 offset = argv[1] - argv[0];
852 memmove( argv[1] - offset, argv[1], end - argv[1] );
853 memset( end - offset, 0, offset );
854 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
855 argv[i-1] = NULL;
857 else
858 #endif /* HAVE_PRCTL */
860 /* remove argv[0] */
861 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
866 /***********************************************************************
867 * __wine_kernel_init
869 * Wine initialisation: load and start the main exe file.
871 void __wine_kernel_init(void)
873 static const WCHAR dotW[] = {'.',0};
874 static const WCHAR exeW[] = {'.','e','x','e',0};
876 WCHAR *p, main_exe_name[MAX_PATH+1];
877 PEB *peb = NtCurrentTeb()->Peb;
879 /* Initialize everything */
880 if (!process_init()) exit(1);
881 set_process_name( __wine_main_argc, __wine_main_argv );
882 set_library_wargv( __wine_main_argv );
884 if (peb->ProcessParameters->ImagePathName.Buffer)
886 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
888 else
890 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
891 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
893 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
894 ExitProcess( GetLastError() );
896 if (!build_command_line( __wine_main_wargv )) goto error;
899 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
900 p = strrchrW( main_exe_name, '.' );
901 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
903 TRACE( "starting process name=%s argv[0]=%s\n",
904 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
906 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
907 MODULE_get_dll_load_path(main_exe_name) );
909 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
911 char msg[1024];
912 DWORD error = GetLastError();
914 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
915 if (error == ERROR_BAD_EXE_FORMAT ||
916 error == ERROR_INVALID_ADDRESS ||
917 error == ERROR_NOT_ENOUGH_MEMORY)
919 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
920 /* if we get back here, it failed */
923 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
924 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
925 ExitProcess( error );
928 /* switch to the new stack */
929 wine_switch_to_stack( start_process, NULL, init_stack() );
931 error:
932 ExitProcess( GetLastError() );
936 /***********************************************************************
937 * build_argv
939 * Build an argv array from a command-line.
940 * 'reserved' is the number of args to reserve before the first one.
942 static char **build_argv( const WCHAR *cmdlineW, int reserved )
944 int argc;
945 char** argv;
946 char *arg,*s,*d,*cmdline;
947 int in_quotes,bcount,len;
949 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
950 if (!(cmdline = malloc(len))) return NULL;
951 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
953 argc=reserved+1;
954 bcount=0;
955 in_quotes=0;
956 s=cmdline;
957 while (1) {
958 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
959 /* space */
960 argc++;
961 /* skip the remaining spaces */
962 while (*s==' ' || *s=='\t') {
963 s++;
965 if (*s=='\0')
966 break;
967 bcount=0;
968 continue;
969 } else if (*s=='\\') {
970 /* '\', count them */
971 bcount++;
972 } else if ((*s=='"') && ((bcount & 1)==0)) {
973 /* unescaped '"' */
974 in_quotes=!in_quotes;
975 bcount=0;
976 } else {
977 /* a regular character */
978 bcount=0;
980 s++;
982 argv=malloc(argc*sizeof(*argv));
983 if (!argv)
984 return NULL;
986 arg=d=s=cmdline;
987 bcount=0;
988 in_quotes=0;
989 argc=reserved;
990 while (*s) {
991 if ((*s==' ' || *s=='\t') && !in_quotes) {
992 /* Close the argument and copy it */
993 *d=0;
994 argv[argc++]=arg;
996 /* skip the remaining spaces */
997 do {
998 s++;
999 } while (*s==' ' || *s=='\t');
1001 /* Start with a new argument */
1002 arg=d=s;
1003 bcount=0;
1004 } else if (*s=='\\') {
1005 /* '\\' */
1006 *d++=*s++;
1007 bcount++;
1008 } else if (*s=='"') {
1009 /* '"' */
1010 if ((bcount & 1)==0) {
1011 /* Preceded by an even number of '\', this is half that
1012 * number of '\', plus a '"' which we discard.
1014 d-=bcount/2;
1015 s++;
1016 in_quotes=!in_quotes;
1017 } else {
1018 /* Preceded by an odd number of '\', this is half that
1019 * number of '\' followed by a '"'
1021 d=d-bcount/2-1;
1022 *d++='"';
1023 s++;
1025 bcount=0;
1026 } else {
1027 /* a regular character */
1028 *d++=*s++;
1029 bcount=0;
1032 if (*arg) {
1033 *d='\0';
1034 argv[argc++]=arg;
1036 argv[argc]=NULL;
1038 return argv;
1042 /***********************************************************************
1043 * alloc_env_string
1045 * Allocate an environment string; helper for build_envp
1047 static char *alloc_env_string( const char *name, const char *value )
1049 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1050 strcpy( ret, name );
1051 strcat( ret, value );
1052 return ret;
1055 /***********************************************************************
1056 * build_envp
1058 * Build the environment of a new child process.
1060 static char **build_envp( const WCHAR *envW )
1062 const WCHAR *end;
1063 char **envp;
1064 char *env, *p;
1065 int count = 0, length;
1067 for (end = envW; *end; count++) end += strlenW(end) + 1;
1068 end++;
1069 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1070 if (!(env = malloc( length ))) return NULL;
1071 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1073 count += 4;
1075 if ((envp = malloc( count * sizeof(*envp) )))
1077 char **envptr = envp;
1079 /* some variables must not be modified, so we get them directly from the unix env */
1080 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1081 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1082 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1083 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1084 /* now put the Windows environment strings */
1085 for (p = env; *p; p += strlen(p) + 1)
1087 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1088 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1089 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1090 if (is_special_env_var( p )) /* prefix it with "WINE" */
1091 *envptr++ = alloc_env_string( "WINE", p );
1092 else
1093 *envptr++ = p;
1095 *envptr = 0;
1097 return envp;
1101 /***********************************************************************
1102 * fork_and_exec
1104 * Fork and exec a new Unix binary, checking for errors.
1106 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1107 const WCHAR *env, const char *newdir, DWORD flags )
1109 int fd[2];
1110 int pid, err;
1112 if (!env) env = GetEnvironmentStringsW();
1114 if (pipe(fd) == -1)
1116 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1117 return -1;
1119 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1120 if (!(pid = fork())) /* child */
1122 char **argv = build_argv( cmdline, 0 );
1123 char **envp = build_envp( env );
1124 close( fd[0] );
1126 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)) setsid();
1128 /* Reset signals that we previously set to SIG_IGN */
1129 signal( SIGPIPE, SIG_DFL );
1130 signal( SIGCHLD, SIG_DFL );
1132 if (newdir) chdir(newdir);
1134 if (argv && envp) execve( filename, argv, envp );
1135 err = errno;
1136 write( fd[1], &err, sizeof(err) );
1137 _exit(1);
1139 close( fd[1] );
1140 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1142 errno = err;
1143 pid = -1;
1145 if (pid == -1) FILE_SetDosError();
1146 close( fd[0] );
1147 return pid;
1151 /***********************************************************************
1152 * create_user_params
1154 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1155 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1156 const STARTUPINFOW *startup )
1158 RTL_USER_PROCESS_PARAMETERS *params;
1159 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1160 NTSTATUS status;
1161 WCHAR buffer[MAX_PATH];
1163 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1164 lstrcpynW( buffer, filename, MAX_PATH );
1165 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1166 lstrcpynW( buffer, filename, MAX_PATH );
1167 RtlInitUnicodeString( &image_str, buffer );
1169 RtlInitUnicodeString( &cmdline_str, cmdline );
1170 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1171 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1172 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1173 if (startup->lpReserved2 && startup->cbReserved2)
1175 runtime.Length = 0;
1176 runtime.MaximumLength = startup->cbReserved2;
1177 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1180 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1181 cur_dir ? &curdir_str : NULL,
1182 &cmdline_str, env,
1183 startup->lpTitle ? &title : NULL,
1184 startup->lpDesktop ? &desktop : NULL,
1185 NULL,
1186 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1187 if (status != STATUS_SUCCESS)
1189 SetLastError( RtlNtStatusToDosError(status) );
1190 return NULL;
1193 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1194 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1196 if (startup->dwFlags & STARTF_USESTDHANDLES)
1198 params->hStdInput = startup->hStdInput;
1199 params->hStdOutput = startup->hStdOutput;
1200 params->hStdError = startup->hStdError;
1202 else
1204 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1205 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1206 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1208 params->dwX = startup->dwX;
1209 params->dwY = startup->dwY;
1210 params->dwXSize = startup->dwXSize;
1211 params->dwYSize = startup->dwYSize;
1212 params->dwXCountChars = startup->dwXCountChars;
1213 params->dwYCountChars = startup->dwYCountChars;
1214 params->dwFillAttribute = startup->dwFillAttribute;
1215 params->dwFlags = startup->dwFlags;
1216 params->wShowWindow = startup->wShowWindow;
1217 return params;
1221 /***********************************************************************
1222 * create_process
1224 * Create a new process. If hFile is a valid handle we have an exe
1225 * file, otherwise it is a Winelib app.
1227 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1228 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1229 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1230 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1231 void *res_start, void *res_end, int exec_only )
1233 BOOL ret, success = FALSE;
1234 HANDLE process_info;
1235 WCHAR *env_end;
1236 char *winedebug = NULL;
1237 RTL_USER_PROCESS_PARAMETERS *params;
1238 int socketfd[2];
1239 pid_t pid;
1240 int err;
1242 if (!env) RtlAcquirePebLock();
1244 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1246 if (!env) RtlReleasePebLock();
1247 return FALSE;
1249 env_end = params->Environment;
1250 while (*env_end)
1252 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1253 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1255 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1256 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1257 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1259 env_end += strlenW(env_end) + 1;
1261 env_end++;
1263 /* create the socket for the new process */
1265 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1267 if (!env) RtlReleasePebLock();
1268 HeapFree( GetProcessHeap(), 0, winedebug );
1269 RtlDestroyProcessParameters( params );
1270 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1271 return FALSE;
1273 wine_server_send_fd( socketfd[1] );
1274 close( socketfd[1] );
1276 /* create the process on the server side */
1278 SERVER_START_REQ( new_process )
1280 req->inherit_all = inherit;
1281 req->create_flags = flags;
1282 req->socket_fd = socketfd[1];
1283 req->exe_file = hFile;
1284 req->process_access = PROCESS_ALL_ACCESS;
1285 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1286 req->thread_access = THREAD_ALL_ACCESS;
1287 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1288 req->hstdin = params->hStdInput;
1289 req->hstdout = params->hStdOutput;
1290 req->hstderr = params->hStdError;
1292 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1294 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1295 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1296 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1297 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1299 else
1301 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1302 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1303 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1306 wine_server_add_data( req, params, params->Size );
1307 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1308 if ((ret = !wine_server_call_err( req )))
1310 info->dwProcessId = (DWORD)reply->pid;
1311 info->dwThreadId = (DWORD)reply->tid;
1312 info->hProcess = reply->phandle;
1313 info->hThread = reply->thandle;
1315 process_info = reply->info;
1317 SERVER_END_REQ;
1319 if (!env) RtlReleasePebLock();
1320 RtlDestroyProcessParameters( params );
1321 if (!ret)
1323 close( socketfd[0] );
1324 HeapFree( GetProcessHeap(), 0, winedebug );
1325 return FALSE;
1328 /* create the child process */
1330 if (exec_only || !(pid = fork())) /* child */
1332 char preloader_reserve[64], socket_env[64];
1333 char **argv = build_argv( cmd_line, 1 );
1335 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)) setsid();
1337 /* Reset signals that we previously set to SIG_IGN */
1338 signal( SIGPIPE, SIG_DFL );
1339 signal( SIGCHLD, SIG_DFL );
1341 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1342 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1343 (unsigned long)res_start, (unsigned long)res_end );
1345 putenv( preloader_reserve );
1346 putenv( socket_env );
1347 if (winedebug) putenv( winedebug );
1348 if (unixdir) chdir(unixdir);
1350 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1351 _exit(1);
1354 /* this is the parent */
1356 close( socketfd[0] );
1357 HeapFree( GetProcessHeap(), 0, winedebug );
1358 if (pid == -1)
1360 FILE_SetDosError();
1361 goto error;
1364 /* wait for the new process info to be ready */
1366 WaitForSingleObject( process_info, INFINITE );
1367 SERVER_START_REQ( get_new_process_info )
1369 req->info = process_info;
1370 wine_server_call( req );
1371 success = reply->success;
1372 err = reply->exit_code;
1374 SERVER_END_REQ;
1376 if (!success)
1378 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1379 goto error;
1381 CloseHandle( process_info );
1382 return success;
1384 error:
1385 CloseHandle( process_info );
1386 CloseHandle( info->hProcess );
1387 CloseHandle( info->hThread );
1388 info->hProcess = info->hThread = 0;
1389 info->dwProcessId = info->dwThreadId = 0;
1390 return FALSE;
1394 /***********************************************************************
1395 * create_vdm_process
1397 * Create a new VDM process for a 16-bit or DOS application.
1399 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1400 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1401 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1402 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1404 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1406 BOOL ret;
1407 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1408 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1410 if (!new_cmd_line)
1412 SetLastError( ERROR_OUTOFMEMORY );
1413 return FALSE;
1415 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1416 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1417 flags, startup, info, unixdir, NULL, NULL, exec_only );
1418 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1419 return ret;
1423 /***********************************************************************
1424 * create_cmd_process
1426 * Create a new cmd shell process for a .BAT file.
1428 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1429 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1430 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1431 LPPROCESS_INFORMATION info )
1434 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1435 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1436 WCHAR comspec[MAX_PATH];
1437 WCHAR *newcmdline;
1438 BOOL ret;
1440 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1441 return FALSE;
1442 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1443 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1444 return FALSE;
1446 strcpyW( newcmdline, comspec );
1447 strcatW( newcmdline, slashcW );
1448 strcatW( newcmdline, cmd_line );
1449 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1450 flags, env, cur_dir, startup, info );
1451 HeapFree( GetProcessHeap(), 0, newcmdline );
1452 return ret;
1456 /*************************************************************************
1457 * get_file_name
1459 * Helper for CreateProcess: retrieve the file name to load from the
1460 * app name and command line. Store the file name in buffer, and
1461 * return a possibly modified command line.
1462 * Also returns a handle to the opened file if it's a Windows binary.
1464 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1465 int buflen, HANDLE *handle )
1467 static const WCHAR quotesW[] = {'"','%','s','"',0};
1469 WCHAR *name, *pos, *ret = NULL;
1470 const WCHAR *p;
1471 BOOL got_space;
1473 /* if we have an app name, everything is easy */
1475 if (appname)
1477 /* use the unmodified app name as file name */
1478 lstrcpynW( buffer, appname, buflen );
1479 *handle = open_exe_file( buffer );
1480 if (!(ret = cmdline) || !cmdline[0])
1482 /* no command-line, create one */
1483 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1484 sprintfW( ret, quotesW, appname );
1486 return ret;
1489 if (!cmdline)
1491 SetLastError( ERROR_INVALID_PARAMETER );
1492 return NULL;
1495 /* first check for a quoted file name */
1497 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1499 int len = p - cmdline - 1;
1500 /* extract the quoted portion as file name */
1501 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1502 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1503 name[len] = 0;
1505 if (find_exe_file( name, buffer, buflen, handle ))
1506 ret = cmdline; /* no change necessary */
1507 goto done;
1510 /* now try the command-line word by word */
1512 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1513 return NULL;
1514 pos = name;
1515 p = cmdline;
1516 got_space = FALSE;
1518 while (*p)
1520 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1521 *pos = 0;
1522 if (find_exe_file( name, buffer, buflen, handle ))
1524 ret = cmdline;
1525 break;
1527 if (*p) got_space = TRUE;
1530 if (ret && got_space) /* now build a new command-line with quotes */
1532 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1533 goto done;
1534 sprintfW( ret, quotesW, name );
1535 strcatW( ret, p );
1538 done:
1539 HeapFree( GetProcessHeap(), 0, name );
1540 return ret;
1544 /**********************************************************************
1545 * CreateProcessA (KERNEL32.@)
1547 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1548 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1549 DWORD flags, LPVOID env, LPCSTR cur_dir,
1550 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1552 BOOL ret = FALSE;
1553 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1554 UNICODE_STRING desktopW, titleW;
1555 STARTUPINFOW infoW;
1557 desktopW.Buffer = NULL;
1558 titleW.Buffer = NULL;
1559 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1560 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1561 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1563 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1564 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1566 memcpy( &infoW, startup_info, sizeof(infoW) );
1567 infoW.lpDesktop = desktopW.Buffer;
1568 infoW.lpTitle = titleW.Buffer;
1570 if (startup_info->lpReserved)
1571 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1572 debugstr_a(startup_info->lpReserved));
1574 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1575 inherit, flags, env, cur_dirW, &infoW, info );
1576 done:
1577 HeapFree( GetProcessHeap(), 0, app_nameW );
1578 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1579 HeapFree( GetProcessHeap(), 0, cur_dirW );
1580 RtlFreeUnicodeString( &desktopW );
1581 RtlFreeUnicodeString( &titleW );
1582 return ret;
1586 /**********************************************************************
1587 * CreateProcessW (KERNEL32.@)
1589 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1590 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1591 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1592 LPPROCESS_INFORMATION info )
1594 BOOL retv = FALSE;
1595 HANDLE hFile = 0;
1596 char *unixdir = NULL;
1597 WCHAR name[MAX_PATH];
1598 WCHAR *tidy_cmdline, *p, *envW = env;
1599 void *res_start, *res_end;
1601 /* Process the AppName and/or CmdLine to get module name and path */
1603 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1605 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1606 return FALSE;
1607 if (hFile == INVALID_HANDLE_VALUE) goto done;
1609 /* Warn if unsupported features are used */
1611 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1612 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1613 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1614 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1615 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1617 if (cur_dir)
1619 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1621 SetLastError(ERROR_DIRECTORY);
1622 goto done;
1625 else
1627 WCHAR buf[MAX_PATH];
1628 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1631 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1633 char *p = env;
1634 DWORD lenW;
1636 while (*p) p += strlen(p) + 1;
1637 p++; /* final null */
1638 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1639 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1640 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1641 flags |= CREATE_UNICODE_ENVIRONMENT;
1644 info->hThread = info->hProcess = 0;
1645 info->dwProcessId = info->dwThreadId = 0;
1647 /* Determine executable type */
1649 if (!hFile) /* builtin exe */
1651 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1652 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1653 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1654 goto done;
1657 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1659 case BINARY_PE_EXE:
1660 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1661 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1662 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1663 break;
1664 case BINARY_OS216:
1665 case BINARY_WIN16:
1666 case BINARY_DOS:
1667 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1668 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1669 inherit, flags, startup_info, info, unixdir, FALSE );
1670 break;
1671 case BINARY_PE_DLL:
1672 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1673 SetLastError( ERROR_BAD_EXE_FORMAT );
1674 break;
1675 case BINARY_UNIX_LIB:
1676 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1677 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1678 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1679 break;
1680 case BINARY_UNKNOWN:
1681 /* check for .com or .bat extension */
1682 if ((p = strrchrW( name, '.' )))
1684 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1686 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1687 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1688 inherit, flags, startup_info, info, unixdir, FALSE );
1689 break;
1691 if (!strcmpiW( p, batW ))
1693 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1694 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1695 inherit, flags, startup_info, info );
1696 break;
1699 /* fall through */
1700 case BINARY_UNIX_EXE:
1702 /* unknown file, try as unix executable */
1703 char *unix_name;
1705 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1707 if ((unix_name = wine_get_unix_file_name( name )))
1709 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags ) != -1);
1710 HeapFree( GetProcessHeap(), 0, unix_name );
1713 break;
1715 CloseHandle( hFile );
1717 done:
1718 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1719 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1720 HeapFree( GetProcessHeap(), 0, unixdir );
1721 return retv;
1725 /**********************************************************************
1726 * exec_process
1728 static void exec_process( LPCWSTR name )
1730 HANDLE hFile;
1731 WCHAR *p;
1732 void *res_start, *res_end;
1733 STARTUPINFOW startup_info;
1734 PROCESS_INFORMATION info;
1736 hFile = open_exe_file( name );
1737 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
1739 memset( &startup_info, 0, sizeof(startup_info) );
1740 startup_info.cb = sizeof(startup_info);
1742 /* Determine executable type */
1744 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1746 case BINARY_PE_EXE:
1747 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1748 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1749 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
1750 break;
1751 case BINARY_UNIX_LIB:
1752 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1753 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1754 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
1755 break;
1756 case BINARY_UNKNOWN:
1757 /* check for .com or .pif extension */
1758 if (!(p = strrchrW( name, '.' ))) break;
1759 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
1760 /* fall through */
1761 case BINARY_OS216:
1762 case BINARY_WIN16:
1763 case BINARY_DOS:
1764 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1765 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1766 FALSE, 0, &startup_info, &info, NULL, TRUE );
1767 break;
1768 default:
1769 break;
1771 CloseHandle( hFile );
1775 /***********************************************************************
1776 * wait_input_idle
1778 * Wrapper to call WaitForInputIdle USER function
1780 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1782 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1784 HMODULE mod = GetModuleHandleA( "user32.dll" );
1785 if (mod)
1787 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1788 if (ptr) return ptr( process, timeout );
1790 return 0;
1794 /***********************************************************************
1795 * WinExec (KERNEL32.@)
1797 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1799 PROCESS_INFORMATION info;
1800 STARTUPINFOA startup;
1801 char *cmdline;
1802 UINT ret;
1804 memset( &startup, 0, sizeof(startup) );
1805 startup.cb = sizeof(startup);
1806 startup.dwFlags = STARTF_USESHOWWINDOW;
1807 startup.wShowWindow = nCmdShow;
1809 /* cmdline needs to be writeable for CreateProcess */
1810 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1811 strcpy( cmdline, lpCmdLine );
1813 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1814 0, NULL, NULL, &startup, &info ))
1816 /* Give 30 seconds to the app to come up */
1817 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1818 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1819 ret = 33;
1820 /* Close off the handles */
1821 CloseHandle( info.hThread );
1822 CloseHandle( info.hProcess );
1824 else if ((ret = GetLastError()) >= 32)
1826 FIXME("Strange error set by CreateProcess: %d\n", ret );
1827 ret = 11;
1829 HeapFree( GetProcessHeap(), 0, cmdline );
1830 return ret;
1834 /**********************************************************************
1835 * LoadModule (KERNEL32.@)
1837 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1839 LOADPARMS32 *params = paramBlock;
1840 PROCESS_INFORMATION info;
1841 STARTUPINFOA startup;
1842 HINSTANCE hInstance;
1843 LPSTR cmdline, p;
1844 char filename[MAX_PATH];
1845 BYTE len;
1847 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1849 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1850 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1851 return (HINSTANCE)GetLastError();
1853 len = (BYTE)params->lpCmdLine[0];
1854 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1855 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1857 strcpy( cmdline, filename );
1858 p = cmdline + strlen(cmdline);
1859 *p++ = ' ';
1860 memcpy( p, params->lpCmdLine + 1, len );
1861 p[len] = 0;
1863 memset( &startup, 0, sizeof(startup) );
1864 startup.cb = sizeof(startup);
1865 if (params->lpCmdShow)
1867 startup.dwFlags = STARTF_USESHOWWINDOW;
1868 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1871 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1872 params->lpEnvAddress, NULL, &startup, &info ))
1874 /* Give 30 seconds to the app to come up */
1875 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1876 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1877 hInstance = (HINSTANCE)33;
1878 /* Close off the handles */
1879 CloseHandle( info.hThread );
1880 CloseHandle( info.hProcess );
1882 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1884 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1885 hInstance = (HINSTANCE)11;
1888 HeapFree( GetProcessHeap(), 0, cmdline );
1889 return hInstance;
1893 /******************************************************************************
1894 * TerminateProcess (KERNEL32.@)
1896 * Terminates a process.
1898 * PARAMS
1899 * handle [I] Process to terminate.
1900 * exit_code [I] Exit code.
1902 * RETURNS
1903 * Success: TRUE.
1904 * Failure: FALSE, check GetLastError().
1906 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1908 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1909 if (status) SetLastError( RtlNtStatusToDosError(status) );
1910 return !status;
1914 /***********************************************************************
1915 * ExitProcess (KERNEL32.@)
1917 * Exits the current process.
1919 * PARAMS
1920 * status [I] Status code to exit with.
1922 * RETURNS
1923 * Nothing.
1925 void WINAPI ExitProcess( DWORD status )
1927 LdrShutdownProcess();
1928 NtTerminateProcess(GetCurrentProcess(), status);
1929 exit(status);
1933 /***********************************************************************
1934 * GetExitCodeProcess [KERNEL32.@]
1936 * Gets termination status of specified process.
1938 * PARAMS
1939 * hProcess [in] Handle to the process.
1940 * lpExitCode [out] Address to receive termination status.
1942 * RETURNS
1943 * Success: TRUE
1944 * Failure: FALSE
1946 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
1948 NTSTATUS status;
1949 PROCESS_BASIC_INFORMATION pbi;
1951 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
1952 sizeof(pbi), NULL);
1953 if (status == STATUS_SUCCESS)
1955 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
1956 return TRUE;
1958 SetLastError( RtlNtStatusToDosError(status) );
1959 return FALSE;
1963 /***********************************************************************
1964 * SetErrorMode (KERNEL32.@)
1966 UINT WINAPI SetErrorMode( UINT mode )
1968 UINT old = process_error_mode;
1969 process_error_mode = mode;
1970 return old;
1974 /**********************************************************************
1975 * TlsAlloc [KERNEL32.@]
1977 * Allocates a thread local storage index.
1979 * RETURNS
1980 * Success: TLS index.
1981 * Failure: 0xFFFFFFFF
1983 DWORD WINAPI TlsAlloc( void )
1985 DWORD index;
1986 PEB * const peb = NtCurrentTeb()->Peb;
1988 RtlAcquirePebLock();
1989 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
1990 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
1991 else
1993 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
1994 if (index != ~0U)
1996 if (!NtCurrentTeb()->TlsExpansionSlots &&
1997 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
1998 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2000 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2001 index = ~0U;
2002 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2004 else
2006 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2007 index += TLS_MINIMUM_AVAILABLE;
2010 else SetLastError( ERROR_NO_MORE_ITEMS );
2012 RtlReleasePebLock();
2013 return index;
2017 /**********************************************************************
2018 * TlsFree [KERNEL32.@]
2020 * Releases a thread local storage index, making it available for reuse.
2022 * PARAMS
2023 * index [in] TLS index to free.
2025 * RETURNS
2026 * Success: TRUE
2027 * Failure: FALSE
2029 BOOL WINAPI TlsFree( DWORD index )
2031 BOOL ret;
2033 RtlAcquirePebLock();
2034 if (index >= TLS_MINIMUM_AVAILABLE)
2036 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2037 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2039 else
2041 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2042 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2044 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2045 else SetLastError( ERROR_INVALID_PARAMETER );
2046 RtlReleasePebLock();
2047 return TRUE;
2051 /**********************************************************************
2052 * TlsGetValue [KERNEL32.@]
2054 * Gets value in a thread's TLS slot.
2056 * PARAMS
2057 * index [in] TLS index to retrieve value for.
2059 * RETURNS
2060 * Success: Value stored in calling thread's TLS slot for index.
2061 * Failure: 0 and GetLastError() returns NO_ERROR.
2063 LPVOID WINAPI TlsGetValue( DWORD index )
2065 LPVOID ret;
2067 if (index < TLS_MINIMUM_AVAILABLE)
2069 ret = NtCurrentTeb()->TlsSlots[index];
2071 else
2073 index -= TLS_MINIMUM_AVAILABLE;
2074 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2076 SetLastError( ERROR_INVALID_PARAMETER );
2077 return NULL;
2079 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2080 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2082 SetLastError( ERROR_SUCCESS );
2083 return ret;
2087 /**********************************************************************
2088 * TlsSetValue [KERNEL32.@]
2090 * Stores a value in the thread's TLS slot.
2092 * PARAMS
2093 * index [in] TLS index to set value for.
2094 * value [in] Value to be stored.
2096 * RETURNS
2097 * Success: TRUE
2098 * Failure: FALSE
2100 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2102 if (index < TLS_MINIMUM_AVAILABLE)
2104 NtCurrentTeb()->TlsSlots[index] = value;
2106 else
2108 index -= TLS_MINIMUM_AVAILABLE;
2109 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2111 SetLastError( ERROR_INVALID_PARAMETER );
2112 return FALSE;
2114 if (!NtCurrentTeb()->TlsExpansionSlots &&
2115 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2116 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2118 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2119 return FALSE;
2121 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2123 return TRUE;
2127 /***********************************************************************
2128 * GetProcessFlags (KERNEL32.@)
2130 DWORD WINAPI GetProcessFlags( DWORD processid )
2132 IMAGE_NT_HEADERS *nt;
2133 DWORD flags = 0;
2135 if (processid && processid != GetCurrentProcessId()) return 0;
2137 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2139 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2140 flags |= PDB32_CONSOLE_PROC;
2142 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2143 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2144 return flags;
2148 /***********************************************************************
2149 * GetProcessDword (KERNEL.485)
2150 * GetProcessDword (KERNEL32.18)
2151 * 'Of course you cannot directly access Windows internal structures'
2153 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2155 DWORD x, y;
2156 STARTUPINFOW siw;
2158 TRACE("(%d, %d)\n", dwProcessID, offset );
2160 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2162 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2163 return 0;
2166 switch ( offset )
2168 case GPD_APP_COMPAT_FLAGS:
2169 return GetAppCompatFlags16(0);
2170 case GPD_LOAD_DONE_EVENT:
2171 return 0;
2172 case GPD_HINSTANCE16:
2173 return GetTaskDS16();
2174 case GPD_WINDOWS_VERSION:
2175 return GetExeVersion16();
2176 case GPD_THDB:
2177 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2178 case GPD_PDB:
2179 return (DWORD)NtCurrentTeb()->Peb;
2180 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2181 GetStartupInfoW(&siw);
2182 return (DWORD)siw.hStdOutput;
2183 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2184 GetStartupInfoW(&siw);
2185 return (DWORD)siw.hStdInput;
2186 case GPD_STARTF_SHOWWINDOW:
2187 GetStartupInfoW(&siw);
2188 return siw.wShowWindow;
2189 case GPD_STARTF_SIZE:
2190 GetStartupInfoW(&siw);
2191 x = siw.dwXSize;
2192 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2193 y = siw.dwYSize;
2194 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2195 return MAKELONG( x, y );
2196 case GPD_STARTF_POSITION:
2197 GetStartupInfoW(&siw);
2198 x = siw.dwX;
2199 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2200 y = siw.dwY;
2201 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2202 return MAKELONG( x, y );
2203 case GPD_STARTF_FLAGS:
2204 GetStartupInfoW(&siw);
2205 return siw.dwFlags;
2206 case GPD_PARENT:
2207 return 0;
2208 case GPD_FLAGS:
2209 return GetProcessFlags(0);
2210 case GPD_USERDATA:
2211 return process_dword;
2212 default:
2213 ERR("Unknown offset %d\n", offset );
2214 return 0;
2218 /***********************************************************************
2219 * SetProcessDword (KERNEL.484)
2220 * 'Of course you cannot directly access Windows internal structures'
2222 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2224 TRACE("(%d, %d)\n", dwProcessID, offset );
2226 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2228 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2229 return;
2232 switch ( offset )
2234 case GPD_APP_COMPAT_FLAGS:
2235 case GPD_LOAD_DONE_EVENT:
2236 case GPD_HINSTANCE16:
2237 case GPD_WINDOWS_VERSION:
2238 case GPD_THDB:
2239 case GPD_PDB:
2240 case GPD_STARTF_SHELLDATA:
2241 case GPD_STARTF_HOTKEY:
2242 case GPD_STARTF_SHOWWINDOW:
2243 case GPD_STARTF_SIZE:
2244 case GPD_STARTF_POSITION:
2245 case GPD_STARTF_FLAGS:
2246 case GPD_PARENT:
2247 case GPD_FLAGS:
2248 ERR("Not allowed to modify offset %d\n", offset );
2249 break;
2250 case GPD_USERDATA:
2251 process_dword = value;
2252 break;
2253 default:
2254 ERR("Unknown offset %d\n", offset );
2255 break;
2260 /***********************************************************************
2261 * ExitProcess (KERNEL.466)
2263 void WINAPI ExitProcess16( WORD status )
2265 DWORD count;
2266 ReleaseThunkLock( &count );
2267 ExitProcess( status );
2271 /*********************************************************************
2272 * OpenProcess (KERNEL32.@)
2274 * Opens a handle to a process.
2276 * PARAMS
2277 * access [I] Desired access rights assigned to the returned handle.
2278 * inherit [I] Determines whether or not child processes will inherit the handle.
2279 * id [I] Process identifier of the process to get a handle to.
2281 * RETURNS
2282 * Success: Valid handle to the specified process.
2283 * Failure: NULL, check GetLastError().
2285 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2287 NTSTATUS status;
2288 HANDLE handle;
2289 OBJECT_ATTRIBUTES attr;
2290 CLIENT_ID cid;
2292 cid.UniqueProcess = (HANDLE)id;
2293 cid.UniqueThread = 0; /* FIXME ? */
2295 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2296 attr.RootDirectory = NULL;
2297 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2298 attr.SecurityDescriptor = NULL;
2299 attr.SecurityQualityOfService = NULL;
2300 attr.ObjectName = NULL;
2302 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2304 status = NtOpenProcess(&handle, access, &attr, &cid);
2305 if (status != STATUS_SUCCESS)
2307 SetLastError( RtlNtStatusToDosError(status) );
2308 return NULL;
2310 return handle;
2314 /*********************************************************************
2315 * MapProcessHandle (KERNEL.483)
2316 * GetProcessId (KERNEL32.@)
2318 * Gets the a unique identifier of a process.
2320 * PARAMS
2321 * hProcess [I] Handle to the process.
2323 * RETURNS
2324 * Success: TRUE.
2325 * Failure: FALSE, check GetLastError().
2327 * NOTES
2329 * The identifier is unique only on the machine and only until the process
2330 * exits (including system shutdown).
2332 DWORD WINAPI GetProcessId( HANDLE hProcess )
2334 NTSTATUS status;
2335 PROCESS_BASIC_INFORMATION pbi;
2337 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2338 sizeof(pbi), NULL);
2339 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2340 SetLastError( RtlNtStatusToDosError(status) );
2341 return 0;
2345 /*********************************************************************
2346 * CloseW32Handle (KERNEL.474)
2347 * CloseHandle (KERNEL32.@)
2349 * Closes a handle.
2351 * PARAMS
2352 * handle [I] Handle to close.
2354 * RETURNS
2355 * Success: TRUE.
2356 * Failure: FALSE, check GetLastError().
2358 BOOL WINAPI CloseHandle( HANDLE handle )
2360 NTSTATUS status;
2362 /* stdio handles need special treatment */
2363 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2364 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2365 (handle == (HANDLE)STD_ERROR_HANDLE))
2366 handle = GetStdHandle( (DWORD)handle );
2368 if (is_console_handle(handle))
2369 return CloseConsoleHandle(handle);
2371 status = NtClose( handle );
2372 if (status) SetLastError( RtlNtStatusToDosError(status) );
2373 return !status;
2377 /*********************************************************************
2378 * GetHandleInformation (KERNEL32.@)
2380 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2382 OBJECT_DATA_INFORMATION info;
2383 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2385 if (status) SetLastError( RtlNtStatusToDosError(status) );
2386 else if (flags)
2388 *flags = 0;
2389 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2390 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2392 return !status;
2396 /*********************************************************************
2397 * SetHandleInformation (KERNEL32.@)
2399 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2401 OBJECT_DATA_INFORMATION info;
2402 NTSTATUS status;
2404 /* if not setting both fields, retrieve current value first */
2405 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2406 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2408 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2410 SetLastError( RtlNtStatusToDosError(status) );
2411 return FALSE;
2414 if (mask & HANDLE_FLAG_INHERIT)
2415 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2416 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2417 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2419 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2420 if (status) SetLastError( RtlNtStatusToDosError(status) );
2421 return !status;
2425 /*********************************************************************
2426 * DuplicateHandle (KERNEL32.@)
2428 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2429 HANDLE dest_process, HANDLE *dest,
2430 DWORD access, BOOL inherit, DWORD options )
2432 NTSTATUS status;
2434 if (is_console_handle(source))
2436 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2437 if (source_process != dest_process ||
2438 source_process != GetCurrentProcess())
2440 SetLastError(ERROR_INVALID_PARAMETER);
2441 return FALSE;
2443 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2444 return (*dest != INVALID_HANDLE_VALUE);
2446 status = NtDuplicateObject( source_process, source, dest_process, dest,
2447 access, inherit ? OBJ_INHERIT : 0, options );
2448 if (status) SetLastError( RtlNtStatusToDosError(status) );
2449 return !status;
2453 /***********************************************************************
2454 * ConvertToGlobalHandle (KERNEL.476)
2455 * ConvertToGlobalHandle (KERNEL32.@)
2457 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2459 HANDLE ret = INVALID_HANDLE_VALUE;
2460 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2461 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2462 return ret;
2466 /***********************************************************************
2467 * SetHandleContext (KERNEL32.@)
2469 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2471 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2472 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2473 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2474 return FALSE;
2478 /***********************************************************************
2479 * GetHandleContext (KERNEL32.@)
2481 DWORD WINAPI GetHandleContext(HANDLE hnd)
2483 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2484 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2485 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2486 return 0;
2490 /***********************************************************************
2491 * CreateSocketHandle (KERNEL32.@)
2493 HANDLE WINAPI CreateSocketHandle(void)
2495 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2496 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2497 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2498 return INVALID_HANDLE_VALUE;
2502 /***********************************************************************
2503 * SetPriorityClass (KERNEL32.@)
2505 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2507 NTSTATUS status;
2508 PROCESS_PRIORITY_CLASS ppc;
2510 ppc.Foreground = FALSE;
2511 switch (priorityclass)
2513 case IDLE_PRIORITY_CLASS:
2514 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2515 case BELOW_NORMAL_PRIORITY_CLASS:
2516 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2517 case NORMAL_PRIORITY_CLASS:
2518 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2519 case ABOVE_NORMAL_PRIORITY_CLASS:
2520 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2521 case HIGH_PRIORITY_CLASS:
2522 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2523 case REALTIME_PRIORITY_CLASS:
2524 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2525 default:
2526 SetLastError(ERROR_INVALID_PARAMETER);
2527 return FALSE;
2530 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2531 &ppc, sizeof(ppc));
2533 if (status != STATUS_SUCCESS)
2535 SetLastError( RtlNtStatusToDosError(status) );
2536 return FALSE;
2538 return TRUE;
2542 /***********************************************************************
2543 * GetPriorityClass (KERNEL32.@)
2545 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2547 NTSTATUS status;
2548 PROCESS_BASIC_INFORMATION pbi;
2550 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2551 sizeof(pbi), NULL);
2552 if (status != STATUS_SUCCESS)
2554 SetLastError( RtlNtStatusToDosError(status) );
2555 return 0;
2557 switch (pbi.BasePriority)
2559 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2560 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2561 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2562 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2563 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2564 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2566 SetLastError( ERROR_INVALID_PARAMETER );
2567 return 0;
2571 /***********************************************************************
2572 * SetProcessAffinityMask (KERNEL32.@)
2574 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2576 NTSTATUS status;
2578 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2579 &affmask, sizeof(DWORD_PTR));
2580 if (!status)
2582 SetLastError( RtlNtStatusToDosError(status) );
2583 return FALSE;
2585 return TRUE;
2589 /**********************************************************************
2590 * GetProcessAffinityMask (KERNEL32.@)
2592 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2593 PDWORD_PTR lpProcessAffinityMask,
2594 PDWORD_PTR lpSystemAffinityMask )
2596 PROCESS_BASIC_INFORMATION pbi;
2597 NTSTATUS status;
2599 status = NtQueryInformationProcess(hProcess,
2600 ProcessBasicInformation,
2601 &pbi, sizeof(pbi), NULL);
2602 if (status)
2604 SetLastError( RtlNtStatusToDosError(status) );
2605 return FALSE;
2607 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2608 /* FIXME */
2609 if (lpSystemAffinityMask) *lpSystemAffinityMask = 1;
2610 return TRUE;
2614 /***********************************************************************
2615 * GetProcessVersion (KERNEL32.@)
2617 DWORD WINAPI GetProcessVersion( DWORD processid )
2619 IMAGE_NT_HEADERS *nt;
2621 if (processid && processid != GetCurrentProcessId())
2623 FIXME("should use ReadProcessMemory\n");
2624 return 0;
2626 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2627 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2628 nt->OptionalHeader.MinorSubsystemVersion);
2629 return 0;
2633 /***********************************************************************
2634 * SetProcessWorkingSetSize [KERNEL32.@]
2635 * Sets the min/max working set sizes for a specified process.
2637 * PARAMS
2638 * hProcess [I] Handle to the process of interest
2639 * minset [I] Specifies minimum working set size
2640 * maxset [I] Specifies maximum working set size
2642 * RETURNS
2643 * Success: TRUE
2644 * Failure: FALSE
2646 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2647 SIZE_T maxset)
2649 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2650 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2651 /* Trim the working set to zero */
2652 /* Swap the process out of physical RAM */
2654 return TRUE;
2657 /***********************************************************************
2658 * GetProcessWorkingSetSize (KERNEL32.@)
2660 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2661 PSIZE_T maxset)
2663 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2664 /* 32 MB working set size */
2665 if (minset) *minset = 32*1024*1024;
2666 if (maxset) *maxset = 32*1024*1024;
2667 return TRUE;
2671 /***********************************************************************
2672 * SetProcessShutdownParameters (KERNEL32.@)
2674 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2676 FIXME("(%08x, %08x): partial stub.\n", level, flags);
2677 shutdown_flags = flags;
2678 shutdown_priority = level;
2679 return TRUE;
2683 /***********************************************************************
2684 * GetProcessShutdownParameters (KERNEL32.@)
2687 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2689 *lpdwLevel = shutdown_priority;
2690 *lpdwFlags = shutdown_flags;
2691 return TRUE;
2695 /***********************************************************************
2696 * GetProcessPriorityBoost (KERNEL32.@)
2698 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2700 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2702 /* Report that no boost is present.. */
2703 *pDisablePriorityBoost = FALSE;
2705 return TRUE;
2708 /***********************************************************************
2709 * SetProcessPriorityBoost (KERNEL32.@)
2711 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2713 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2714 /* Say we can do it. I doubt the program will notice that we don't. */
2715 return TRUE;
2719 /***********************************************************************
2720 * ReadProcessMemory (KERNEL32.@)
2722 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2723 SIZE_T *bytes_read )
2725 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2726 if (status) SetLastError( RtlNtStatusToDosError(status) );
2727 return !status;
2731 /***********************************************************************
2732 * WriteProcessMemory (KERNEL32.@)
2734 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2735 SIZE_T *bytes_written )
2737 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2738 if (status) SetLastError( RtlNtStatusToDosError(status) );
2739 return !status;
2743 /****************************************************************************
2744 * FlushInstructionCache (KERNEL32.@)
2746 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2748 NTSTATUS status;
2749 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2750 if (status) SetLastError( RtlNtStatusToDosError(status) );
2751 return !status;
2755 /******************************************************************
2756 * GetProcessIoCounters (KERNEL32.@)
2758 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2760 NTSTATUS status;
2762 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2763 ioc, sizeof(*ioc), NULL);
2764 if (status) SetLastError( RtlNtStatusToDosError(status) );
2765 return !status;
2768 /***********************************************************************
2769 * ProcessIdToSessionId (KERNEL32.@)
2770 * This function is available on Terminal Server 4SP4 and Windows 2000
2772 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2774 /* According to MSDN, if the calling process is not in a terminal
2775 * services environment, then the sessionid returned is zero.
2777 *sessionid_ptr = 0;
2778 return TRUE;
2782 /***********************************************************************
2783 * RegisterServiceProcess (KERNEL.491)
2784 * RegisterServiceProcess (KERNEL32.@)
2786 * A service process calls this function to ensure that it continues to run
2787 * even after a user logged off.
2789 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2791 /* I don't think that Wine needs to do anything in this function */
2792 return 1; /* success */
2796 /**********************************************************************
2797 * IsWow64Process (KERNEL32.@)
2799 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
2801 FIXME("(%p %p) stub!\n", hProcess, Wow64Process);
2802 *Wow64Process = FALSE;
2803 return TRUE;
2807 /***********************************************************************
2808 * GetCurrentProcess (KERNEL32.@)
2810 * Get a handle to the current process.
2812 * PARAMS
2813 * None.
2815 * RETURNS
2816 * A handle representing the current process.
2818 #undef GetCurrentProcess
2819 HANDLE WINAPI GetCurrentProcess(void)
2821 return (HANDLE)0xffffffff;
2824 /***********************************************************************
2825 * CmdBatNotification (KERNEL32.@)
2827 * Notifies the system that a batch file has started or finished.
2829 * PARAMS
2830 * bBatchRunning [I] TRUE if a batch file has started or
2831 * FALSE if a batch file has finished executing.
2833 * RETURNS
2834 * Unknown.
2836 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
2838 FIXME("%d\n", bBatchRunning);
2839 return FALSE;