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 WINE_DEFAULT_DEBUG_CHANNEL(process);
50 WINE_DECLARE_DEBUG_CHANNEL(file);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
61 static UINT process_error_mode;
63 static HANDLE main_exe_file;
64 static DWORD shutdown_flags = 0;
65 static DWORD shutdown_priority = 0x280;
66 static DWORD process_dword;
68 int main_create_flags = 0;
69 HMODULE kernel32_handle = 0;
71 const WCHAR *DIR_Windows = NULL;
72 const WCHAR *DIR_System = NULL;
75 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
76 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
77 #define PDB32_DOS_PROC 0x0010 /* Dos process */
78 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
79 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
80 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
82 static const WCHAR comW[] = {'.','c','o','m',0};
83 static const WCHAR batW[] = {'.','b','a','t',0};
84 static const WCHAR pifW[] = {'.','p','i','f',0};
85 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
87 extern void SHELL_LoadRegistry(void);
90 /***********************************************************************
93 inline static int contains_path( LPCWSTR name )
95 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
99 /***********************************************************************
102 * Check if an environment variable needs to be handled specially when
103 * passed through the Unix environment (i.e. prefixed with "WINE").
105 inline static int is_special_env_var( const char *var )
107 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
108 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
109 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
110 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
114 /***************************************************************************
117 * Get the path of a builtin module when the native file does not exist.
119 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
122 UINT len = strlenW( DIR_System );
124 if (contains_path( libname ))
126 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
127 filename, &file_part ) > size * sizeof(WCHAR))
128 return FALSE; /* too long */
130 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
132 while (filename[len] == '\\') len++;
133 if (filename + len != file_part) return FALSE;
137 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
138 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
139 file_part = filename + len;
140 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
141 strcpyW( file_part, libname );
143 if (ext && !strchrW( file_part, '.' ))
145 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
146 return FALSE; /* too long */
147 strcatW( file_part, ext );
153 /***********************************************************************
154 * open_builtin_exe_file
156 * Open an exe file for a builtin exe.
158 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
159 int test_only, int *file_exists )
161 char exename[MAX_PATH];
166 if ((p = strrchrW( name, '/' ))) name = p + 1;
167 if ((p = strrchrW( name, '\\' ))) name = p + 1;
169 /* we don't want to depend on the current codepage here */
170 len = strlenW( name ) + 1;
171 if (len >= sizeof(exename)) return NULL;
172 for (i = 0; i < len; i++)
174 if (name[i] > 127) return NULL;
175 exename[i] = (char)name[i];
176 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
178 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
182 /***********************************************************************
185 * Open a specific exe file, taking load order into account.
186 * Returns the file handle or 0 for a builtin exe.
188 static HANDLE open_exe_file( const WCHAR *name )
190 enum loadorder_type loadorder[LOADORDER_NTYPES];
191 WCHAR buffer[MAX_PATH];
195 TRACE("looking for %s\n", debugstr_w(name) );
197 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
198 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
200 /* file doesn't exist, check for builtin */
201 if (!contains_path( name )) goto error;
202 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
206 MODULE_GetLoadOrderW( loadorder, NULL, name );
208 for(i = 0; i < LOADORDER_NTYPES; i++)
210 if (loadorder[i] == LOADORDER_INVALID) break;
214 TRACE( "Trying native exe %s\n", debugstr_w(name) );
215 if (handle != INVALID_HANDLE_VALUE) return handle;
218 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
219 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
222 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
229 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
232 SetLastError( ERROR_FILE_NOT_FOUND );
233 return INVALID_HANDLE_VALUE;
237 /***********************************************************************
240 * Open an exe file, and return the full name and file handle.
241 * Returns FALSE if file could not be found.
242 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
243 * If file is a builtin exe, returns TRUE and sets handle to 0.
245 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
247 static const WCHAR exeW[] = {'.','e','x','e',0};
249 enum loadorder_type loadorder[LOADORDER_NTYPES];
252 TRACE("looking for %s\n", debugstr_w(name) );
254 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
255 !get_builtin_path( name, exeW, buffer, buflen ))
257 /* no builtin found, try native without extension in case it is a Unix app */
259 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
261 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
262 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
263 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
269 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
271 for(i = 0; i < LOADORDER_NTYPES; i++)
273 if (loadorder[i] == LOADORDER_INVALID) break;
277 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
278 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
279 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
281 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
284 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
285 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
296 SetLastError( ERROR_FILE_NOT_FOUND );
301 /**********************************************************************
304 * Load a PE format EXE file.
306 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
309 FILE_FS_DEVICE_INFORMATION device_info;
310 IMAGE_NT_HEADERS *nt;
313 OBJECT_ATTRIBUTES attr;
317 attr.Length = sizeof(attr);
318 attr.RootDirectory = 0;
319 attr.ObjectName = NULL;
321 attr.SecurityDescriptor = NULL;
322 attr.SecurityQualityOfService = NULL;
325 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
326 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
330 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
331 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
337 nt = RtlImageNtHeader( module );
338 if (nt->OptionalHeader.AddressOfEntryPoint)
340 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
341 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
342 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
343 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
346 if (NtQueryVolumeInformationFile( file, &io, &device_info, sizeof(device_info),
347 FileFsDeviceInformation ) == STATUS_SUCCESS)
349 /* don't keep the file handle open on removable media */
350 if (device_info.Characteristics & FILE_REMOVABLE_MEDIA)
352 CloseHandle( main_exe_file );
360 /***********************************************************************
361 * build_initial_environment
363 * Build the Win32 environment from the Unix environment
365 static BOOL build_initial_environment( char **environ )
372 /* Compute the total size of the Unix environment */
373 for (e = environ; *e; e++)
375 if (is_special_env_var( *e )) continue;
376 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
378 size *= sizeof(WCHAR);
380 /* Now allocate the environment */
382 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
383 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
386 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
387 endptr = p + size / sizeof(WCHAR);
389 /* And fill it with the Unix environment */
390 for (e = environ; *e; e++)
394 /* skip Unix special variables and use the Wine variants instead */
395 if (!strncmp( str, "WINE", 4 ))
397 if (is_special_env_var( str + 4 )) str += 4;
398 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
400 else if (is_special_env_var( str )) continue; /* skip it */
402 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
410 /***********************************************************************
411 * set_registry_variables
413 * Set environment variables by enumerating the values of a key;
414 * helper for set_registry_environment().
415 * Note that Windows happily truncates the value if it's too big.
417 static void set_registry_variables( HANDLE hkey, ULONG type )
419 UNICODE_STRING env_name, env_value;
423 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
424 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
426 for (index = 0; ; index++)
428 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
429 buffer, sizeof(buffer), &size );
430 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
432 if (info->Type != type)
434 env_name.Buffer = info->Name;
435 env_name.Length = env_name.MaximumLength = info->NameLength;
436 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
437 env_value.Length = env_value.MaximumLength = info->DataLength;
438 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
439 env_value.Length--; /* don't count terminating null if any */
440 if (info->Type == REG_EXPAND_SZ)
442 WCHAR buf_expanded[1024];
443 UNICODE_STRING env_expanded;
444 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
445 env_expanded.Buffer=buf_expanded;
446 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
447 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
448 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
452 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
458 /***********************************************************************
459 * set_registry_environment
461 * Set the environment variables specified in the registry.
463 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
464 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
465 * on the order in which the variables are processed. But on Windows it
466 * does not really matter since they only use %SystemDrive% and
467 * %SystemRoot% which are predefined. But Wine defines these in the
468 * registry, so we need two passes.
470 static void set_registry_environment(void)
472 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
473 'S','y','s','t','e','m','\\',
474 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
475 'C','o','n','t','r','o','l','\\',
476 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
477 'E','n','v','i','r','o','n','m','e','n','t',0};
478 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
480 OBJECT_ATTRIBUTES attr;
481 UNICODE_STRING nameW;
484 attr.Length = sizeof(attr);
485 attr.RootDirectory = 0;
486 attr.ObjectName = &nameW;
488 attr.SecurityDescriptor = NULL;
489 attr.SecurityQualityOfService = NULL;
491 /* first the system environment variables */
492 RtlInitUnicodeString( &nameW, env_keyW );
493 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
495 set_registry_variables( hkey, REG_SZ );
496 set_registry_variables( hkey, REG_EXPAND_SZ );
500 /* then the ones for the current user */
501 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return;
502 RtlInitUnicodeString( &nameW, envW );
503 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
505 set_registry_variables( hkey, REG_SZ );
506 set_registry_variables( hkey, REG_EXPAND_SZ );
509 NtClose( attr.RootDirectory );
513 /***********************************************************************
516 * Set the Wine library Unicode argv global variables.
518 static void set_library_wargv( char **argv )
526 for (argc = 0; argv[argc]; argc++)
527 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
529 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
530 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
531 p = (WCHAR *)(wargv + argc + 1);
532 for (argc = 0; argv[argc]; argc++)
534 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
541 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
543 for (argc = 0; wargv[argc]; argc++)
544 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
546 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
547 q = (char *)(argv + argc + 1);
548 for (argc = 0; wargv[argc]; argc++)
550 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
557 __wine_main_argv = argv;
558 __wine_main_wargv = wargv;
562 /***********************************************************************
565 * Build the command line of a process from the argv array.
567 * Note that it does NOT necessarily include the file name.
568 * Sometimes we don't even have any command line options at all.
570 * We must quote and escape characters so that the argv array can be rebuilt
571 * from the command line:
572 * - spaces and tabs must be quoted
574 * - quotes must be escaped
576 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
577 * resulting in an odd number of '\' followed by a '"'
580 * - '\'s that are not followed by a '"' can be left as is
584 static BOOL build_command_line( WCHAR **argv )
589 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
591 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
594 for (arg = argv; *arg; arg++)
596 int has_space,bcount;
602 if( !*a ) has_space=1;
607 if (*a==' ' || *a=='\t') {
609 } else if (*a=='"') {
610 /* doubling of '\' preceding a '"',
611 * plus escaping of said '"'
619 len+=(a-*arg)+1 /* for the separating space */;
621 len+=2; /* for the quotes */
624 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
627 p = rupp->CommandLine.Buffer;
628 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
629 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
630 for (arg = argv; *arg; arg++)
632 int has_space,has_quote;
635 /* Check for quotes and spaces in this argument */
636 has_space=has_quote=0;
638 if( !*a ) has_space=1;
640 if (*a==' ' || *a=='\t') {
644 } else if (*a=='"') {
652 /* Now transfer it to the command line */
669 /* Double all the '\\' preceding this '"', plus one */
670 for (i=0;i<=bcount;i++)
682 while ((*p=*x++)) p++;
688 if (p > rupp->CommandLine.Buffer)
689 p--; /* remove last space */
696 /* make sure the unicode string doesn't point beyond the end pointer */
697 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
699 if ((char *)str->Buffer >= end_ptr)
701 str->Length = str->MaximumLength = 0;
705 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
707 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
709 if (str->Length >= str->MaximumLength)
711 if (str->MaximumLength >= sizeof(WCHAR))
712 str->Length = str->MaximumLength - sizeof(WCHAR);
714 str->Length = str->MaximumLength = 0;
718 static void version(void)
720 MESSAGE( "%s\n", PACKAGE_STRING );
724 static void usage(void)
726 MESSAGE( "%s\n", PACKAGE_STRING );
727 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
728 MESSAGE( " wine --help Display this help and exit\n");
729 MESSAGE( " wine --version Output version information and exit\n");
734 /***********************************************************************
735 * init_user_process_params
737 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
739 static BOOL init_user_process_params( RTL_USER_PROCESS_PARAMETERS *params )
743 SIZE_T size, env_size, info_size;
744 HANDLE hstdin, hstdout, hstderr;
746 size = info_size = params->AllocationSize;
747 if (!size) return TRUE; /* no parameters received from parent */
749 SERVER_START_REQ( get_startup_info )
751 wine_server_set_reply( req, params, size );
752 if ((ret = !wine_server_call( req )))
754 info_size = wine_server_reply_size( reply );
755 main_create_flags = reply->create_flags;
756 main_exe_file = reply->exe_file;
757 hstdin = reply->hstdin;
758 hstdout = reply->hstdout;
759 hstderr = reply->hstderr;
763 if (!ret) return ret;
765 params->AllocationSize = size;
766 if (params->Size > info_size) params->Size = info_size;
768 /* make sure the strings are valid */
769 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
770 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
771 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
772 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
773 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
774 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
775 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
776 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
778 /* environment needs to be a separate memory block */
779 env_size = info_size - params->Size;
780 if (!env_size) env_size = 1;
782 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
783 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
785 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
786 params->Environment = ptr;
788 /* convert value from server:
789 * + 0 => INVALID_HANDLE_VALUE
790 * + console handle needs to be mapped
793 hstdin = INVALID_HANDLE_VALUE;
794 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
795 hstdin = console_handle_map(hstdin);
798 hstdout = INVALID_HANDLE_VALUE;
799 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
800 hstdout = console_handle_map(hstdout);
803 hstderr = INVALID_HANDLE_VALUE;
804 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
805 hstderr = console_handle_map(hstderr);
807 params->hStdInput = hstdin;
808 params->hStdOutput = hstdout;
809 params->hStdError = hstderr;
811 RtlNormalizeProcessParams( params );
816 /***********************************************************************
817 * init_current_directory
819 * Initialize the current directory from the Unix cwd or the parent info.
821 static void init_current_directory( CURDIR *cur_dir )
823 UNICODE_STRING dir_str;
827 /* if we received a cur dir from the parent, try this first */
829 if (cur_dir->DosPath.Length)
831 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
834 /* now try to get it from the Unix cwd */
836 for (size = 256; ; size *= 2)
838 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
839 if (getcwd( cwd, size )) break;
840 HeapFree( GetProcessHeap(), 0, cwd );
841 if (errno == ERANGE) continue;
849 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
850 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
852 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
853 RtlInitUnicodeString( &dir_str, dirW );
854 RtlSetCurrentDirectory_U( &dir_str );
855 RtlFreeUnicodeString( &dir_str );
859 if (!cur_dir->DosPath.Length) /* still not initialized */
861 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
862 "starting in the Windows directory.\n", cwd ? cwd : "" );
863 RtlInitUnicodeString( &dir_str, DIR_Windows );
864 RtlSetCurrentDirectory_U( &dir_str );
866 HeapFree( GetProcessHeap(), 0, cwd );
869 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
870 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
874 /***********************************************************************
877 * Initialize the windows and system directories from the environment.
879 static void init_windows_dirs(void)
881 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
883 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
884 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
885 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
886 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
891 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
893 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
894 GetEnvironmentVariableW( windirW, buffer, len );
895 DIR_Windows = buffer;
897 else DIR_Windows = default_windirW;
899 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
901 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
902 GetEnvironmentVariableW( winsysdirW, buffer, len );
907 len = strlenW( DIR_Windows );
908 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
909 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
910 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
914 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
915 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
916 debugstr_w(DIR_Windows) );
917 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
918 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
919 debugstr_w(DIR_System) );
921 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
922 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
924 /* set the directories in ntdll too */
925 __wine_init_windows_dir( DIR_Windows, DIR_System );
929 /***********************************************************************
932 * Main process initialisation code
934 static BOOL process_init(void)
936 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
937 PEB *peb = NtCurrentTeb()->Peb;
943 setlocale(LC_CTYPE,"");
945 if (!init_user_process_params( peb->ProcessParameters )) return FALSE;
947 kernel32_handle = GetModuleHandleW(kernel32W);
951 if (!peb->ProcessParameters->Environment)
953 /* Copy the parent environment */
954 if (!build_initial_environment( __wine_main_environ )) return FALSE;
956 /* convert old configuration to new format */
957 convert_old_config();
959 set_registry_environment();
963 init_current_directory( &peb->ProcessParameters->CurrentDirectory );
969 /***********************************************************************
972 * Allocate the stack of new process.
974 static void *init_stack(void)
977 SIZE_T stack_size, page_size = getpagesize();
978 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
980 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
981 stack_size += page_size; /* for the guard page */
982 stack_size = (stack_size + 0xffff) & ~0xffff; /* round to 64K boundary */
983 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
985 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
987 ERR( "failed to allocate main process stack\n" );
991 /* note: limit is lower than base since the stack grows down */
992 NtCurrentTeb()->DeallocationStack = base;
993 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
994 NtCurrentTeb()->Tib.StackLimit = (char *)base + page_size;
996 /* setup guard page */
997 VirtualProtect( base, page_size, PAGE_NOACCESS, NULL );
998 return NtCurrentTeb()->Tib.StackBase;
1002 /***********************************************************************
1005 * Startup routine of a new process. Runs on the new process stack.
1007 static void start_process( void *arg )
1011 PEB *peb = NtCurrentTeb()->Peb;
1012 IMAGE_NT_HEADERS *nt;
1013 LPTHREAD_START_ROUTINE entry;
1015 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
1017 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1018 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1019 nt->OptionalHeader.AddressOfEntryPoint);
1021 if (TRACE_ON(relay))
1022 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1023 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1025 SetLastError( 0 ); /* clear error code */
1026 if (peb->BeingDebugged) DbgBreakPoint();
1027 ExitProcess( entry( peb ) );
1029 __EXCEPT(UnhandledExceptionFilter)
1031 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1037 /***********************************************************************
1038 * __wine_kernel_init
1040 * Wine initialisation: load and start the main exe file.
1042 void __wine_kernel_init(void)
1044 WCHAR *main_exe_name, *p;
1047 PEB *peb = NtCurrentTeb()->Peb;
1049 /* Initialize everything */
1050 if (!process_init()) exit(1);
1052 __wine_main_argv++; /* remove argv[0] (wine itself) */
1055 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1057 WCHAR buffer[MAX_PATH];
1058 WCHAR exe_nameW[MAX_PATH];
1060 if (!__wine_main_argv[0]) usage();
1061 if (__wine_main_argc == 1)
1063 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1064 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1067 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1068 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1070 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1073 if (main_exe_file == INVALID_HANDLE_VALUE)
1075 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1078 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1079 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1082 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1083 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1085 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1086 MODULE_get_dll_load_path(NULL) );
1088 if (!main_exe_file) /* no file handle -> Winelib app */
1090 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1091 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ) &&
1092 NtCurrentTeb()->Peb->ImageBaseAddress)
1094 MESSAGE( "wine: cannot open builtin exe for %s: %s\n",
1095 debugstr_w(main_exe_name), error );
1099 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1102 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1103 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1105 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1108 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1110 case BINARY_UNKNOWN:
1111 /* check for .com extension */
1112 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1114 MESSAGE( "wine: cannot determine executable type for %s\n",
1115 debugstr_w(main_exe_name) );
1122 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1123 CloseHandle( main_exe_file );
1127 __wine_main_argv[0] = "winevdm.exe";
1128 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1130 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1131 debugstr_w(main_exe_name), error );
1133 case BINARY_UNIX_EXE:
1134 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1136 case BINARY_UNIX_LIB:
1140 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1141 CloseHandle( main_exe_file );
1143 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1144 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1146 static const WCHAR soW[] = {'.','s','o',0};
1147 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1150 /* update the unicode string */
1151 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1153 HeapFree( GetProcessHeap(), 0, unix_name );
1156 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1162 /* build command line */
1163 set_library_wargv( __wine_main_argv );
1164 if (!build_command_line( __wine_main_wargv )) goto error;
1166 /* switch to the new stack */
1167 wine_switch_to_stack( start_process, NULL, init_stack() );
1170 ExitProcess( GetLastError() );
1174 /***********************************************************************
1177 * Build an argv array from a command-line.
1178 * 'reserved' is the number of args to reserve before the first one.
1180 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1184 char *arg,*s,*d,*cmdline;
1185 int in_quotes,bcount,len;
1187 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1188 if (!(cmdline = malloc(len))) return NULL;
1189 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1196 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1199 /* skip the remaining spaces */
1200 while (*s==' ' || *s=='\t') {
1207 } else if (*s=='\\') {
1208 /* '\', count them */
1210 } else if ((*s=='"') && ((bcount & 1)==0)) {
1212 in_quotes=!in_quotes;
1215 /* a regular character */
1220 argv=malloc(argc*sizeof(*argv));
1229 if ((*s==' ' || *s=='\t') && !in_quotes) {
1230 /* Close the argument and copy it */
1234 /* skip the remaining spaces */
1237 } while (*s==' ' || *s=='\t');
1239 /* Start with a new argument */
1242 } else if (*s=='\\') {
1246 } else if (*s=='"') {
1248 if ((bcount & 1)==0) {
1249 /* Preceded by an even number of '\', this is half that
1250 * number of '\', plus a '"' which we discard.
1254 in_quotes=!in_quotes;
1256 /* Preceded by an odd number of '\', this is half that
1257 * number of '\' followed by a '"'
1265 /* a regular character */
1280 /***********************************************************************
1283 * Allocate an environment string; helper for build_envp
1285 static char *alloc_env_string( const char *name, const char *value )
1287 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1288 strcpy( ret, name );
1289 strcat( ret, value );
1293 /***********************************************************************
1296 * Build the environment of a new child process.
1298 static char **build_envp( const WCHAR *envW )
1303 int count = 0, length;
1305 for (end = envW; *end; count++) end += strlenW(end) + 1;
1307 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1308 if (!(env = malloc( length ))) return NULL;
1309 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1313 if ((envp = malloc( count * sizeof(*envp) )))
1315 char **envptr = envp;
1317 /* some variables must not be modified, so we get them directly from the unix env */
1318 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1319 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1320 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1321 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1322 /* now put the Windows environment strings */
1323 for (p = env; *p; p += strlen(p) + 1)
1325 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1326 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1327 if (is_special_env_var( p )) /* prefix it with "WINE" */
1328 *envptr++ = alloc_env_string( "WINE", p );
1338 /***********************************************************************
1341 * Fork and exec a new Unix binary, checking for errors.
1343 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1344 const WCHAR *env, const char *newdir )
1349 if (!env) env = GetEnvironmentStringsW();
1353 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1356 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1357 if (!(pid = fork())) /* child */
1359 char **argv = build_argv( cmdline, 0 );
1360 char **envp = build_envp( env );
1363 /* Reset signals that we previously set to SIG_IGN */
1364 signal( SIGPIPE, SIG_DFL );
1365 signal( SIGCHLD, SIG_DFL );
1367 if (newdir) chdir(newdir);
1369 if (argv && envp) execve( filename, argv, envp );
1371 write( fd[1], &err, sizeof(err) );
1375 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1380 if (pid == -1) FILE_SetDosError();
1386 /***********************************************************************
1387 * create_user_params
1389 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1390 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1391 const STARTUPINFOW *startup )
1393 RTL_USER_PROCESS_PARAMETERS *params;
1394 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1396 WCHAR buffer[MAX_PATH];
1398 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1399 lstrcpynW( buffer, filename, MAX_PATH );
1400 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1401 lstrcpynW( buffer, filename, MAX_PATH );
1402 RtlInitUnicodeString( &image_str, buffer );
1404 RtlInitUnicodeString( &cmdline_str, cmdline );
1405 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1406 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1407 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1408 if (startup->lpReserved2 && startup->cbReserved2)
1411 runtime.MaximumLength = startup->cbReserved2;
1412 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1415 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1416 cur_dir ? &curdir_str : NULL,
1418 startup->lpTitle ? &title : NULL,
1419 startup->lpDesktop ? &desktop : NULL,
1421 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1422 if (status != STATUS_SUCCESS)
1424 SetLastError( RtlNtStatusToDosError(status) );
1428 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1430 params->hStdInput = startup->hStdInput;
1431 params->hStdOutput = startup->hStdOutput;
1432 params->hStdError = startup->hStdError;
1433 params->dwX = startup->dwX;
1434 params->dwY = startup->dwY;
1435 params->dwXSize = startup->dwXSize;
1436 params->dwYSize = startup->dwYSize;
1437 params->dwXCountChars = startup->dwXCountChars;
1438 params->dwYCountChars = startup->dwYCountChars;
1439 params->dwFillAttribute = startup->dwFillAttribute;
1440 params->dwFlags = startup->dwFlags;
1441 params->wShowWindow = startup->wShowWindow;
1446 /***********************************************************************
1449 * Create a new process. If hFile is a valid handle we have an exe
1450 * file, otherwise it is a Winelib app.
1452 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1453 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1454 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1455 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1456 void *res_start, void *res_end )
1458 BOOL ret, success = FALSE;
1459 HANDLE process_info;
1461 char *winedebug = NULL;
1462 RTL_USER_PROCESS_PARAMETERS *params;
1468 char preloader_reserve[64];
1470 if (!env) RtlAcquirePebLock();
1472 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1474 if (!env) RtlReleasePebLock();
1477 env_end = params->Environment;
1480 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1481 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1483 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1484 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1485 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1487 env_end += strlenW(env_end) + 1;
1491 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1492 (unsigned long)res_start, (unsigned long)res_end, 0 );
1494 /* create the synchronization pipes */
1496 if (pipe( startfd ) == -1)
1498 if (!env) RtlReleasePebLock();
1499 HeapFree( GetProcessHeap(), 0, winedebug );
1500 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1501 RtlDestroyProcessParameters( params );
1504 if (pipe( execfd ) == -1)
1506 if (!env) RtlReleasePebLock();
1507 HeapFree( GetProcessHeap(), 0, winedebug );
1508 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1509 close( startfd[0] );
1510 close( startfd[1] );
1511 RtlDestroyProcessParameters( params );
1514 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1516 /* create the child process */
1518 if (!(pid = fork())) /* child */
1520 char **argv = build_argv( cmd_line, 1 );
1522 close( startfd[1] );
1525 /* wait for parent to tell us to start */
1526 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1528 close( startfd[0] );
1529 /* Reset signals that we previously set to SIG_IGN */
1530 signal( SIGPIPE, SIG_DFL );
1531 signal( SIGCHLD, SIG_DFL );
1533 putenv( preloader_reserve );
1534 if (winedebug) putenv( winedebug );
1535 if (unixdir) chdir(unixdir);
1539 /* first, try for a WINELOADER environment variable */
1540 const char *loader = getenv("WINELOADER");
1541 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1542 /* now use the standard search strategy */
1543 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1546 write( execfd[1], &err, sizeof(err) );
1550 /* this is the parent */
1552 close( startfd[0] );
1554 HeapFree( GetProcessHeap(), 0, winedebug );
1557 if (!env) RtlReleasePebLock();
1558 close( startfd[1] );
1561 RtlDestroyProcessParameters( params );
1565 /* create the process on the server side */
1567 SERVER_START_REQ( new_process )
1569 req->inherit_all = inherit;
1570 req->create_flags = flags;
1571 req->unix_pid = pid;
1572 req->exe_file = hFile;
1573 if (startup->dwFlags & STARTF_USESTDHANDLES)
1575 req->hstdin = startup->hStdInput;
1576 req->hstdout = startup->hStdOutput;
1577 req->hstderr = startup->hStdError;
1581 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1582 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1583 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1586 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1588 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1589 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1590 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1591 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1595 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1596 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1597 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1600 wine_server_add_data( req, params, params->Size );
1601 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1602 ret = !wine_server_call_err( req );
1603 process_info = reply->info;
1607 if (!env) RtlReleasePebLock();
1608 RtlDestroyProcessParameters( params );
1611 close( startfd[1] );
1616 /* tell child to start and wait for it to exec */
1618 write( startfd[1], &dummy, 1 );
1619 close( startfd[1] );
1621 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1626 CloseHandle( process_info );
1631 /* wait for the new process info to be ready */
1633 WaitForSingleObject( process_info, INFINITE );
1634 SERVER_START_REQ( get_new_process_info )
1636 req->info = process_info;
1637 req->process_access = PROCESS_ALL_ACCESS;
1638 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1639 req->thread_access = THREAD_ALL_ACCESS;
1640 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1641 if ((ret = !wine_server_call_err( req )))
1643 info->dwProcessId = (DWORD)reply->pid;
1644 info->dwThreadId = (DWORD)reply->tid;
1645 info->hProcess = reply->phandle;
1646 info->hThread = reply->thandle;
1647 success = reply->success;
1652 if (ret && !success) /* new process failed to start */
1655 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1656 CloseHandle( info->hThread );
1657 CloseHandle( info->hProcess );
1660 CloseHandle( process_info );
1665 /***********************************************************************
1666 * create_vdm_process
1668 * Create a new VDM process for a 16-bit or DOS application.
1670 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1671 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1672 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1673 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1675 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1678 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1679 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1683 SetLastError( ERROR_OUTOFMEMORY );
1686 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1687 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1688 flags, startup, info, unixdir, NULL, NULL );
1689 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1694 /***********************************************************************
1695 * create_cmd_process
1697 * Create a new cmd shell process for a .BAT file.
1699 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1700 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1701 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1702 LPPROCESS_INFORMATION info )
1705 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1706 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1707 WCHAR comspec[MAX_PATH];
1711 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1713 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1714 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1717 strcpyW( newcmdline, comspec );
1718 strcatW( newcmdline, slashcW );
1719 strcatW( newcmdline, cmd_line );
1720 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1721 flags, env, cur_dir, startup, info );
1722 HeapFree( GetProcessHeap(), 0, newcmdline );
1727 /*************************************************************************
1730 * Helper for CreateProcess: retrieve the file name to load from the
1731 * app name and command line. Store the file name in buffer, and
1732 * return a possibly modified command line.
1733 * Also returns a handle to the opened file if it's a Windows binary.
1735 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1736 int buflen, HANDLE *handle )
1738 static const WCHAR quotesW[] = {'"','%','s','"',0};
1740 WCHAR *name, *pos, *ret = NULL;
1744 /* if we have an app name, everything is easy */
1748 /* use the unmodified app name as file name */
1749 lstrcpynW( buffer, appname, buflen );
1750 *handle = open_exe_file( buffer );
1751 if (!(ret = cmdline) || !cmdline[0])
1753 /* no command-line, create one */
1754 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1755 sprintfW( ret, quotesW, appname );
1762 SetLastError( ERROR_INVALID_PARAMETER );
1766 /* first check for a quoted file name */
1768 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1770 int len = p - cmdline - 1;
1771 /* extract the quoted portion as file name */
1772 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1773 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1776 if (find_exe_file( name, buffer, buflen, handle ))
1777 ret = cmdline; /* no change necessary */
1781 /* now try the command-line word by word */
1783 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1791 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1793 if (find_exe_file( name, buffer, buflen, handle ))
1798 if (*p) got_space = TRUE;
1801 if (ret && got_space) /* now build a new command-line with quotes */
1803 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1805 sprintfW( ret, quotesW, name );
1810 HeapFree( GetProcessHeap(), 0, name );
1815 /**********************************************************************
1816 * CreateProcessA (KERNEL32.@)
1818 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1819 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1820 DWORD flags, LPVOID env, LPCSTR cur_dir,
1821 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1824 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1825 UNICODE_STRING desktopW, titleW;
1828 desktopW.Buffer = NULL;
1829 titleW.Buffer = NULL;
1830 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1831 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1832 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1834 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1835 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1837 memcpy( &infoW, startup_info, sizeof(infoW) );
1838 infoW.lpDesktop = desktopW.Buffer;
1839 infoW.lpTitle = titleW.Buffer;
1841 if (startup_info->lpReserved)
1842 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1843 debugstr_a(startup_info->lpReserved));
1845 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1846 inherit, flags, env, cur_dirW, &infoW, info );
1848 HeapFree( GetProcessHeap(), 0, app_nameW );
1849 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1850 HeapFree( GetProcessHeap(), 0, cur_dirW );
1851 RtlFreeUnicodeString( &desktopW );
1852 RtlFreeUnicodeString( &titleW );
1857 /**********************************************************************
1858 * CreateProcessW (KERNEL32.@)
1860 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1861 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1862 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1863 LPPROCESS_INFORMATION info )
1867 char *unixdir = NULL;
1868 WCHAR name[MAX_PATH];
1869 WCHAR *tidy_cmdline, *p, *envW = env;
1870 void *res_start, *res_end;
1872 /* Process the AppName and/or CmdLine to get module name and path */
1874 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1876 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1878 if (hFile == INVALID_HANDLE_VALUE) goto done;
1880 /* Warn if unsupported features are used */
1882 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1883 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1884 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1885 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1886 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1890 unixdir = wine_get_unix_file_name( cur_dir );
1894 WCHAR buf[MAX_PATH];
1895 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1898 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1903 while (*p) p += strlen(p) + 1;
1904 p++; /* final null */
1905 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1906 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1907 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1908 flags |= CREATE_UNICODE_ENVIRONMENT;
1911 info->hThread = info->hProcess = 0;
1912 info->dwProcessId = info->dwThreadId = 0;
1914 /* Determine executable type */
1916 if (!hFile) /* builtin exe */
1918 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1919 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1920 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1924 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1927 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1928 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1929 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1934 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1935 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1936 inherit, flags, startup_info, info, unixdir );
1939 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1940 SetLastError( ERROR_BAD_EXE_FORMAT );
1942 case BINARY_UNIX_LIB:
1943 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1944 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1945 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1947 case BINARY_UNKNOWN:
1948 /* check for .com or .bat extension */
1949 if ((p = strrchrW( name, '.' )))
1951 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1953 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1954 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1955 inherit, flags, startup_info, info, unixdir );
1958 if (!strcmpiW( p, batW ))
1960 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1961 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1962 inherit, flags, startup_info, info );
1967 case BINARY_UNIX_EXE:
1969 /* unknown file, try as unix executable */
1972 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1974 if ((unix_name = wine_get_unix_file_name( name )))
1976 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1977 HeapFree( GetProcessHeap(), 0, unix_name );
1982 CloseHandle( hFile );
1985 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1986 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1987 HeapFree( GetProcessHeap(), 0, unixdir );
1992 /***********************************************************************
1995 * Wrapper to call WaitForInputIdle USER function
1997 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1999 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2001 HMODULE mod = GetModuleHandleA( "user32.dll" );
2004 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2005 if (ptr) return ptr( process, timeout );
2011 /***********************************************************************
2012 * WinExec (KERNEL32.@)
2014 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2016 PROCESS_INFORMATION info;
2017 STARTUPINFOA startup;
2021 memset( &startup, 0, sizeof(startup) );
2022 startup.cb = sizeof(startup);
2023 startup.dwFlags = STARTF_USESHOWWINDOW;
2024 startup.wShowWindow = nCmdShow;
2026 /* cmdline needs to be writeable for CreateProcess */
2027 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2028 strcpy( cmdline, lpCmdLine );
2030 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2031 0, NULL, NULL, &startup, &info ))
2033 /* Give 30 seconds to the app to come up */
2034 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2035 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2037 /* Close off the handles */
2038 CloseHandle( info.hThread );
2039 CloseHandle( info.hProcess );
2041 else if ((ret = GetLastError()) >= 32)
2043 FIXME("Strange error set by CreateProcess: %d\n", ret );
2046 HeapFree( GetProcessHeap(), 0, cmdline );
2051 /**********************************************************************
2052 * LoadModule (KERNEL32.@)
2054 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2056 LOADPARMS32 *params = paramBlock;
2057 PROCESS_INFORMATION info;
2058 STARTUPINFOA startup;
2059 HINSTANCE hInstance;
2061 char filename[MAX_PATH];
2064 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2066 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2067 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2068 return (HINSTANCE)GetLastError();
2070 len = (BYTE)params->lpCmdLine[0];
2071 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2072 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2074 strcpy( cmdline, filename );
2075 p = cmdline + strlen(cmdline);
2077 memcpy( p, params->lpCmdLine + 1, len );
2080 memset( &startup, 0, sizeof(startup) );
2081 startup.cb = sizeof(startup);
2082 if (params->lpCmdShow)
2084 startup.dwFlags = STARTF_USESHOWWINDOW;
2085 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2088 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2089 params->lpEnvAddress, NULL, &startup, &info ))
2091 /* Give 30 seconds to the app to come up */
2092 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2093 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2094 hInstance = (HINSTANCE)33;
2095 /* Close off the handles */
2096 CloseHandle( info.hThread );
2097 CloseHandle( info.hProcess );
2099 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2101 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2102 hInstance = (HINSTANCE)11;
2105 HeapFree( GetProcessHeap(), 0, cmdline );
2110 /******************************************************************************
2111 * TerminateProcess (KERNEL32.@)
2113 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2115 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2116 if (status) SetLastError( RtlNtStatusToDosError(status) );
2121 /***********************************************************************
2122 * ExitProcess (KERNEL32.@)
2124 void WINAPI ExitProcess( DWORD status )
2126 LdrShutdownProcess();
2127 NtTerminateProcess(GetCurrentProcess(), status);
2132 /***********************************************************************
2133 * GetExitCodeProcess [KERNEL32.@]
2135 * Gets termination status of specified process.
2138 * hProcess [in] Handle to the process.
2139 * lpExitCode [out] Address to receive termination status.
2145 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2148 PROCESS_BASIC_INFORMATION pbi;
2150 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2152 if (status == STATUS_SUCCESS)
2154 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2157 SetLastError( RtlNtStatusToDosError(status) );
2162 /***********************************************************************
2163 * SetErrorMode (KERNEL32.@)
2165 UINT WINAPI SetErrorMode( UINT mode )
2167 UINT old = process_error_mode;
2168 process_error_mode = mode;
2173 /**********************************************************************
2174 * TlsAlloc [KERNEL32.@]
2176 * Allocates a thread local storage index.
2179 * Success: TLS index.
2180 * Failure: 0xFFFFFFFF
2182 DWORD WINAPI TlsAlloc( void )
2185 PEB * const peb = NtCurrentTeb()->Peb;
2187 RtlAcquirePebLock();
2188 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2189 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2192 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2195 if (!NtCurrentTeb()->TlsExpansionSlots &&
2196 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2197 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2199 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2201 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2205 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2206 index += TLS_MINIMUM_AVAILABLE;
2209 else SetLastError( ERROR_NO_MORE_ITEMS );
2211 RtlReleasePebLock();
2216 /**********************************************************************
2217 * TlsFree [KERNEL32.@]
2219 * Releases a thread local storage index, making it available for reuse.
2222 * index [in] TLS index to free.
2228 BOOL WINAPI TlsFree( DWORD index )
2232 RtlAcquirePebLock();
2233 if (index >= TLS_MINIMUM_AVAILABLE)
2235 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2236 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2240 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2241 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2243 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2244 else SetLastError( ERROR_INVALID_PARAMETER );
2245 RtlReleasePebLock();
2250 /**********************************************************************
2251 * TlsGetValue [KERNEL32.@]
2253 * Gets value in a thread's TLS slot.
2256 * index [in] TLS index to retrieve value for.
2259 * Success: Value stored in calling thread's TLS slot for index.
2260 * Failure: 0 and GetLastError() returns NO_ERROR.
2262 LPVOID WINAPI TlsGetValue( DWORD index )
2266 if (index < TLS_MINIMUM_AVAILABLE)
2268 ret = NtCurrentTeb()->TlsSlots[index];
2272 index -= TLS_MINIMUM_AVAILABLE;
2273 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2275 SetLastError( ERROR_INVALID_PARAMETER );
2278 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2279 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2281 SetLastError( ERROR_SUCCESS );
2286 /**********************************************************************
2287 * TlsSetValue [KERNEL32.@]
2289 * Stores a value in the thread's TLS slot.
2292 * index [in] TLS index to set value for.
2293 * value [in] Value to be stored.
2299 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2301 if (index < TLS_MINIMUM_AVAILABLE)
2303 NtCurrentTeb()->TlsSlots[index] = value;
2307 index -= TLS_MINIMUM_AVAILABLE;
2308 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2310 SetLastError( ERROR_INVALID_PARAMETER );
2313 if (!NtCurrentTeb()->TlsExpansionSlots &&
2314 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2315 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2317 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2320 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2326 /***********************************************************************
2327 * GetProcessFlags (KERNEL32.@)
2329 DWORD WINAPI GetProcessFlags( DWORD processid )
2331 IMAGE_NT_HEADERS *nt;
2334 if (processid && processid != GetCurrentProcessId()) return 0;
2336 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2338 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2339 flags |= PDB32_CONSOLE_PROC;
2341 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2342 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2347 /***********************************************************************
2348 * GetProcessDword (KERNEL.485)
2349 * GetProcessDword (KERNEL32.18)
2350 * 'Of course you cannot directly access Windows internal structures'
2352 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2357 TRACE("(%ld, %d)\n", dwProcessID, offset );
2359 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2361 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2367 case GPD_APP_COMPAT_FLAGS:
2368 return GetAppCompatFlags16(0);
2369 case GPD_LOAD_DONE_EVENT:
2371 case GPD_HINSTANCE16:
2372 return GetTaskDS16();
2373 case GPD_WINDOWS_VERSION:
2374 return GetExeVersion16();
2376 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2378 return (DWORD)NtCurrentTeb()->Peb;
2379 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2380 GetStartupInfoW(&siw);
2381 return (DWORD)siw.hStdOutput;
2382 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2383 GetStartupInfoW(&siw);
2384 return (DWORD)siw.hStdInput;
2385 case GPD_STARTF_SHOWWINDOW:
2386 GetStartupInfoW(&siw);
2387 return siw.wShowWindow;
2388 case GPD_STARTF_SIZE:
2389 GetStartupInfoW(&siw);
2391 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2393 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2394 return MAKELONG( x, y );
2395 case GPD_STARTF_POSITION:
2396 GetStartupInfoW(&siw);
2398 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2400 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2401 return MAKELONG( x, y );
2402 case GPD_STARTF_FLAGS:
2403 GetStartupInfoW(&siw);
2408 return GetProcessFlags(0);
2410 return process_dword;
2412 ERR("Unknown offset %d\n", offset );
2417 /***********************************************************************
2418 * SetProcessDword (KERNEL.484)
2419 * 'Of course you cannot directly access Windows internal structures'
2421 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2423 TRACE("(%ld, %d)\n", dwProcessID, offset );
2425 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2427 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2433 case GPD_APP_COMPAT_FLAGS:
2434 case GPD_LOAD_DONE_EVENT:
2435 case GPD_HINSTANCE16:
2436 case GPD_WINDOWS_VERSION:
2439 case GPD_STARTF_SHELLDATA:
2440 case GPD_STARTF_HOTKEY:
2441 case GPD_STARTF_SHOWWINDOW:
2442 case GPD_STARTF_SIZE:
2443 case GPD_STARTF_POSITION:
2444 case GPD_STARTF_FLAGS:
2447 ERR("Not allowed to modify offset %d\n", offset );
2450 process_dword = value;
2453 ERR("Unknown offset %d\n", offset );
2459 /***********************************************************************
2460 * ExitProcess (KERNEL.466)
2462 void WINAPI ExitProcess16( WORD status )
2465 ReleaseThunkLock( &count );
2466 ExitProcess( status );
2470 /*********************************************************************
2471 * OpenProcess (KERNEL32.@)
2473 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2477 OBJECT_ATTRIBUTES attr;
2480 cid.UniqueProcess = (HANDLE)id;
2481 cid.UniqueThread = 0; /* FIXME ? */
2483 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2484 attr.RootDirectory = NULL;
2485 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2486 attr.SecurityDescriptor = NULL;
2487 attr.SecurityQualityOfService = NULL;
2488 attr.ObjectName = NULL;
2490 status = NtOpenProcess(&handle, access, &attr, &cid);
2491 if (status != STATUS_SUCCESS)
2493 SetLastError( RtlNtStatusToDosError(status) );
2500 /*********************************************************************
2501 * MapProcessHandle (KERNEL.483)
2502 * GetProcessId (KERNEL32.@)
2504 DWORD WINAPI GetProcessId( HANDLE hProcess )
2507 PROCESS_BASIC_INFORMATION pbi;
2509 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2511 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2512 SetLastError( RtlNtStatusToDosError(status) );
2517 /*********************************************************************
2518 * CloseW32Handle (KERNEL.474)
2519 * CloseHandle (KERNEL32.@)
2521 BOOL WINAPI CloseHandle( HANDLE handle )
2525 /* stdio handles need special treatment */
2526 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2527 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2528 (handle == (HANDLE)STD_ERROR_HANDLE))
2529 handle = GetStdHandle( (DWORD)handle );
2531 if (is_console_handle(handle))
2532 return CloseConsoleHandle(handle);
2534 status = NtClose( handle );
2535 if (status) SetLastError( RtlNtStatusToDosError(status) );
2540 /*********************************************************************
2541 * GetHandleInformation (KERNEL32.@)
2543 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2545 OBJECT_DATA_INFORMATION info;
2546 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2548 if (status) SetLastError( RtlNtStatusToDosError(status) );
2552 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2553 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2559 /*********************************************************************
2560 * SetHandleInformation (KERNEL32.@)
2562 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2564 OBJECT_DATA_INFORMATION info;
2567 /* if not setting both fields, retrieve current value first */
2568 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2569 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2571 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2573 SetLastError( RtlNtStatusToDosError(status) );
2577 if (mask & HANDLE_FLAG_INHERIT)
2578 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2579 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2580 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2582 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2583 if (status) SetLastError( RtlNtStatusToDosError(status) );
2588 /*********************************************************************
2589 * DuplicateHandle (KERNEL32.@)
2591 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2592 HANDLE dest_process, HANDLE *dest,
2593 DWORD access, BOOL inherit, DWORD options )
2597 if (is_console_handle(source))
2599 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2600 if (source_process != dest_process ||
2601 source_process != GetCurrentProcess())
2603 SetLastError(ERROR_INVALID_PARAMETER);
2606 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2607 return (*dest != INVALID_HANDLE_VALUE);
2609 status = NtDuplicateObject( source_process, source, dest_process, dest,
2610 access, inherit ? OBJ_INHERIT : 0, options );
2611 if (status) SetLastError( RtlNtStatusToDosError(status) );
2616 /***********************************************************************
2617 * ConvertToGlobalHandle (KERNEL.476)
2618 * ConvertToGlobalHandle (KERNEL32.@)
2620 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2622 HANDLE ret = INVALID_HANDLE_VALUE;
2623 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2624 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2629 /***********************************************************************
2630 * SetHandleContext (KERNEL32.@)
2632 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2634 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2635 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2636 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2641 /***********************************************************************
2642 * GetHandleContext (KERNEL32.@)
2644 DWORD WINAPI GetHandleContext(HANDLE hnd)
2646 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2647 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2648 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2653 /***********************************************************************
2654 * CreateSocketHandle (KERNEL32.@)
2656 HANDLE WINAPI CreateSocketHandle(void)
2658 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2659 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2660 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2661 return INVALID_HANDLE_VALUE;
2665 /***********************************************************************
2666 * SetPriorityClass (KERNEL32.@)
2668 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2671 PROCESS_PRIORITY_CLASS ppc;
2673 ppc.Foreground = FALSE;
2674 switch (priorityclass)
2676 case IDLE_PRIORITY_CLASS:
2677 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2678 case BELOW_NORMAL_PRIORITY_CLASS:
2679 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2680 case NORMAL_PRIORITY_CLASS:
2681 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2682 case ABOVE_NORMAL_PRIORITY_CLASS:
2683 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2684 case HIGH_PRIORITY_CLASS:
2685 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2686 case REALTIME_PRIORITY_CLASS:
2687 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2689 SetLastError(ERROR_INVALID_PARAMETER);
2693 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2696 if (status != STATUS_SUCCESS)
2698 SetLastError( RtlNtStatusToDosError(status) );
2705 /***********************************************************************
2706 * GetPriorityClass (KERNEL32.@)
2708 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2711 PROCESS_BASIC_INFORMATION pbi;
2713 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2715 if (status != STATUS_SUCCESS)
2717 SetLastError( RtlNtStatusToDosError(status) );
2720 switch (pbi.BasePriority)
2722 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2723 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2724 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2725 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2726 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2727 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2729 SetLastError( ERROR_INVALID_PARAMETER );
2734 /***********************************************************************
2735 * SetProcessAffinityMask (KERNEL32.@)
2737 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2741 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2742 &affmask, sizeof(DWORD_PTR));
2745 SetLastError( RtlNtStatusToDosError(status) );
2752 /**********************************************************************
2753 * GetProcessAffinityMask (KERNEL32.@)
2755 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2756 PDWORD_PTR lpProcessAffinityMask,
2757 PDWORD_PTR lpSystemAffinityMask )
2759 PROCESS_BASIC_INFORMATION pbi;
2762 status = NtQueryInformationProcess(hProcess,
2763 ProcessBasicInformation,
2764 &pbi, sizeof(pbi), NULL);
2767 SetLastError( RtlNtStatusToDosError(status) );
2770 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2772 if (lpSystemAffinityMask) *lpSystemAffinityMask = 1;
2777 /***********************************************************************
2778 * GetProcessVersion (KERNEL32.@)
2780 DWORD WINAPI GetProcessVersion( DWORD processid )
2782 IMAGE_NT_HEADERS *nt;
2784 if (processid && processid != GetCurrentProcessId())
2786 FIXME("should use ReadProcessMemory\n");
2789 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2790 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2791 nt->OptionalHeader.MinorSubsystemVersion);
2796 /***********************************************************************
2797 * SetProcessWorkingSetSize [KERNEL32.@]
2798 * Sets the min/max working set sizes for a specified process.
2801 * hProcess [I] Handle to the process of interest
2802 * minset [I] Specifies minimum working set size
2803 * maxset [I] Specifies maximum working set size
2809 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2812 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2813 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2814 /* Trim the working set to zero */
2815 /* Swap the process out of physical RAM */
2820 /***********************************************************************
2821 * GetProcessWorkingSetSize (KERNEL32.@)
2823 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2826 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2827 /* 32 MB working set size */
2828 if (minset) *minset = 32*1024*1024;
2829 if (maxset) *maxset = 32*1024*1024;
2834 /***********************************************************************
2835 * SetProcessShutdownParameters (KERNEL32.@)
2837 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2839 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2840 shutdown_flags = flags;
2841 shutdown_priority = level;
2846 /***********************************************************************
2847 * GetProcessShutdownParameters (KERNEL32.@)
2850 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2852 *lpdwLevel = shutdown_priority;
2853 *lpdwFlags = shutdown_flags;
2858 /***********************************************************************
2859 * GetProcessPriorityBoost (KERNEL32.@)
2861 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2863 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2865 /* Report that no boost is present.. */
2866 *pDisablePriorityBoost = FALSE;
2871 /***********************************************************************
2872 * SetProcessPriorityBoost (KERNEL32.@)
2874 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2876 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2877 /* Say we can do it. I doubt the program will notice that we don't. */
2882 /***********************************************************************
2883 * ReadProcessMemory (KERNEL32.@)
2885 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2886 SIZE_T *bytes_read )
2888 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2889 if (status) SetLastError( RtlNtStatusToDosError(status) );
2894 /***********************************************************************
2895 * WriteProcessMemory (KERNEL32.@)
2897 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2898 SIZE_T *bytes_written )
2900 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2901 if (status) SetLastError( RtlNtStatusToDosError(status) );
2906 /****************************************************************************
2907 * FlushInstructionCache (KERNEL32.@)
2909 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2912 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2913 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2914 if (status) SetLastError( RtlNtStatusToDosError(status) );
2919 /******************************************************************
2920 * GetProcessIoCounters (KERNEL32.@)
2922 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2926 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2927 ioc, sizeof(*ioc), NULL);
2928 if (status) SetLastError( RtlNtStatusToDosError(status) );
2932 /***********************************************************************
2933 * ProcessIdToSessionId (KERNEL32.@)
2934 * This function is available on Terminal Server 4SP4 and Windows 2000
2936 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2938 /* According to MSDN, if the calling process is not in a terminal
2939 * services environment, then the sessionid returned is zero.
2946 /***********************************************************************
2947 * RegisterServiceProcess (KERNEL.491)
2948 * RegisterServiceProcess (KERNEL32.@)
2950 * A service process calls this function to ensure that it continues to run
2951 * even after a user logged off.
2953 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2955 /* I don't think that Wine needs to do anything in this function */
2956 return 1; /* success */
2960 /***********************************************************************
2961 * GetCurrentProcess (KERNEL32.@)
2963 * Get a handle to the current process.
2969 * A handle representing the current process.
2971 #undef GetCurrentProcess
2972 HANDLE WINAPI GetCurrentProcess(void)
2974 return (HANDLE)0xffffffff;