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);
1484 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1487 write( execfd[1], &err, sizeof(err) );
1491 /* this is the parent */
1493 close( startfd[0] );
1495 HeapFree( GetProcessHeap(), 0, winedebug );
1498 if (!env) RtlReleasePebLock();
1499 close( startfd[1] );
1502 RtlDestroyProcessParameters( params );
1506 /* create the process on the server side */
1508 SERVER_START_REQ( new_process )
1510 req->inherit_all = inherit;
1511 req->create_flags = flags;
1512 req->unix_pid = pid;
1513 req->exe_file = hFile;
1514 if (startup->dwFlags & STARTF_USESTDHANDLES)
1516 req->hstdin = startup->hStdInput;
1517 req->hstdout = startup->hStdOutput;
1518 req->hstderr = startup->hStdError;
1522 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1523 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1524 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1527 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1529 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1530 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1531 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1532 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1536 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1537 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1538 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1541 wine_server_add_data( req, params, params->Size );
1542 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1543 ret = !wine_server_call_err( req );
1544 process_info = reply->info;
1548 if (!env) RtlReleasePebLock();
1549 RtlDestroyProcessParameters( params );
1552 close( startfd[1] );
1557 /* tell child to start and wait for it to exec */
1559 write( startfd[1], &dummy, 1 );
1560 close( startfd[1] );
1562 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1567 CloseHandle( process_info );
1572 /* wait for the new process info to be ready */
1574 WaitForSingleObject( process_info, INFINITE );
1575 SERVER_START_REQ( get_new_process_info )
1577 req->info = process_info;
1578 req->process_access = PROCESS_ALL_ACCESS;
1579 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1580 req->thread_access = THREAD_ALL_ACCESS;
1581 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1582 if ((ret = !wine_server_call_err( req )))
1584 info->dwProcessId = (DWORD)reply->pid;
1585 info->dwThreadId = (DWORD)reply->tid;
1586 info->hProcess = reply->phandle;
1587 info->hThread = reply->thandle;
1588 success = reply->success;
1593 if (ret && !success) /* new process failed to start */
1596 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1597 CloseHandle( info->hThread );
1598 CloseHandle( info->hProcess );
1601 CloseHandle( process_info );
1606 /***********************************************************************
1607 * create_vdm_process
1609 * Create a new VDM process for a 16-bit or DOS application.
1611 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1612 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1613 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1614 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1616 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1619 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1620 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1624 SetLastError( ERROR_OUTOFMEMORY );
1627 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1628 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1629 flags, startup, info, unixdir, NULL, NULL );
1630 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1635 /***********************************************************************
1636 * create_cmd_process
1638 * Create a new cmd shell process for a .BAT file.
1640 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1641 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1642 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1643 LPPROCESS_INFORMATION info )
1646 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1647 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1648 WCHAR comspec[MAX_PATH];
1652 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1654 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1655 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1658 strcpyW( newcmdline, comspec );
1659 strcatW( newcmdline, slashcW );
1660 strcatW( newcmdline, cmd_line );
1661 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1662 flags, env, cur_dir, startup, info );
1663 HeapFree( GetProcessHeap(), 0, newcmdline );
1668 /*************************************************************************
1671 * Helper for CreateProcess: retrieve the file name to load from the
1672 * app name and command line. Store the file name in buffer, and
1673 * return a possibly modified command line.
1674 * Also returns a handle to the opened file if it's a Windows binary.
1676 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1677 int buflen, HANDLE *handle )
1679 static const WCHAR quotesW[] = {'"','%','s','"',0};
1681 WCHAR *name, *pos, *ret = NULL;
1685 /* if we have an app name, everything is easy */
1689 /* use the unmodified app name as file name */
1690 lstrcpynW( buffer, appname, buflen );
1691 *handle = open_exe_file( buffer );
1692 if (!(ret = cmdline) || !cmdline[0])
1694 /* no command-line, create one */
1695 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1696 sprintfW( ret, quotesW, appname );
1703 SetLastError( ERROR_INVALID_PARAMETER );
1707 /* first check for a quoted file name */
1709 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1711 int len = p - cmdline - 1;
1712 /* extract the quoted portion as file name */
1713 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1714 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1717 if (find_exe_file( name, buffer, buflen, handle ))
1718 ret = cmdline; /* no change necessary */
1722 /* now try the command-line word by word */
1724 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1732 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1734 if (find_exe_file( name, buffer, buflen, handle ))
1739 if (*p) got_space = TRUE;
1742 if (ret && got_space) /* now build a new command-line with quotes */
1744 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1746 sprintfW( ret, quotesW, name );
1751 HeapFree( GetProcessHeap(), 0, name );
1756 /**********************************************************************
1757 * CreateProcessA (KERNEL32.@)
1759 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1760 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1761 DWORD flags, LPVOID env, LPCSTR cur_dir,
1762 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1765 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1766 UNICODE_STRING desktopW, titleW;
1769 desktopW.Buffer = NULL;
1770 titleW.Buffer = NULL;
1771 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1772 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1773 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1775 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1776 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1778 memcpy( &infoW, startup_info, sizeof(infoW) );
1779 infoW.lpDesktop = desktopW.Buffer;
1780 infoW.lpTitle = titleW.Buffer;
1782 if (startup_info->lpReserved)
1783 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1784 debugstr_a(startup_info->lpReserved));
1786 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1787 inherit, flags, env, cur_dirW, &infoW, info );
1789 HeapFree( GetProcessHeap(), 0, app_nameW );
1790 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1791 HeapFree( GetProcessHeap(), 0, cur_dirW );
1792 RtlFreeUnicodeString( &desktopW );
1793 RtlFreeUnicodeString( &titleW );
1798 /**********************************************************************
1799 * CreateProcessW (KERNEL32.@)
1801 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1802 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1803 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1804 LPPROCESS_INFORMATION info )
1808 char *unixdir = NULL;
1809 WCHAR name[MAX_PATH];
1810 WCHAR *tidy_cmdline, *p, *envW = env;
1811 void *res_start, *res_end;
1813 /* Process the AppName and/or CmdLine to get module name and path */
1815 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1817 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1819 if (hFile == INVALID_HANDLE_VALUE) goto done;
1821 /* Warn if unsupported features are used */
1823 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1824 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1825 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1826 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1827 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1831 unixdir = wine_get_unix_file_name( cur_dir );
1835 WCHAR buf[MAX_PATH];
1836 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1839 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1844 while (*p) p += strlen(p) + 1;
1845 p++; /* final null */
1846 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1847 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1848 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1849 flags |= CREATE_UNICODE_ENVIRONMENT;
1852 info->hThread = info->hProcess = 0;
1853 info->dwProcessId = info->dwThreadId = 0;
1855 /* Determine executable type */
1857 if (!hFile) /* builtin exe */
1859 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1860 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1861 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1865 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1868 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1869 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1870 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1875 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1876 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1877 inherit, flags, startup_info, info, unixdir );
1880 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1881 SetLastError( ERROR_BAD_EXE_FORMAT );
1883 case BINARY_UNIX_LIB:
1884 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1885 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1886 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1888 case BINARY_UNKNOWN:
1889 /* check for .com or .bat extension */
1890 if ((p = strrchrW( name, '.' )))
1892 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1894 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1895 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1896 inherit, flags, startup_info, info, unixdir );
1899 if (!strcmpiW( p, batW ))
1901 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1902 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1903 inherit, flags, startup_info, info );
1908 case BINARY_UNIX_EXE:
1910 /* unknown file, try as unix executable */
1913 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1915 if ((unix_name = wine_get_unix_file_name( name )))
1917 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1918 HeapFree( GetProcessHeap(), 0, unix_name );
1923 CloseHandle( hFile );
1926 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1927 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1928 HeapFree( GetProcessHeap(), 0, unixdir );
1933 /***********************************************************************
1936 * Wrapper to call WaitForInputIdle USER function
1938 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1940 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1942 HMODULE mod = GetModuleHandleA( "user32.dll" );
1945 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1946 if (ptr) return ptr( process, timeout );
1952 /***********************************************************************
1953 * WinExec (KERNEL32.@)
1955 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1957 PROCESS_INFORMATION info;
1958 STARTUPINFOA startup;
1962 memset( &startup, 0, sizeof(startup) );
1963 startup.cb = sizeof(startup);
1964 startup.dwFlags = STARTF_USESHOWWINDOW;
1965 startup.wShowWindow = nCmdShow;
1967 /* cmdline needs to be writeable for CreateProcess */
1968 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1969 strcpy( cmdline, lpCmdLine );
1971 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1972 0, NULL, NULL, &startup, &info ))
1974 /* Give 30 seconds to the app to come up */
1975 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1976 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1978 /* Close off the handles */
1979 CloseHandle( info.hThread );
1980 CloseHandle( info.hProcess );
1982 else if ((ret = GetLastError()) >= 32)
1984 FIXME("Strange error set by CreateProcess: %d\n", ret );
1987 HeapFree( GetProcessHeap(), 0, cmdline );
1992 /**********************************************************************
1993 * LoadModule (KERNEL32.@)
1995 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1997 LOADPARMS32 *params = paramBlock;
1998 PROCESS_INFORMATION info;
1999 STARTUPINFOA startup;
2000 HINSTANCE hInstance;
2002 char filename[MAX_PATH];
2005 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2007 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2008 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2009 return (HINSTANCE)GetLastError();
2011 len = (BYTE)params->lpCmdLine[0];
2012 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2013 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2015 strcpy( cmdline, filename );
2016 p = cmdline + strlen(cmdline);
2018 memcpy( p, params->lpCmdLine + 1, len );
2021 memset( &startup, 0, sizeof(startup) );
2022 startup.cb = sizeof(startup);
2023 if (params->lpCmdShow)
2025 startup.dwFlags = STARTF_USESHOWWINDOW;
2026 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2029 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2030 params->lpEnvAddress, NULL, &startup, &info ))
2032 /* Give 30 seconds to the app to come up */
2033 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2034 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2035 hInstance = (HINSTANCE)33;
2036 /* Close off the handles */
2037 CloseHandle( info.hThread );
2038 CloseHandle( info.hProcess );
2040 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2042 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2043 hInstance = (HINSTANCE)11;
2046 HeapFree( GetProcessHeap(), 0, cmdline );
2051 /******************************************************************************
2052 * TerminateProcess (KERNEL32.@)
2054 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2056 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2057 if (status) SetLastError( RtlNtStatusToDosError(status) );
2062 /***********************************************************************
2063 * ExitProcess (KERNEL32.@)
2065 void WINAPI ExitProcess( DWORD status )
2067 LdrShutdownProcess();
2068 NtTerminateProcess(GetCurrentProcess(), status);
2073 /***********************************************************************
2074 * GetExitCodeProcess [KERNEL32.@]
2076 * Gets termination status of specified process.
2079 * hProcess [in] Handle to the process.
2080 * lpExitCode [out] Address to receive termination status.
2086 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2089 PROCESS_BASIC_INFORMATION pbi;
2091 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2093 if (status == STATUS_SUCCESS)
2095 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2098 SetLastError( RtlNtStatusToDosError(status) );
2103 /***********************************************************************
2104 * SetErrorMode (KERNEL32.@)
2106 UINT WINAPI SetErrorMode( UINT mode )
2108 UINT old = process_error_mode;
2109 process_error_mode = mode;
2114 /**********************************************************************
2115 * TlsAlloc [KERNEL32.@]
2117 * Allocates a thread local storage index.
2120 * Success: TLS index.
2121 * Failure: 0xFFFFFFFF
2123 DWORD WINAPI TlsAlloc( void )
2126 PEB * const peb = NtCurrentTeb()->Peb;
2128 RtlAcquirePebLock();
2129 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2130 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2133 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2136 if (!NtCurrentTeb()->TlsExpansionSlots &&
2137 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2138 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2140 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2142 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2146 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2147 index += TLS_MINIMUM_AVAILABLE;
2150 else SetLastError( ERROR_NO_MORE_ITEMS );
2152 RtlReleasePebLock();
2157 /**********************************************************************
2158 * TlsFree [KERNEL32.@]
2160 * Releases a thread local storage index, making it available for reuse.
2163 * index [in] TLS index to free.
2169 BOOL WINAPI TlsFree( DWORD index )
2173 RtlAcquirePebLock();
2174 if (index >= TLS_MINIMUM_AVAILABLE)
2176 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2177 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2181 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2182 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2184 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2185 else SetLastError( ERROR_INVALID_PARAMETER );
2186 RtlReleasePebLock();
2191 /**********************************************************************
2192 * TlsGetValue [KERNEL32.@]
2194 * Gets value in a thread's TLS slot.
2197 * index [in] TLS index to retrieve value for.
2200 * Success: Value stored in calling thread's TLS slot for index.
2201 * Failure: 0 and GetLastError() returns NO_ERROR.
2203 LPVOID WINAPI TlsGetValue( DWORD index )
2207 if (index < TLS_MINIMUM_AVAILABLE)
2209 ret = NtCurrentTeb()->TlsSlots[index];
2213 index -= TLS_MINIMUM_AVAILABLE;
2214 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2216 SetLastError( ERROR_INVALID_PARAMETER );
2219 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2220 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2222 SetLastError( ERROR_SUCCESS );
2227 /**********************************************************************
2228 * TlsSetValue [KERNEL32.@]
2230 * Stores a value in the thread's TLS slot.
2233 * index [in] TLS index to set value for.
2234 * value [in] Value to be stored.
2240 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2242 if (index < TLS_MINIMUM_AVAILABLE)
2244 NtCurrentTeb()->TlsSlots[index] = value;
2248 index -= TLS_MINIMUM_AVAILABLE;
2249 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2251 SetLastError( ERROR_INVALID_PARAMETER );
2254 if (!NtCurrentTeb()->TlsExpansionSlots &&
2255 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2256 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2258 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2261 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2267 /***********************************************************************
2268 * GetProcessFlags (KERNEL32.@)
2270 DWORD WINAPI GetProcessFlags( DWORD processid )
2272 IMAGE_NT_HEADERS *nt;
2275 if (processid && processid != GetCurrentProcessId()) return 0;
2277 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2279 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2280 flags |= PDB32_CONSOLE_PROC;
2282 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2283 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2288 /***********************************************************************
2289 * GetProcessDword (KERNEL.485)
2290 * GetProcessDword (KERNEL32.18)
2291 * 'Of course you cannot directly access Windows internal structures'
2293 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2298 TRACE("(%ld, %d)\n", dwProcessID, offset );
2300 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2302 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2308 case GPD_APP_COMPAT_FLAGS:
2309 return GetAppCompatFlags16(0);
2310 case GPD_LOAD_DONE_EVENT:
2312 case GPD_HINSTANCE16:
2313 return GetTaskDS16();
2314 case GPD_WINDOWS_VERSION:
2315 return GetExeVersion16();
2317 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2319 return (DWORD)NtCurrentTeb()->Peb;
2320 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2321 GetStartupInfoW(&siw);
2322 return (DWORD)siw.hStdOutput;
2323 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2324 GetStartupInfoW(&siw);
2325 return (DWORD)siw.hStdInput;
2326 case GPD_STARTF_SHOWWINDOW:
2327 GetStartupInfoW(&siw);
2328 return siw.wShowWindow;
2329 case GPD_STARTF_SIZE:
2330 GetStartupInfoW(&siw);
2332 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2334 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2335 return MAKELONG( x, y );
2336 case GPD_STARTF_POSITION:
2337 GetStartupInfoW(&siw);
2339 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2341 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2342 return MAKELONG( x, y );
2343 case GPD_STARTF_FLAGS:
2344 GetStartupInfoW(&siw);
2349 return GetProcessFlags(0);
2351 return process_dword;
2353 ERR("Unknown offset %d\n", offset );
2358 /***********************************************************************
2359 * SetProcessDword (KERNEL.484)
2360 * 'Of course you cannot directly access Windows internal structures'
2362 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2364 TRACE("(%ld, %d)\n", dwProcessID, offset );
2366 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2368 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2374 case GPD_APP_COMPAT_FLAGS:
2375 case GPD_LOAD_DONE_EVENT:
2376 case GPD_HINSTANCE16:
2377 case GPD_WINDOWS_VERSION:
2380 case GPD_STARTF_SHELLDATA:
2381 case GPD_STARTF_HOTKEY:
2382 case GPD_STARTF_SHOWWINDOW:
2383 case GPD_STARTF_SIZE:
2384 case GPD_STARTF_POSITION:
2385 case GPD_STARTF_FLAGS:
2388 ERR("Not allowed to modify offset %d\n", offset );
2391 process_dword = value;
2394 ERR("Unknown offset %d\n", offset );
2400 /***********************************************************************
2401 * ExitProcess (KERNEL.466)
2403 void WINAPI ExitProcess16( WORD status )
2406 ReleaseThunkLock( &count );
2407 ExitProcess( status );
2411 /*********************************************************************
2412 * OpenProcess (KERNEL32.@)
2414 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2418 OBJECT_ATTRIBUTES attr;
2421 cid.UniqueProcess = (HANDLE)id;
2422 cid.UniqueThread = 0; /* FIXME ? */
2424 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2425 attr.RootDirectory = NULL;
2426 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2427 attr.SecurityDescriptor = NULL;
2428 attr.SecurityQualityOfService = NULL;
2429 attr.ObjectName = NULL;
2431 status = NtOpenProcess(&handle, access, &attr, &cid);
2432 if (status != STATUS_SUCCESS)
2434 SetLastError( RtlNtStatusToDosError(status) );
2441 /*********************************************************************
2442 * MapProcessHandle (KERNEL.483)
2443 * GetProcessId (KERNEL32.@)
2445 DWORD WINAPI GetProcessId( HANDLE hProcess )
2448 PROCESS_BASIC_INFORMATION pbi;
2450 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2452 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2453 SetLastError( RtlNtStatusToDosError(status) );
2458 /*********************************************************************
2459 * CloseW32Handle (KERNEL.474)
2460 * CloseHandle (KERNEL32.@)
2462 BOOL WINAPI CloseHandle( HANDLE handle )
2466 /* stdio handles need special treatment */
2467 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2468 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2469 (handle == (HANDLE)STD_ERROR_HANDLE))
2470 handle = GetStdHandle( (DWORD)handle );
2472 if (is_console_handle(handle))
2473 return CloseConsoleHandle(handle);
2475 status = NtClose( handle );
2476 if (status) SetLastError( RtlNtStatusToDosError(status) );
2481 /*********************************************************************
2482 * GetHandleInformation (KERNEL32.@)
2484 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2486 OBJECT_DATA_INFORMATION info;
2487 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2489 if (status) SetLastError( RtlNtStatusToDosError(status) );
2493 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2494 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2500 /*********************************************************************
2501 * SetHandleInformation (KERNEL32.@)
2503 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2505 OBJECT_DATA_INFORMATION info;
2508 /* if not setting both fields, retrieve current value first */
2509 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2510 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2512 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2514 SetLastError( RtlNtStatusToDosError(status) );
2518 if (mask & HANDLE_FLAG_INHERIT)
2519 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2520 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2521 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2523 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2524 if (status) SetLastError( RtlNtStatusToDosError(status) );
2529 /*********************************************************************
2530 * DuplicateHandle (KERNEL32.@)
2532 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2533 HANDLE dest_process, HANDLE *dest,
2534 DWORD access, BOOL inherit, DWORD options )
2538 if (is_console_handle(source))
2540 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2541 if (source_process != dest_process ||
2542 source_process != GetCurrentProcess())
2544 SetLastError(ERROR_INVALID_PARAMETER);
2547 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2548 return (*dest != INVALID_HANDLE_VALUE);
2550 status = NtDuplicateObject( source_process, source, dest_process, dest,
2551 access, inherit ? OBJ_INHERIT : 0, options );
2552 if (status) SetLastError( RtlNtStatusToDosError(status) );
2557 /***********************************************************************
2558 * ConvertToGlobalHandle (KERNEL.476)
2559 * ConvertToGlobalHandle (KERNEL32.@)
2561 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2563 HANDLE ret = INVALID_HANDLE_VALUE;
2564 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2565 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2570 /***********************************************************************
2571 * SetHandleContext (KERNEL32.@)
2573 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2575 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2576 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2577 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2582 /***********************************************************************
2583 * GetHandleContext (KERNEL32.@)
2585 DWORD WINAPI GetHandleContext(HANDLE hnd)
2587 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2588 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2589 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2594 /***********************************************************************
2595 * CreateSocketHandle (KERNEL32.@)
2597 HANDLE WINAPI CreateSocketHandle(void)
2599 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2600 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2601 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2602 return INVALID_HANDLE_VALUE;
2606 /***********************************************************************
2607 * SetPriorityClass (KERNEL32.@)
2609 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2612 PROCESS_PRIORITY_CLASS ppc;
2614 ppc.Foreground = FALSE;
2615 switch (priorityclass)
2617 case IDLE_PRIORITY_CLASS:
2618 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2619 case BELOW_NORMAL_PRIORITY_CLASS:
2620 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2621 case NORMAL_PRIORITY_CLASS:
2622 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2623 case ABOVE_NORMAL_PRIORITY_CLASS:
2624 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2625 case HIGH_PRIORITY_CLASS:
2626 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2627 case REALTIME_PRIORITY_CLASS:
2628 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2630 SetLastError(ERROR_INVALID_PARAMETER);
2634 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2637 if (status != STATUS_SUCCESS)
2639 SetLastError( RtlNtStatusToDosError(status) );
2646 /***********************************************************************
2647 * GetPriorityClass (KERNEL32.@)
2649 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2652 PROCESS_BASIC_INFORMATION pbi;
2654 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2656 if (status != STATUS_SUCCESS)
2658 SetLastError( RtlNtStatusToDosError(status) );
2661 switch (pbi.BasePriority)
2663 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2664 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2665 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2666 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2667 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2668 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2670 SetLastError( ERROR_INVALID_PARAMETER );
2675 /***********************************************************************
2676 * SetProcessAffinityMask (KERNEL32.@)
2678 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2682 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2683 &affmask, sizeof(DWORD_PTR));
2686 SetLastError( RtlNtStatusToDosError(status) );
2693 /**********************************************************************
2694 * GetProcessAffinityMask (KERNEL32.@)
2696 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2697 PDWORD_PTR lpProcessAffinityMask,
2698 PDWORD_PTR lpSystemAffinityMask )
2700 PROCESS_BASIC_INFORMATION pbi;
2703 status = NtQueryInformationProcess(hProcess,
2704 ProcessBasicInformation,
2705 &pbi, sizeof(pbi), NULL);
2708 SetLastError( RtlNtStatusToDosError(status) );
2711 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2713 if (lpSystemAffinityMask) *lpSystemAffinityMask = 1;
2718 /***********************************************************************
2719 * GetProcessVersion (KERNEL32.@)
2721 DWORD WINAPI GetProcessVersion( DWORD processid )
2723 IMAGE_NT_HEADERS *nt;
2725 if (processid && processid != GetCurrentProcessId())
2727 FIXME("should use ReadProcessMemory\n");
2730 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2731 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2732 nt->OptionalHeader.MinorSubsystemVersion);
2737 /***********************************************************************
2738 * SetProcessWorkingSetSize [KERNEL32.@]
2739 * Sets the min/max working set sizes for a specified process.
2742 * hProcess [I] Handle to the process of interest
2743 * minset [I] Specifies minimum working set size
2744 * maxset [I] Specifies maximum working set size
2750 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2753 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2754 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2755 /* Trim the working set to zero */
2756 /* Swap the process out of physical RAM */
2761 /***********************************************************************
2762 * GetProcessWorkingSetSize (KERNEL32.@)
2764 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2767 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2768 /* 32 MB working set size */
2769 if (minset) *minset = 32*1024*1024;
2770 if (maxset) *maxset = 32*1024*1024;
2775 /***********************************************************************
2776 * SetProcessShutdownParameters (KERNEL32.@)
2778 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2780 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2781 shutdown_flags = flags;
2782 shutdown_priority = level;
2787 /***********************************************************************
2788 * GetProcessShutdownParameters (KERNEL32.@)
2791 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2793 *lpdwLevel = shutdown_priority;
2794 *lpdwFlags = shutdown_flags;
2799 /***********************************************************************
2800 * GetProcessPriorityBoost (KERNEL32.@)
2802 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2804 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2806 /* Report that no boost is present.. */
2807 *pDisablePriorityBoost = FALSE;
2812 /***********************************************************************
2813 * SetProcessPriorityBoost (KERNEL32.@)
2815 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2817 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2818 /* Say we can do it. I doubt the program will notice that we don't. */
2823 /***********************************************************************
2824 * ReadProcessMemory (KERNEL32.@)
2826 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2827 SIZE_T *bytes_read )
2829 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2830 if (status) SetLastError( RtlNtStatusToDosError(status) );
2835 /***********************************************************************
2836 * WriteProcessMemory (KERNEL32.@)
2838 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2839 SIZE_T *bytes_written )
2841 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2842 if (status) SetLastError( RtlNtStatusToDosError(status) );
2847 /****************************************************************************
2848 * FlushInstructionCache (KERNEL32.@)
2850 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2853 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2854 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2855 if (status) SetLastError( RtlNtStatusToDosError(status) );
2860 /******************************************************************
2861 * GetProcessIoCounters (KERNEL32.@)
2863 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2867 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2868 ioc, sizeof(*ioc), NULL);
2869 if (status) SetLastError( RtlNtStatusToDosError(status) );
2873 /***********************************************************************
2874 * ProcessIdToSessionId (KERNEL32.@)
2875 * This function is available on Terminal Server 4SP4 and Windows 2000
2877 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2879 /* According to MSDN, if the calling process is not in a terminal
2880 * services environment, then the sessionid returned is zero.
2887 /***********************************************************************
2888 * RegisterServiceProcess (KERNEL.491)
2889 * RegisterServiceProcess (KERNEL32.@)
2891 * A service process calls this function to ensure that it continues to run
2892 * even after a user logged off.
2894 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2896 /* I don't think that Wine needs to do anything in this function */
2897 return 1; /* success */
2901 /***********************************************************************
2902 * GetCurrentProcess (KERNEL32.@)
2904 * Get a handle to the current process.
2910 * A handle representing the current process.
2912 #undef GetCurrentProcess
2913 HANDLE WINAPI GetCurrentProcess(void)
2915 return (HANDLE)0xffffffff;