4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
34 #include <sys/types.h>
37 #define WIN32_NO_STATUS
38 #include "wine/winbase16.h"
39 #include "wine/winuser16.h"
43 #include "kernel_private.h"
44 #include "wine/exception.h"
45 #include "wine/server.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
49 #ifdef HAVE_VALGRIND_MEMCHECK_H
50 #include <valgrind/memcheck.h>
53 WINE_DEFAULT_DEBUG_CHANNEL(process);
54 WINE_DECLARE_DEBUG_CHANNEL(file);
55 WINE_DECLARE_DEBUG_CHANNEL(relay);
65 static UINT process_error_mode;
67 static HANDLE main_exe_file;
68 static DWORD shutdown_flags = 0;
69 static DWORD shutdown_priority = 0x280;
70 static DWORD process_dword;
72 HMODULE kernel32_handle = 0;
74 const WCHAR *DIR_Windows = NULL;
75 const WCHAR *DIR_System = NULL;
78 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
79 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
80 #define PDB32_DOS_PROC 0x0010 /* Dos process */
81 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
82 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
83 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
85 static const WCHAR comW[] = {'.','c','o','m',0};
86 static const WCHAR batW[] = {'.','b','a','t',0};
87 static const WCHAR pifW[] = {'.','p','i','f',0};
88 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
90 extern void SHELL_LoadRegistry(void);
93 /***********************************************************************
96 inline static int contains_path( LPCWSTR name )
98 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
102 /***********************************************************************
105 * Check if an environment variable needs to be handled specially when
106 * passed through the Unix environment (i.e. prefixed with "WINE").
108 inline static int is_special_env_var( const char *var )
110 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
111 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
112 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
113 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
117 /***************************************************************************
120 * Get the path of a builtin module when the native file does not exist.
122 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
125 UINT len = strlenW( DIR_System );
127 if (contains_path( libname ))
129 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
130 filename, &file_part ) > size * sizeof(WCHAR))
131 return FALSE; /* too long */
133 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
135 while (filename[len] == '\\') len++;
136 if (filename + len != file_part) return FALSE;
140 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
141 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
142 file_part = filename + len;
143 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
144 strcpyW( file_part, libname );
146 if (ext && !strchrW( file_part, '.' ))
148 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
149 return FALSE; /* too long */
150 strcatW( file_part, ext );
156 /***********************************************************************
157 * open_builtin_exe_file
159 * Open an exe file for a builtin exe.
161 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
162 int test_only, int *file_exists )
164 char exename[MAX_PATH];
169 if ((p = strrchrW( name, '/' ))) name = p + 1;
170 if ((p = strrchrW( name, '\\' ))) name = p + 1;
172 /* we don't want to depend on the current codepage here */
173 len = strlenW( name ) + 1;
174 if (len >= sizeof(exename)) return NULL;
175 for (i = 0; i < len; i++)
177 if (name[i] > 127) return NULL;
178 exename[i] = (char)name[i];
179 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
181 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
185 /***********************************************************************
188 * Open a specific exe file, taking load order into account.
189 * Returns the file handle or 0 for a builtin exe.
191 static HANDLE open_exe_file( const WCHAR *name )
193 enum loadorder_type loadorder[LOADORDER_NTYPES];
194 WCHAR buffer[MAX_PATH];
198 TRACE("looking for %s\n", debugstr_w(name) );
200 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
201 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
203 /* file doesn't exist, check for builtin */
204 if (!contains_path( name )) goto error;
205 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
209 MODULE_GetLoadOrderW( loadorder, NULL, name );
211 for(i = 0; i < LOADORDER_NTYPES; i++)
213 if (loadorder[i] == LOADORDER_INVALID) break;
217 TRACE( "Trying native exe %s\n", debugstr_w(name) );
218 if (handle != INVALID_HANDLE_VALUE) return handle;
221 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
222 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
225 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
232 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
235 SetLastError( ERROR_FILE_NOT_FOUND );
236 return INVALID_HANDLE_VALUE;
240 /***********************************************************************
243 * Open an exe file, and return the full name and file handle.
244 * Returns FALSE if file could not be found.
245 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
246 * If file is a builtin exe, returns TRUE and sets handle to 0.
248 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
250 static const WCHAR exeW[] = {'.','e','x','e',0};
252 enum loadorder_type loadorder[LOADORDER_NTYPES];
255 TRACE("looking for %s\n", debugstr_w(name) );
257 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
258 !get_builtin_path( name, exeW, buffer, buflen ))
260 /* no builtin found, try native without extension in case it is a Unix app */
262 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
264 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
265 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
266 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
272 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
274 for(i = 0; i < LOADORDER_NTYPES; i++)
276 if (loadorder[i] == LOADORDER_INVALID) break;
280 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
281 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
282 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
284 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
287 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
288 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
299 SetLastError( ERROR_FILE_NOT_FOUND );
304 /***********************************************************************
305 * build_initial_environment
307 * Build the Win32 environment from the Unix environment
309 static BOOL build_initial_environment( char **environ )
316 /* Compute the total size of the Unix environment */
317 for (e = environ; *e; e++)
319 if (is_special_env_var( *e )) continue;
320 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
322 size *= sizeof(WCHAR);
324 /* Now allocate the environment */
326 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
327 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
330 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
331 endptr = p + size / sizeof(WCHAR);
333 /* And fill it with the Unix environment */
334 for (e = environ; *e; e++)
338 /* skip Unix special variables and use the Wine variants instead */
339 if (!strncmp( str, "WINE", 4 ))
341 if (is_special_env_var( str + 4 )) str += 4;
342 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
344 else if (is_special_env_var( str )) continue; /* skip it */
346 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
354 /***********************************************************************
355 * set_registry_variables
357 * Set environment variables by enumerating the values of a key;
358 * helper for set_registry_environment().
359 * Note that Windows happily truncates the value if it's too big.
361 static void set_registry_variables( HANDLE hkey, ULONG type )
363 UNICODE_STRING env_name, env_value;
367 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
368 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
370 for (index = 0; ; index++)
372 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
373 buffer, sizeof(buffer), &size );
374 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
376 if (info->Type != type)
378 env_name.Buffer = info->Name;
379 env_name.Length = env_name.MaximumLength = info->NameLength;
380 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
381 env_value.Length = env_value.MaximumLength = info->DataLength;
382 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
383 env_value.Length--; /* don't count terminating null if any */
384 if (info->Type == REG_EXPAND_SZ)
386 WCHAR buf_expanded[1024];
387 UNICODE_STRING env_expanded;
388 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
389 env_expanded.Buffer=buf_expanded;
390 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
391 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
392 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
396 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
402 /***********************************************************************
403 * set_registry_environment
405 * Set the environment variables specified in the registry.
407 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
408 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
409 * on the order in which the variables are processed. But on Windows it
410 * does not really matter since they only use %SystemDrive% and
411 * %SystemRoot% which are predefined. But Wine defines these in the
412 * registry, so we need two passes.
414 static void set_registry_environment(void)
416 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
417 'S','y','s','t','e','m','\\',
418 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
419 'C','o','n','t','r','o','l','\\',
420 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
421 'E','n','v','i','r','o','n','m','e','n','t',0};
422 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
424 OBJECT_ATTRIBUTES attr;
425 UNICODE_STRING nameW;
428 attr.Length = sizeof(attr);
429 attr.RootDirectory = 0;
430 attr.ObjectName = &nameW;
432 attr.SecurityDescriptor = NULL;
433 attr.SecurityQualityOfService = NULL;
435 /* first the system environment variables */
436 RtlInitUnicodeString( &nameW, env_keyW );
437 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
439 set_registry_variables( hkey, REG_SZ );
440 set_registry_variables( hkey, REG_EXPAND_SZ );
444 /* then the ones for the current user */
445 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return;
446 RtlInitUnicodeString( &nameW, envW );
447 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
449 set_registry_variables( hkey, REG_SZ );
450 set_registry_variables( hkey, REG_EXPAND_SZ );
453 NtClose( attr.RootDirectory );
457 /***********************************************************************
460 * Set the Wine library Unicode argv global variables.
462 static void set_library_wargv( char **argv )
470 for (argc = 0; argv[argc]; argc++)
471 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
473 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
474 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
475 p = (WCHAR *)(wargv + argc + 1);
476 for (argc = 0; argv[argc]; argc++)
478 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
485 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
487 for (argc = 0; wargv[argc]; argc++)
488 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
490 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
491 q = (char *)(argv + argc + 1);
492 for (argc = 0; wargv[argc]; argc++)
494 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
501 __wine_main_argv = argv;
502 __wine_main_wargv = wargv;
506 /***********************************************************************
509 * Build the command line of a process from the argv array.
511 * Note that it does NOT necessarily include the file name.
512 * Sometimes we don't even have any command line options at all.
514 * We must quote and escape characters so that the argv array can be rebuilt
515 * from the command line:
516 * - spaces and tabs must be quoted
518 * - quotes must be escaped
520 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
521 * resulting in an odd number of '\' followed by a '"'
524 * - '\'s that are not followed by a '"' can be left as is
528 static BOOL build_command_line( WCHAR **argv )
533 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
535 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
538 for (arg = argv; *arg; arg++)
540 int has_space,bcount;
546 if( !*a ) has_space=1;
551 if (*a==' ' || *a=='\t') {
553 } else if (*a=='"') {
554 /* doubling of '\' preceding a '"',
555 * plus escaping of said '"'
563 len+=(a-*arg)+1 /* for the separating space */;
565 len+=2; /* for the quotes */
568 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
571 p = rupp->CommandLine.Buffer;
572 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
573 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
574 for (arg = argv; *arg; arg++)
576 int has_space,has_quote;
579 /* Check for quotes and spaces in this argument */
580 has_space=has_quote=0;
582 if( !*a ) has_space=1;
584 if (*a==' ' || *a=='\t') {
588 } else if (*a=='"') {
596 /* Now transfer it to the command line */
613 /* Double all the '\\' preceding this '"', plus one */
614 for (i=0;i<=bcount;i++)
626 while ((*p=*x++)) p++;
632 if (p > rupp->CommandLine.Buffer)
633 p--; /* remove last space */
640 /* make sure the unicode string doesn't point beyond the end pointer */
641 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
643 if ((char *)str->Buffer >= end_ptr)
645 str->Length = str->MaximumLength = 0;
649 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
651 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
653 if (str->Length >= str->MaximumLength)
655 if (str->MaximumLength >= sizeof(WCHAR))
656 str->Length = str->MaximumLength - sizeof(WCHAR);
658 str->Length = str->MaximumLength = 0;
662 static void version(void)
664 MESSAGE( "%s\n", PACKAGE_STRING );
668 static void usage(void)
670 MESSAGE( "%s\n", PACKAGE_STRING );
671 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
672 MESSAGE( " wine --help Display this help and exit\n");
673 MESSAGE( " wine --version Output version information and exit\n");
678 /***********************************************************************
679 * init_user_process_params
681 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
683 static BOOL init_user_process_params( RTL_USER_PROCESS_PARAMETERS *params )
687 SIZE_T size, env_size, info_size;
688 HANDLE hstdin, hstdout, hstderr;
690 size = info_size = params->AllocationSize;
691 if (!size) return TRUE; /* no parameters received from parent */
693 SERVER_START_REQ( get_startup_info )
695 wine_server_set_reply( req, params, size );
696 if ((ret = !wine_server_call( req )))
698 info_size = wine_server_reply_size( reply );
699 main_exe_file = reply->exe_file;
700 hstdin = reply->hstdin;
701 hstdout = reply->hstdout;
702 hstderr = reply->hstderr;
706 if (!ret) return ret;
708 params->AllocationSize = size;
709 if (params->Size > info_size) params->Size = info_size;
711 /* make sure the strings are valid */
712 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
713 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
714 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
715 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
716 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
717 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
718 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
719 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
721 /* environment needs to be a separate memory block */
722 env_size = info_size - params->Size;
723 if (!env_size) env_size = 1;
725 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
726 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
728 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
729 params->Environment = ptr;
731 /* convert value from server:
732 * + 0 => INVALID_HANDLE_VALUE
733 * + console handle needs to be mapped
736 hstdin = INVALID_HANDLE_VALUE;
737 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
738 hstdin = console_handle_map(hstdin);
741 hstdout = INVALID_HANDLE_VALUE;
742 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
743 hstdout = console_handle_map(hstdout);
746 hstderr = INVALID_HANDLE_VALUE;
747 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
748 hstderr = console_handle_map(hstderr);
750 params->hStdInput = hstdin;
751 params->hStdOutput = hstdout;
752 params->hStdError = hstderr;
754 RtlNormalizeProcessParams( params );
759 /***********************************************************************
760 * init_current_directory
762 * Initialize the current directory from the Unix cwd or the parent info.
764 static void init_current_directory( CURDIR *cur_dir )
766 UNICODE_STRING dir_str;
770 /* if we received a cur dir from the parent, try this first */
772 if (cur_dir->DosPath.Length)
774 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
777 /* now try to get it from the Unix cwd */
779 for (size = 256; ; size *= 2)
781 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
782 if (getcwd( cwd, size )) break;
783 HeapFree( GetProcessHeap(), 0, cwd );
784 if (errno == ERANGE) continue;
792 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
793 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
795 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
796 RtlInitUnicodeString( &dir_str, dirW );
797 RtlSetCurrentDirectory_U( &dir_str );
798 RtlFreeUnicodeString( &dir_str );
802 if (!cur_dir->DosPath.Length) /* still not initialized */
804 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
805 "starting in the Windows directory.\n", cwd ? cwd : "" );
806 RtlInitUnicodeString( &dir_str, DIR_Windows );
807 RtlSetCurrentDirectory_U( &dir_str );
809 HeapFree( GetProcessHeap(), 0, cwd );
812 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
813 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
817 /***********************************************************************
820 * Initialize the windows and system directories from the environment.
822 static void init_windows_dirs(void)
824 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
826 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
827 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
828 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
829 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
834 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
836 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
837 GetEnvironmentVariableW( windirW, buffer, len );
838 DIR_Windows = buffer;
840 else DIR_Windows = default_windirW;
842 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
844 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
845 GetEnvironmentVariableW( winsysdirW, buffer, len );
850 len = strlenW( DIR_Windows );
851 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
852 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
853 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
857 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
858 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
859 debugstr_w(DIR_Windows) );
860 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
861 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
862 debugstr_w(DIR_System) );
864 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
865 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
867 /* set the directories in ntdll too */
868 __wine_init_windows_dir( DIR_Windows, DIR_System );
872 /***********************************************************************
875 * Main process initialisation code
877 static BOOL process_init(void)
879 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
880 PEB *peb = NtCurrentTeb()->Peb;
886 setlocale(LC_CTYPE,"");
888 if (!init_user_process_params( peb->ProcessParameters )) return FALSE;
890 kernel32_handle = GetModuleHandleW(kernel32W);
894 if (!peb->ProcessParameters->Environment)
896 /* Copy the parent environment */
897 if (!build_initial_environment( __wine_main_environ )) return FALSE;
899 /* convert old configuration to new format */
900 convert_old_config();
902 set_registry_environment();
906 init_current_directory( &peb->ProcessParameters->CurrentDirectory );
912 /***********************************************************************
915 * Allocate the stack of new process.
917 static void *init_stack(void)
920 SIZE_T stack_size, page_size = getpagesize();
921 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
923 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
924 stack_size += page_size; /* for the guard page */
925 stack_size = (stack_size + 0xffff) & ~0xffff; /* round to 64K boundary */
926 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
928 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
930 ERR( "failed to allocate main process stack\n" );
934 /* note: limit is lower than base since the stack grows down */
935 NtCurrentTeb()->DeallocationStack = base;
936 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
937 NtCurrentTeb()->Tib.StackLimit = (char *)base + page_size;
939 #ifdef VALGRIND_STACK_REGISTER
940 /* no need to de-register the stack as it's the one of the main thread */
941 VALGRIND_STACK_REGISTER(NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase);
944 /* setup guard page */
945 VirtualProtect( base, page_size, PAGE_NOACCESS, NULL );
946 return NtCurrentTeb()->Tib.StackBase;
950 /***********************************************************************
953 * Startup routine of a new process. Runs on the new process stack.
955 static void start_process( void *arg )
959 PEB *peb = NtCurrentTeb()->Peb;
960 IMAGE_NT_HEADERS *nt;
961 LPTHREAD_START_ROUTINE entry;
963 LdrInitializeThunk( 0, 0, 0, 0 );
965 nt = RtlImageNtHeader( peb->ImageBaseAddress );
966 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
967 nt->OptionalHeader.AddressOfEntryPoint);
970 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
971 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
973 SetLastError( 0 ); /* clear error code */
974 if (peb->BeingDebugged) DbgBreakPoint();
975 ExitProcess( entry( peb ) );
977 __EXCEPT(UnhandledExceptionFilter)
979 TerminateThread( GetCurrentThread(), GetExceptionCode() );
985 /***********************************************************************
988 * Wine initialisation: load and start the main exe file.
990 void __wine_kernel_init(void)
992 WCHAR *main_exe_name, *p;
995 PEB *peb = NtCurrentTeb()->Peb;
997 /* Initialize everything */
998 if (!process_init()) exit(1);
1000 __wine_main_argv++; /* remove argv[0] (wine itself) */
1003 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1005 WCHAR buffer[MAX_PATH];
1006 WCHAR exe_nameW[MAX_PATH];
1008 if (!__wine_main_argv[0]) usage();
1009 if (__wine_main_argc == 1)
1011 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1012 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1015 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1016 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1018 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1021 if (main_exe_file == INVALID_HANDLE_VALUE)
1023 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1026 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1027 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1030 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1031 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1033 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1034 MODULE_get_dll_load_path(NULL) );
1036 if (!main_exe_file) /* no file handle -> Winelib app */
1038 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1039 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ) &&
1040 NtCurrentTeb()->Peb->ImageBaseAddress)
1042 MESSAGE( "wine: cannot open builtin exe for %s: %s\n",
1043 debugstr_w(main_exe_name), error );
1047 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1050 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1051 if ((peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1053 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1056 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1058 case BINARY_UNKNOWN:
1059 /* check for .com extension */
1060 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1062 MESSAGE( "wine: cannot determine executable type for %s\n",
1063 debugstr_w(main_exe_name) );
1070 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1073 __wine_main_argv[0] = "winevdm.exe";
1074 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1076 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1077 debugstr_w(main_exe_name), error );
1079 case BINARY_UNIX_EXE:
1080 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1082 case BINARY_UNIX_LIB:
1086 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1087 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1088 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1090 static const WCHAR soW[] = {'.','s','o',0};
1091 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1094 /* update the unicode string */
1095 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1097 HeapFree( GetProcessHeap(), 0, unix_name );
1100 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1106 CloseHandle( main_exe_file );
1108 /* build command line */
1109 set_library_wargv( __wine_main_argv );
1110 if (!build_command_line( __wine_main_wargv )) goto error;
1112 /* switch to the new stack */
1113 wine_switch_to_stack( start_process, NULL, init_stack() );
1116 ExitProcess( GetLastError() );
1120 /***********************************************************************
1123 * Build an argv array from a command-line.
1124 * 'reserved' is the number of args to reserve before the first one.
1126 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1130 char *arg,*s,*d,*cmdline;
1131 int in_quotes,bcount,len;
1133 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1134 if (!(cmdline = malloc(len))) return NULL;
1135 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1142 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1145 /* skip the remaining spaces */
1146 while (*s==' ' || *s=='\t') {
1153 } else if (*s=='\\') {
1154 /* '\', count them */
1156 } else if ((*s=='"') && ((bcount & 1)==0)) {
1158 in_quotes=!in_quotes;
1161 /* a regular character */
1166 argv=malloc(argc*sizeof(*argv));
1175 if ((*s==' ' || *s=='\t') && !in_quotes) {
1176 /* Close the argument and copy it */
1180 /* skip the remaining spaces */
1183 } while (*s==' ' || *s=='\t');
1185 /* Start with a new argument */
1188 } else if (*s=='\\') {
1192 } else if (*s=='"') {
1194 if ((bcount & 1)==0) {
1195 /* Preceded by an even number of '\', this is half that
1196 * number of '\', plus a '"' which we discard.
1200 in_quotes=!in_quotes;
1202 /* Preceded by an odd number of '\', this is half that
1203 * number of '\' followed by a '"'
1211 /* a regular character */
1226 /***********************************************************************
1229 * Allocate an environment string; helper for build_envp
1231 static char *alloc_env_string( const char *name, const char *value )
1233 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1234 strcpy( ret, name );
1235 strcat( ret, value );
1239 /***********************************************************************
1242 * Build the environment of a new child process.
1244 static char **build_envp( const WCHAR *envW )
1249 int count = 0, length;
1251 for (end = envW; *end; count++) end += strlenW(end) + 1;
1253 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1254 if (!(env = malloc( length ))) return NULL;
1255 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1259 if ((envp = malloc( count * sizeof(*envp) )))
1261 char **envptr = envp;
1263 /* some variables must not be modified, so we get them directly from the unix env */
1264 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1265 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1266 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1267 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1268 /* now put the Windows environment strings */
1269 for (p = env; *p; p += strlen(p) + 1)
1271 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1272 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1273 if (is_special_env_var( p )) /* prefix it with "WINE" */
1274 *envptr++ = alloc_env_string( "WINE", p );
1284 /***********************************************************************
1287 * Fork and exec a new Unix binary, checking for errors.
1289 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1290 const WCHAR *env, const char *newdir )
1295 if (!env) env = GetEnvironmentStringsW();
1299 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1302 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1303 if (!(pid = fork())) /* child */
1305 char **argv = build_argv( cmdline, 0 );
1306 char **envp = build_envp( env );
1309 /* Reset signals that we previously set to SIG_IGN */
1310 signal( SIGPIPE, SIG_DFL );
1311 signal( SIGCHLD, SIG_DFL );
1313 if (newdir) chdir(newdir);
1315 if (argv && envp) execve( filename, argv, envp );
1317 write( fd[1], &err, sizeof(err) );
1321 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1326 if (pid == -1) FILE_SetDosError();
1332 /***********************************************************************
1333 * create_user_params
1335 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1336 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1337 const STARTUPINFOW *startup )
1339 RTL_USER_PROCESS_PARAMETERS *params;
1340 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1342 WCHAR buffer[MAX_PATH];
1344 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1345 lstrcpynW( buffer, filename, MAX_PATH );
1346 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1347 lstrcpynW( buffer, filename, MAX_PATH );
1348 RtlInitUnicodeString( &image_str, buffer );
1350 RtlInitUnicodeString( &cmdline_str, cmdline );
1351 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1352 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1353 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1354 if (startup->lpReserved2 && startup->cbReserved2)
1357 runtime.MaximumLength = startup->cbReserved2;
1358 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1361 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1362 cur_dir ? &curdir_str : NULL,
1364 startup->lpTitle ? &title : NULL,
1365 startup->lpDesktop ? &desktop : NULL,
1367 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1368 if (status != STATUS_SUCCESS)
1370 SetLastError( RtlNtStatusToDosError(status) );
1374 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1375 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1377 params->hStdInput = startup->hStdInput;
1378 params->hStdOutput = startup->hStdOutput;
1379 params->hStdError = startup->hStdError;
1380 params->dwX = startup->dwX;
1381 params->dwY = startup->dwY;
1382 params->dwXSize = startup->dwXSize;
1383 params->dwYSize = startup->dwYSize;
1384 params->dwXCountChars = startup->dwXCountChars;
1385 params->dwYCountChars = startup->dwYCountChars;
1386 params->dwFillAttribute = startup->dwFillAttribute;
1387 params->dwFlags = startup->dwFlags;
1388 params->wShowWindow = startup->wShowWindow;
1393 /***********************************************************************
1396 * Create a new process. If hFile is a valid handle we have an exe
1397 * file, otherwise it is a Winelib app.
1399 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1400 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1401 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1402 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1403 void *res_start, void *res_end )
1405 BOOL ret, success = FALSE;
1406 HANDLE process_info;
1408 char *winedebug = NULL;
1409 RTL_USER_PROCESS_PARAMETERS *params;
1415 char preloader_reserve[64];
1417 if (!env) RtlAcquirePebLock();
1419 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1421 if (!env) RtlReleasePebLock();
1424 env_end = params->Environment;
1427 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1428 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1430 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1431 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1432 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1434 env_end += strlenW(env_end) + 1;
1438 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1439 (unsigned long)res_start, (unsigned long)res_end, 0 );
1441 /* create the synchronization pipes */
1443 if (pipe( startfd ) == -1)
1445 if (!env) RtlReleasePebLock();
1446 HeapFree( GetProcessHeap(), 0, winedebug );
1447 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1448 RtlDestroyProcessParameters( params );
1451 if (pipe( execfd ) == -1)
1453 if (!env) RtlReleasePebLock();
1454 HeapFree( GetProcessHeap(), 0, winedebug );
1455 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1456 close( startfd[0] );
1457 close( startfd[1] );
1458 RtlDestroyProcessParameters( params );
1461 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1463 /* create the child process */
1465 if (!(pid = fork())) /* child */
1467 char **argv = build_argv( cmd_line, 1 );
1469 close( startfd[1] );
1472 /* wait for parent to tell us to start */
1473 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1475 close( startfd[0] );
1476 /* Reset signals that we previously set to SIG_IGN */
1477 signal( SIGPIPE, SIG_DFL );
1478 signal( SIGCHLD, SIG_DFL );
1480 putenv( preloader_reserve );
1481 if (winedebug) putenv( winedebug );
1482 if (unixdir) chdir(unixdir);
1486 /* first, try for a WINELOADER environment variable */
1487 const char *loader = getenv("WINELOADER");
1488 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1489 /* now use the standard search strategy */
1490 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1493 write( execfd[1], &err, sizeof(err) );
1497 /* this is the parent */
1499 close( startfd[0] );
1501 HeapFree( GetProcessHeap(), 0, winedebug );
1504 if (!env) RtlReleasePebLock();
1505 close( startfd[1] );
1508 RtlDestroyProcessParameters( params );
1512 /* create the process on the server side */
1514 SERVER_START_REQ( new_process )
1516 req->inherit_all = inherit;
1517 req->create_flags = flags;
1518 req->unix_pid = pid;
1519 req->exe_file = hFile;
1520 if (startup->dwFlags & STARTF_USESTDHANDLES)
1522 req->hstdin = startup->hStdInput;
1523 req->hstdout = startup->hStdOutput;
1524 req->hstderr = startup->hStdError;
1528 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1529 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1530 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1533 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1535 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1536 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1537 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1538 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1542 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1543 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1544 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1547 wine_server_add_data( req, params, params->Size );
1548 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1549 ret = !wine_server_call_err( req );
1550 process_info = reply->info;
1554 if (!env) RtlReleasePebLock();
1555 RtlDestroyProcessParameters( params );
1558 close( startfd[1] );
1563 /* tell child to start and wait for it to exec */
1565 write( startfd[1], &dummy, 1 );
1566 close( startfd[1] );
1568 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1573 CloseHandle( process_info );
1578 /* wait for the new process info to be ready */
1580 WaitForSingleObject( process_info, INFINITE );
1581 SERVER_START_REQ( get_new_process_info )
1583 req->info = process_info;
1584 req->process_access = PROCESS_ALL_ACCESS;
1585 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1586 req->thread_access = THREAD_ALL_ACCESS;
1587 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1588 if ((ret = !wine_server_call_err( req )))
1590 info->dwProcessId = (DWORD)reply->pid;
1591 info->dwThreadId = (DWORD)reply->tid;
1592 info->hProcess = reply->phandle;
1593 info->hThread = reply->thandle;
1594 success = reply->success;
1599 if (ret && !success) /* new process failed to start */
1602 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1603 CloseHandle( info->hThread );
1604 CloseHandle( info->hProcess );
1607 CloseHandle( process_info );
1612 /***********************************************************************
1613 * create_vdm_process
1615 * Create a new VDM process for a 16-bit or DOS application.
1617 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1618 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1619 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1620 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1622 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1625 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1626 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1630 SetLastError( ERROR_OUTOFMEMORY );
1633 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1634 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1635 flags, startup, info, unixdir, NULL, NULL );
1636 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1641 /***********************************************************************
1642 * create_cmd_process
1644 * Create a new cmd shell process for a .BAT file.
1646 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1647 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1648 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1649 LPPROCESS_INFORMATION info )
1652 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1653 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1654 WCHAR comspec[MAX_PATH];
1658 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1660 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1661 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1664 strcpyW( newcmdline, comspec );
1665 strcatW( newcmdline, slashcW );
1666 strcatW( newcmdline, cmd_line );
1667 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1668 flags, env, cur_dir, startup, info );
1669 HeapFree( GetProcessHeap(), 0, newcmdline );
1674 /*************************************************************************
1677 * Helper for CreateProcess: retrieve the file name to load from the
1678 * app name and command line. Store the file name in buffer, and
1679 * return a possibly modified command line.
1680 * Also returns a handle to the opened file if it's a Windows binary.
1682 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1683 int buflen, HANDLE *handle )
1685 static const WCHAR quotesW[] = {'"','%','s','"',0};
1687 WCHAR *name, *pos, *ret = NULL;
1691 /* if we have an app name, everything is easy */
1695 /* use the unmodified app name as file name */
1696 lstrcpynW( buffer, appname, buflen );
1697 *handle = open_exe_file( buffer );
1698 if (!(ret = cmdline) || !cmdline[0])
1700 /* no command-line, create one */
1701 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1702 sprintfW( ret, quotesW, appname );
1709 SetLastError( ERROR_INVALID_PARAMETER );
1713 /* first check for a quoted file name */
1715 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1717 int len = p - cmdline - 1;
1718 /* extract the quoted portion as file name */
1719 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1720 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1723 if (find_exe_file( name, buffer, buflen, handle ))
1724 ret = cmdline; /* no change necessary */
1728 /* now try the command-line word by word */
1730 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1738 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1740 if (find_exe_file( name, buffer, buflen, handle ))
1745 if (*p) got_space = TRUE;
1748 if (ret && got_space) /* now build a new command-line with quotes */
1750 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1752 sprintfW( ret, quotesW, name );
1757 HeapFree( GetProcessHeap(), 0, name );
1762 /**********************************************************************
1763 * CreateProcessA (KERNEL32.@)
1765 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1766 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1767 DWORD flags, LPVOID env, LPCSTR cur_dir,
1768 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1771 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1772 UNICODE_STRING desktopW, titleW;
1775 desktopW.Buffer = NULL;
1776 titleW.Buffer = NULL;
1777 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1778 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1779 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1781 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1782 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1784 memcpy( &infoW, startup_info, sizeof(infoW) );
1785 infoW.lpDesktop = desktopW.Buffer;
1786 infoW.lpTitle = titleW.Buffer;
1788 if (startup_info->lpReserved)
1789 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1790 debugstr_a(startup_info->lpReserved));
1792 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1793 inherit, flags, env, cur_dirW, &infoW, info );
1795 HeapFree( GetProcessHeap(), 0, app_nameW );
1796 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1797 HeapFree( GetProcessHeap(), 0, cur_dirW );
1798 RtlFreeUnicodeString( &desktopW );
1799 RtlFreeUnicodeString( &titleW );
1804 /**********************************************************************
1805 * CreateProcessW (KERNEL32.@)
1807 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1808 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1809 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1810 LPPROCESS_INFORMATION info )
1814 char *unixdir = NULL;
1815 WCHAR name[MAX_PATH];
1816 WCHAR *tidy_cmdline, *p, *envW = env;
1817 void *res_start, *res_end;
1819 /* Process the AppName and/or CmdLine to get module name and path */
1821 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1823 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1825 if (hFile == INVALID_HANDLE_VALUE) goto done;
1827 /* Warn if unsupported features are used */
1829 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1830 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1831 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1832 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1833 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1837 unixdir = wine_get_unix_file_name( cur_dir );
1841 WCHAR buf[MAX_PATH];
1842 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1845 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1850 while (*p) p += strlen(p) + 1;
1851 p++; /* final null */
1852 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1853 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1854 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1855 flags |= CREATE_UNICODE_ENVIRONMENT;
1858 info->hThread = info->hProcess = 0;
1859 info->dwProcessId = info->dwThreadId = 0;
1861 /* Determine executable type */
1863 if (!hFile) /* builtin exe */
1865 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1866 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1867 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1871 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1874 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1875 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1876 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1881 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1882 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1883 inherit, flags, startup_info, info, unixdir );
1886 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1887 SetLastError( ERROR_BAD_EXE_FORMAT );
1889 case BINARY_UNIX_LIB:
1890 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1891 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1892 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1894 case BINARY_UNKNOWN:
1895 /* check for .com or .bat extension */
1896 if ((p = strrchrW( name, '.' )))
1898 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1900 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1901 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1902 inherit, flags, startup_info, info, unixdir );
1905 if (!strcmpiW( p, batW ))
1907 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1908 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1909 inherit, flags, startup_info, info );
1914 case BINARY_UNIX_EXE:
1916 /* unknown file, try as unix executable */
1919 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1921 if ((unix_name = wine_get_unix_file_name( name )))
1923 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1924 HeapFree( GetProcessHeap(), 0, unix_name );
1929 CloseHandle( hFile );
1932 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1933 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1934 HeapFree( GetProcessHeap(), 0, unixdir );
1939 /***********************************************************************
1942 * Wrapper to call WaitForInputIdle USER function
1944 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1946 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1948 HMODULE mod = GetModuleHandleA( "user32.dll" );
1951 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1952 if (ptr) return ptr( process, timeout );
1958 /***********************************************************************
1959 * WinExec (KERNEL32.@)
1961 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1963 PROCESS_INFORMATION info;
1964 STARTUPINFOA startup;
1968 memset( &startup, 0, sizeof(startup) );
1969 startup.cb = sizeof(startup);
1970 startup.dwFlags = STARTF_USESHOWWINDOW;
1971 startup.wShowWindow = nCmdShow;
1973 /* cmdline needs to be writeable for CreateProcess */
1974 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1975 strcpy( cmdline, lpCmdLine );
1977 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1978 0, NULL, NULL, &startup, &info ))
1980 /* Give 30 seconds to the app to come up */
1981 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1982 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1984 /* Close off the handles */
1985 CloseHandle( info.hThread );
1986 CloseHandle( info.hProcess );
1988 else if ((ret = GetLastError()) >= 32)
1990 FIXME("Strange error set by CreateProcess: %d\n", ret );
1993 HeapFree( GetProcessHeap(), 0, cmdline );
1998 /**********************************************************************
1999 * LoadModule (KERNEL32.@)
2001 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2003 LOADPARMS32 *params = paramBlock;
2004 PROCESS_INFORMATION info;
2005 STARTUPINFOA startup;
2006 HINSTANCE hInstance;
2008 char filename[MAX_PATH];
2011 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2013 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2014 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2015 return (HINSTANCE)GetLastError();
2017 len = (BYTE)params->lpCmdLine[0];
2018 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2019 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2021 strcpy( cmdline, filename );
2022 p = cmdline + strlen(cmdline);
2024 memcpy( p, params->lpCmdLine + 1, len );
2027 memset( &startup, 0, sizeof(startup) );
2028 startup.cb = sizeof(startup);
2029 if (params->lpCmdShow)
2031 startup.dwFlags = STARTF_USESHOWWINDOW;
2032 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2035 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2036 params->lpEnvAddress, NULL, &startup, &info ))
2038 /* Give 30 seconds to the app to come up */
2039 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2040 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2041 hInstance = (HINSTANCE)33;
2042 /* Close off the handles */
2043 CloseHandle( info.hThread );
2044 CloseHandle( info.hProcess );
2046 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2048 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2049 hInstance = (HINSTANCE)11;
2052 HeapFree( GetProcessHeap(), 0, cmdline );
2057 /******************************************************************************
2058 * TerminateProcess (KERNEL32.@)
2060 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2062 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2063 if (status) SetLastError( RtlNtStatusToDosError(status) );
2068 /***********************************************************************
2069 * ExitProcess (KERNEL32.@)
2071 void WINAPI ExitProcess( DWORD status )
2073 LdrShutdownProcess();
2074 NtTerminateProcess(GetCurrentProcess(), status);
2079 /***********************************************************************
2080 * GetExitCodeProcess [KERNEL32.@]
2082 * Gets termination status of specified process.
2085 * hProcess [in] Handle to the process.
2086 * lpExitCode [out] Address to receive termination status.
2092 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2095 PROCESS_BASIC_INFORMATION pbi;
2097 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2099 if (status == STATUS_SUCCESS)
2101 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2104 SetLastError( RtlNtStatusToDosError(status) );
2109 /***********************************************************************
2110 * SetErrorMode (KERNEL32.@)
2112 UINT WINAPI SetErrorMode( UINT mode )
2114 UINT old = process_error_mode;
2115 process_error_mode = mode;
2120 /**********************************************************************
2121 * TlsAlloc [KERNEL32.@]
2123 * Allocates a thread local storage index.
2126 * Success: TLS index.
2127 * Failure: 0xFFFFFFFF
2129 DWORD WINAPI TlsAlloc( void )
2132 PEB * const peb = NtCurrentTeb()->Peb;
2134 RtlAcquirePebLock();
2135 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2136 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2139 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2142 if (!NtCurrentTeb()->TlsExpansionSlots &&
2143 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2144 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2146 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2148 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2152 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2153 index += TLS_MINIMUM_AVAILABLE;
2156 else SetLastError( ERROR_NO_MORE_ITEMS );
2158 RtlReleasePebLock();
2163 /**********************************************************************
2164 * TlsFree [KERNEL32.@]
2166 * Releases a thread local storage index, making it available for reuse.
2169 * index [in] TLS index to free.
2175 BOOL WINAPI TlsFree( DWORD index )
2179 RtlAcquirePebLock();
2180 if (index >= TLS_MINIMUM_AVAILABLE)
2182 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2183 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2187 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2188 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2190 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2191 else SetLastError( ERROR_INVALID_PARAMETER );
2192 RtlReleasePebLock();
2197 /**********************************************************************
2198 * TlsGetValue [KERNEL32.@]
2200 * Gets value in a thread's TLS slot.
2203 * index [in] TLS index to retrieve value for.
2206 * Success: Value stored in calling thread's TLS slot for index.
2207 * Failure: 0 and GetLastError() returns NO_ERROR.
2209 LPVOID WINAPI TlsGetValue( DWORD index )
2213 if (index < TLS_MINIMUM_AVAILABLE)
2215 ret = NtCurrentTeb()->TlsSlots[index];
2219 index -= TLS_MINIMUM_AVAILABLE;
2220 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2222 SetLastError( ERROR_INVALID_PARAMETER );
2225 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2226 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2228 SetLastError( ERROR_SUCCESS );
2233 /**********************************************************************
2234 * TlsSetValue [KERNEL32.@]
2236 * Stores a value in the thread's TLS slot.
2239 * index [in] TLS index to set value for.
2240 * value [in] Value to be stored.
2246 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2248 if (index < TLS_MINIMUM_AVAILABLE)
2250 NtCurrentTeb()->TlsSlots[index] = value;
2254 index -= TLS_MINIMUM_AVAILABLE;
2255 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2257 SetLastError( ERROR_INVALID_PARAMETER );
2260 if (!NtCurrentTeb()->TlsExpansionSlots &&
2261 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2262 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2264 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2267 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2273 /***********************************************************************
2274 * GetProcessFlags (KERNEL32.@)
2276 DWORD WINAPI GetProcessFlags( DWORD processid )
2278 IMAGE_NT_HEADERS *nt;
2281 if (processid && processid != GetCurrentProcessId()) return 0;
2283 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2285 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2286 flags |= PDB32_CONSOLE_PROC;
2288 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2289 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2294 /***********************************************************************
2295 * GetProcessDword (KERNEL.485)
2296 * GetProcessDword (KERNEL32.18)
2297 * 'Of course you cannot directly access Windows internal structures'
2299 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2304 TRACE("(%ld, %d)\n", dwProcessID, offset );
2306 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2308 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2314 case GPD_APP_COMPAT_FLAGS:
2315 return GetAppCompatFlags16(0);
2316 case GPD_LOAD_DONE_EVENT:
2318 case GPD_HINSTANCE16:
2319 return GetTaskDS16();
2320 case GPD_WINDOWS_VERSION:
2321 return GetExeVersion16();
2323 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2325 return (DWORD)NtCurrentTeb()->Peb;
2326 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2327 GetStartupInfoW(&siw);
2328 return (DWORD)siw.hStdOutput;
2329 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2330 GetStartupInfoW(&siw);
2331 return (DWORD)siw.hStdInput;
2332 case GPD_STARTF_SHOWWINDOW:
2333 GetStartupInfoW(&siw);
2334 return siw.wShowWindow;
2335 case GPD_STARTF_SIZE:
2336 GetStartupInfoW(&siw);
2338 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2340 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2341 return MAKELONG( x, y );
2342 case GPD_STARTF_POSITION:
2343 GetStartupInfoW(&siw);
2345 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2347 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2348 return MAKELONG( x, y );
2349 case GPD_STARTF_FLAGS:
2350 GetStartupInfoW(&siw);
2355 return GetProcessFlags(0);
2357 return process_dword;
2359 ERR("Unknown offset %d\n", offset );
2364 /***********************************************************************
2365 * SetProcessDword (KERNEL.484)
2366 * 'Of course you cannot directly access Windows internal structures'
2368 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2370 TRACE("(%ld, %d)\n", dwProcessID, offset );
2372 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2374 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2380 case GPD_APP_COMPAT_FLAGS:
2381 case GPD_LOAD_DONE_EVENT:
2382 case GPD_HINSTANCE16:
2383 case GPD_WINDOWS_VERSION:
2386 case GPD_STARTF_SHELLDATA:
2387 case GPD_STARTF_HOTKEY:
2388 case GPD_STARTF_SHOWWINDOW:
2389 case GPD_STARTF_SIZE:
2390 case GPD_STARTF_POSITION:
2391 case GPD_STARTF_FLAGS:
2394 ERR("Not allowed to modify offset %d\n", offset );
2397 process_dword = value;
2400 ERR("Unknown offset %d\n", offset );
2406 /***********************************************************************
2407 * ExitProcess (KERNEL.466)
2409 void WINAPI ExitProcess16( WORD status )
2412 ReleaseThunkLock( &count );
2413 ExitProcess( status );
2417 /*********************************************************************
2418 * OpenProcess (KERNEL32.@)
2420 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2424 OBJECT_ATTRIBUTES attr;
2427 cid.UniqueProcess = (HANDLE)id;
2428 cid.UniqueThread = 0; /* FIXME ? */
2430 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2431 attr.RootDirectory = NULL;
2432 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2433 attr.SecurityDescriptor = NULL;
2434 attr.SecurityQualityOfService = NULL;
2435 attr.ObjectName = NULL;
2437 status = NtOpenProcess(&handle, access, &attr, &cid);
2438 if (status != STATUS_SUCCESS)
2440 SetLastError( RtlNtStatusToDosError(status) );
2447 /*********************************************************************
2448 * MapProcessHandle (KERNEL.483)
2449 * GetProcessId (KERNEL32.@)
2451 DWORD WINAPI GetProcessId( HANDLE hProcess )
2454 PROCESS_BASIC_INFORMATION pbi;
2456 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2458 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2459 SetLastError( RtlNtStatusToDosError(status) );
2464 /*********************************************************************
2465 * CloseW32Handle (KERNEL.474)
2466 * CloseHandle (KERNEL32.@)
2468 BOOL WINAPI CloseHandle( HANDLE handle )
2472 /* stdio handles need special treatment */
2473 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2474 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2475 (handle == (HANDLE)STD_ERROR_HANDLE))
2476 handle = GetStdHandle( (DWORD)handle );
2478 if (is_console_handle(handle))
2479 return CloseConsoleHandle(handle);
2481 status = NtClose( handle );
2482 if (status) SetLastError( RtlNtStatusToDosError(status) );
2487 /*********************************************************************
2488 * GetHandleInformation (KERNEL32.@)
2490 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2492 OBJECT_DATA_INFORMATION info;
2493 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2495 if (status) SetLastError( RtlNtStatusToDosError(status) );
2499 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2500 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2506 /*********************************************************************
2507 * SetHandleInformation (KERNEL32.@)
2509 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2511 OBJECT_DATA_INFORMATION info;
2514 /* if not setting both fields, retrieve current value first */
2515 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2516 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2518 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2520 SetLastError( RtlNtStatusToDosError(status) );
2524 if (mask & HANDLE_FLAG_INHERIT)
2525 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2526 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2527 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2529 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2530 if (status) SetLastError( RtlNtStatusToDosError(status) );
2535 /*********************************************************************
2536 * DuplicateHandle (KERNEL32.@)
2538 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2539 HANDLE dest_process, HANDLE *dest,
2540 DWORD access, BOOL inherit, DWORD options )
2544 if (is_console_handle(source))
2546 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2547 if (source_process != dest_process ||
2548 source_process != GetCurrentProcess())
2550 SetLastError(ERROR_INVALID_PARAMETER);
2553 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2554 return (*dest != INVALID_HANDLE_VALUE);
2556 status = NtDuplicateObject( source_process, source, dest_process, dest,
2557 access, inherit ? OBJ_INHERIT : 0, options );
2558 if (status) SetLastError( RtlNtStatusToDosError(status) );
2563 /***********************************************************************
2564 * ConvertToGlobalHandle (KERNEL.476)
2565 * ConvertToGlobalHandle (KERNEL32.@)
2567 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2569 HANDLE ret = INVALID_HANDLE_VALUE;
2570 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2571 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2576 /***********************************************************************
2577 * SetHandleContext (KERNEL32.@)
2579 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2581 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2582 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2583 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2588 /***********************************************************************
2589 * GetHandleContext (KERNEL32.@)
2591 DWORD WINAPI GetHandleContext(HANDLE hnd)
2593 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2594 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2595 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2600 /***********************************************************************
2601 * CreateSocketHandle (KERNEL32.@)
2603 HANDLE WINAPI CreateSocketHandle(void)
2605 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2606 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2607 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2608 return INVALID_HANDLE_VALUE;
2612 /***********************************************************************
2613 * SetPriorityClass (KERNEL32.@)
2615 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2618 PROCESS_PRIORITY_CLASS ppc;
2620 ppc.Foreground = FALSE;
2621 switch (priorityclass)
2623 case IDLE_PRIORITY_CLASS:
2624 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2625 case BELOW_NORMAL_PRIORITY_CLASS:
2626 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2627 case NORMAL_PRIORITY_CLASS:
2628 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2629 case ABOVE_NORMAL_PRIORITY_CLASS:
2630 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2631 case HIGH_PRIORITY_CLASS:
2632 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2633 case REALTIME_PRIORITY_CLASS:
2634 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2636 SetLastError(ERROR_INVALID_PARAMETER);
2640 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2643 if (status != STATUS_SUCCESS)
2645 SetLastError( RtlNtStatusToDosError(status) );
2652 /***********************************************************************
2653 * GetPriorityClass (KERNEL32.@)
2655 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2658 PROCESS_BASIC_INFORMATION pbi;
2660 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2662 if (status != STATUS_SUCCESS)
2664 SetLastError( RtlNtStatusToDosError(status) );
2667 switch (pbi.BasePriority)
2669 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2670 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2671 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2672 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2673 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2674 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2676 SetLastError( ERROR_INVALID_PARAMETER );
2681 /***********************************************************************
2682 * SetProcessAffinityMask (KERNEL32.@)
2684 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2688 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2689 &affmask, sizeof(DWORD_PTR));
2692 SetLastError( RtlNtStatusToDosError(status) );
2699 /**********************************************************************
2700 * GetProcessAffinityMask (KERNEL32.@)
2702 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2703 PDWORD_PTR lpProcessAffinityMask,
2704 PDWORD_PTR lpSystemAffinityMask )
2706 PROCESS_BASIC_INFORMATION pbi;
2709 status = NtQueryInformationProcess(hProcess,
2710 ProcessBasicInformation,
2711 &pbi, sizeof(pbi), NULL);
2714 SetLastError( RtlNtStatusToDosError(status) );
2717 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2719 if (lpSystemAffinityMask) *lpSystemAffinityMask = 1;
2724 /***********************************************************************
2725 * GetProcessVersion (KERNEL32.@)
2727 DWORD WINAPI GetProcessVersion( DWORD processid )
2729 IMAGE_NT_HEADERS *nt;
2731 if (processid && processid != GetCurrentProcessId())
2733 FIXME("should use ReadProcessMemory\n");
2736 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2737 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2738 nt->OptionalHeader.MinorSubsystemVersion);
2743 /***********************************************************************
2744 * SetProcessWorkingSetSize [KERNEL32.@]
2745 * Sets the min/max working set sizes for a specified process.
2748 * hProcess [I] Handle to the process of interest
2749 * minset [I] Specifies minimum working set size
2750 * maxset [I] Specifies maximum working set size
2756 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2759 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2760 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2761 /* Trim the working set to zero */
2762 /* Swap the process out of physical RAM */
2767 /***********************************************************************
2768 * GetProcessWorkingSetSize (KERNEL32.@)
2770 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2773 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2774 /* 32 MB working set size */
2775 if (minset) *minset = 32*1024*1024;
2776 if (maxset) *maxset = 32*1024*1024;
2781 /***********************************************************************
2782 * SetProcessShutdownParameters (KERNEL32.@)
2784 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2786 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2787 shutdown_flags = flags;
2788 shutdown_priority = level;
2793 /***********************************************************************
2794 * GetProcessShutdownParameters (KERNEL32.@)
2797 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2799 *lpdwLevel = shutdown_priority;
2800 *lpdwFlags = shutdown_flags;
2805 /***********************************************************************
2806 * GetProcessPriorityBoost (KERNEL32.@)
2808 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2810 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2812 /* Report that no boost is present.. */
2813 *pDisablePriorityBoost = FALSE;
2818 /***********************************************************************
2819 * SetProcessPriorityBoost (KERNEL32.@)
2821 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2823 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2824 /* Say we can do it. I doubt the program will notice that we don't. */
2829 /***********************************************************************
2830 * ReadProcessMemory (KERNEL32.@)
2832 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2833 SIZE_T *bytes_read )
2835 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2836 if (status) SetLastError( RtlNtStatusToDosError(status) );
2841 /***********************************************************************
2842 * WriteProcessMemory (KERNEL32.@)
2844 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2845 SIZE_T *bytes_written )
2847 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2848 if (status) SetLastError( RtlNtStatusToDosError(status) );
2853 /****************************************************************************
2854 * FlushInstructionCache (KERNEL32.@)
2856 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2859 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2860 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2861 if (status) SetLastError( RtlNtStatusToDosError(status) );
2866 /******************************************************************
2867 * GetProcessIoCounters (KERNEL32.@)
2869 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2873 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2874 ioc, sizeof(*ioc), NULL);
2875 if (status) SetLastError( RtlNtStatusToDosError(status) );
2879 /***********************************************************************
2880 * ProcessIdToSessionId (KERNEL32.@)
2881 * This function is available on Terminal Server 4SP4 and Windows 2000
2883 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2885 /* According to MSDN, if the calling process is not in a terminal
2886 * services environment, then the sessionid returned is zero.
2893 /***********************************************************************
2894 * RegisterServiceProcess (KERNEL.491)
2895 * RegisterServiceProcess (KERNEL32.@)
2897 * A service process calls this function to ensure that it continues to run
2898 * even after a user logged off.
2900 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2902 /* I don't think that Wine needs to do anything in this function */
2903 return 1; /* success */
2907 /***********************************************************************
2908 * GetCurrentProcess (KERNEL32.@)
2910 * Get a handle to the current process.
2916 * A handle representing the current process.
2918 #undef GetCurrentProcess
2919 HANDLE WINAPI GetCurrentProcess(void)
2921 return (HANDLE)0xffffffff;