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>
36 #include "wine/winbase16.h"
37 #include "wine/winuser16.h"
42 #include "kernel_private.h"
43 #include "wine/exception.h"
44 #include "wine/server.h"
45 #include "wine/unicode.h"
46 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(process);
49 WINE_DECLARE_DEBUG_CHANNEL(file);
50 WINE_DECLARE_DEBUG_CHANNEL(relay);
60 static UINT process_error_mode;
62 static HANDLE main_exe_file;
63 static DWORD shutdown_flags = 0;
64 static DWORD shutdown_priority = 0x280;
65 static DWORD process_dword;
67 int main_create_flags = 0;
68 HMODULE kernel32_handle = 0;
70 const WCHAR *DIR_Windows = NULL;
71 const WCHAR *DIR_System = NULL;
74 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
75 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
76 #define PDB32_DOS_PROC 0x0010 /* Dos process */
77 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
78 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
79 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
81 static const WCHAR comW[] = {'.','c','o','m',0};
82 static const WCHAR batW[] = {'.','b','a','t',0};
83 static const WCHAR pifW[] = {'.','p','i','f',0};
84 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
86 extern void SHELL_LoadRegistry(void);
87 extern void VERSION_Init( const WCHAR *appname );
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];
165 if ((p = strrchrW( name, '/' ))) name = p + 1;
166 if ((p = strrchrW( name, '\\' ))) name = p + 1;
168 /* we don't want to depend on the current codepage here */
169 len = strlenW( name ) + 1;
170 if (len >= sizeof(exename)) return NULL;
171 for (i = 0; i < len; i++)
173 if (name[i] > 127) return NULL;
174 exename[i] = (char)name[i];
175 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
177 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
181 /***********************************************************************
184 * Open a specific exe file, taking load order into account.
185 * Returns the file handle or 0 for a builtin exe.
187 static HANDLE open_exe_file( const WCHAR *name )
189 enum loadorder_type loadorder[LOADORDER_NTYPES];
190 WCHAR buffer[MAX_PATH];
194 TRACE("looking for %s\n", debugstr_w(name) );
196 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
197 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
199 /* file doesn't exist, check for builtin */
200 if (!contains_path( name )) goto error;
201 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
205 MODULE_GetLoadOrderW( loadorder, NULL, name );
207 for(i = 0; i < LOADORDER_NTYPES; i++)
209 if (loadorder[i] == LOADORDER_INVALID) break;
213 TRACE( "Trying native exe %s\n", debugstr_w(name) );
214 if (handle != INVALID_HANDLE_VALUE) return handle;
217 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
218 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
221 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
228 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
231 SetLastError( ERROR_FILE_NOT_FOUND );
232 return INVALID_HANDLE_VALUE;
236 /***********************************************************************
239 * Open an exe file, and return the full name and file handle.
240 * Returns FALSE if file could not be found.
241 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
242 * If file is a builtin exe, returns TRUE and sets handle to 0.
244 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
246 static const WCHAR exeW[] = {'.','e','x','e',0};
248 enum loadorder_type loadorder[LOADORDER_NTYPES];
251 TRACE("looking for %s\n", debugstr_w(name) );
253 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
254 !get_builtin_path( name, exeW, buffer, buflen ))
256 /* no builtin found, try native without extension in case it is a Unix app */
258 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
260 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
261 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
262 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
268 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
270 for(i = 0; i < LOADORDER_NTYPES; i++)
272 if (loadorder[i] == LOADORDER_INVALID) break;
276 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
277 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
278 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
280 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
283 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
284 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
295 SetLastError( ERROR_FILE_NOT_FOUND );
300 /**********************************************************************
303 * Load a PE format EXE file.
305 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
308 FILE_FS_DEVICE_INFORMATION device_info;
309 IMAGE_NT_HEADERS *nt;
312 OBJECT_ATTRIBUTES attr;
316 attr.Length = sizeof(attr);
317 attr.RootDirectory = 0;
318 attr.ObjectName = NULL;
320 attr.SecurityDescriptor = NULL;
321 attr.SecurityQualityOfService = NULL;
324 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
325 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
329 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
330 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
336 nt = RtlImageNtHeader( module );
337 if (nt->OptionalHeader.AddressOfEntryPoint)
339 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
340 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
341 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
342 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
345 if (NtQueryVolumeInformationFile( file, &io, &device_info, sizeof(device_info),
346 FileFsDeviceInformation ) == STATUS_SUCCESS)
348 /* don't keep the file handle open on removable media */
349 if (device_info.Characteristics & FILE_REMOVABLE_MEDIA)
351 CloseHandle( main_exe_file );
359 /***********************************************************************
360 * build_initial_environment
362 * Build the Win32 environment from the Unix environment
364 static BOOL build_initial_environment( char **environ )
371 /* Compute the total size of the Unix environment */
372 for (e = environ; *e; e++)
374 if (is_special_env_var( *e )) continue;
375 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
377 size *= sizeof(WCHAR);
379 /* Now allocate the environment */
381 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
382 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
385 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
386 endptr = p + size / sizeof(WCHAR);
388 /* And fill it with the Unix environment */
389 for (e = environ; *e; e++)
393 /* skip Unix special variables and use the Wine variants instead */
394 if (!strncmp( str, "WINE", 4 ))
396 if (is_special_env_var( str + 4 )) str += 4;
397 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
399 else if (is_special_env_var( str )) continue; /* skip it */
401 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
409 /***********************************************************************
410 * set_registry_variables
412 * Set environment variables by enumerating the values of a key;
413 * helper for set_registry_environment().
414 * Note that Windows happily truncates the value if it's too big.
416 static void set_registry_variables( HANDLE hkey, ULONG type )
418 UNICODE_STRING env_name, env_value;
422 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
423 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
425 for (index = 0; ; index++)
427 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
428 buffer, sizeof(buffer), &size );
429 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
431 if (info->Type != type)
433 env_name.Buffer = info->Name;
434 env_name.Length = env_name.MaximumLength = info->NameLength;
435 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
436 env_value.Length = env_value.MaximumLength = info->DataLength;
437 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
438 env_value.Length--; /* don't count terminating null if any */
439 if (info->Type == REG_EXPAND_SZ)
441 WCHAR buf_expanded[1024];
442 UNICODE_STRING env_expanded;
443 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
444 env_expanded.Buffer=buf_expanded;
445 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
446 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
447 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
451 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
457 /***********************************************************************
458 * set_registry_environment
460 * Set the environment variables specified in the registry.
462 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
463 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
464 * on the order in which the variables are processed. But on Windows it
465 * does not really matter since they only use %SystemDrive% and
466 * %SystemRoot% which are predefined. But Wine defines these in the
467 * registry, so we need two passes.
469 static void set_registry_environment(void)
471 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
472 'S','y','s','t','e','m','\\',
473 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
474 'C','o','n','t','r','o','l','\\',
475 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
476 'E','n','v','i','r','o','n','m','e','n','t',0};
477 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
479 OBJECT_ATTRIBUTES attr;
480 UNICODE_STRING nameW;
483 attr.Length = sizeof(attr);
484 attr.RootDirectory = 0;
485 attr.ObjectName = &nameW;
487 attr.SecurityDescriptor = NULL;
488 attr.SecurityQualityOfService = NULL;
490 /* first the system environment variables */
491 RtlInitUnicodeString( &nameW, env_keyW );
492 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
494 set_registry_variables( hkey, REG_SZ );
495 set_registry_variables( hkey, REG_EXPAND_SZ );
499 /* then the ones for the current user */
500 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return;
501 RtlInitUnicodeString( &nameW, envW );
502 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
504 set_registry_variables( hkey, REG_SZ );
505 set_registry_variables( hkey, REG_EXPAND_SZ );
508 NtClose( attr.RootDirectory );
512 /***********************************************************************
515 * Set the Wine library Unicode argv global variables.
517 static void set_library_wargv( char **argv )
525 for (argc = 0; argv[argc]; argc++)
526 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
528 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
529 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
530 p = (WCHAR *)(wargv + argc + 1);
531 for (argc = 0; argv[argc]; argc++)
533 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
540 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
542 for (argc = 0; wargv[argc]; argc++)
543 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
545 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
546 q = (char *)(argv + argc + 1);
547 for (argc = 0; wargv[argc]; argc++)
549 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
556 __wine_main_argv = argv;
557 __wine_main_wargv = wargv;
561 /***********************************************************************
564 * Build the command line of a process from the argv array.
566 * Note that it does NOT necessarily include the file name.
567 * Sometimes we don't even have any command line options at all.
569 * We must quote and escape characters so that the argv array can be rebuilt
570 * from the command line:
571 * - spaces and tabs must be quoted
573 * - quotes must be escaped
575 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
576 * resulting in an odd number of '\' followed by a '"'
579 * - '\'s that are not followed by a '"' can be left as is
583 static BOOL build_command_line( WCHAR **argv )
588 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
590 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
593 for (arg = argv; *arg; arg++)
595 int has_space,bcount;
601 if( !*a ) has_space=1;
606 if (*a==' ' || *a=='\t') {
608 } else if (*a=='"') {
609 /* doubling of '\' preceding a '"',
610 * plus escaping of said '"'
618 len+=(a-*arg)+1 /* for the separating space */;
620 len+=2; /* for the quotes */
623 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
626 p = rupp->CommandLine.Buffer;
627 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
628 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
629 for (arg = argv; *arg; arg++)
631 int has_space,has_quote;
634 /* Check for quotes and spaces in this argument */
635 has_space=has_quote=0;
637 if( !*a ) has_space=1;
639 if (*a==' ' || *a=='\t') {
643 } else if (*a=='"') {
651 /* Now transfer it to the command line */
668 /* Double all the '\\' preceding this '"', plus one */
669 for (i=0;i<=bcount;i++)
681 while ((*p=*x++)) p++;
687 if (p > rupp->CommandLine.Buffer)
688 p--; /* remove last space */
695 /* make sure the unicode string doesn't point beyond the end pointer */
696 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
698 if ((char *)str->Buffer >= end_ptr)
700 str->Length = str->MaximumLength = 0;
704 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
706 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
708 if (str->Length >= str->MaximumLength)
710 if (str->MaximumLength >= sizeof(WCHAR))
711 str->Length = str->MaximumLength - sizeof(WCHAR);
713 str->Length = str->MaximumLength = 0;
717 static void version(void)
719 MESSAGE( "%s\n", PACKAGE_STRING );
723 static void usage(void)
725 MESSAGE( "%s\n", PACKAGE_STRING );
726 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
727 MESSAGE( " wine --help Display this help and exit\n");
728 MESSAGE( " wine --version Output version information and exit\n");
733 /***********************************************************************
734 * init_user_process_params
736 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
738 static BOOL init_user_process_params( RTL_USER_PROCESS_PARAMETERS *params )
742 DWORD size, env_size, info_size;
743 HANDLE hstdin, hstdout, hstderr;
745 size = info_size = params->AllocationSize;
746 if (!size) return TRUE; /* no parameters received from parent */
748 SERVER_START_REQ( get_startup_info )
750 wine_server_set_reply( req, params, size );
751 if ((ret = !wine_server_call( req )))
753 info_size = wine_server_reply_size( reply );
754 main_create_flags = reply->create_flags;
755 main_exe_file = reply->exe_file;
756 hstdin = reply->hstdin;
757 hstdout = reply->hstdout;
758 hstderr = reply->hstderr;
762 if (!ret) return ret;
764 params->AllocationSize = size;
765 if (params->Size > info_size) params->Size = info_size;
767 /* make sure the strings are valid */
768 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
769 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
770 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
771 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
772 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
773 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
774 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
775 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
777 /* environment needs to be a separate memory block */
778 env_size = info_size - params->Size;
779 if (!env_size) env_size = 1;
781 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
782 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
784 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
785 params->Environment = ptr;
787 /* convert value from server:
788 * + 0 => INVALID_HANDLE_VALUE
789 * + console handle needs to be mapped
792 hstdin = INVALID_HANDLE_VALUE;
793 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
794 hstdin = console_handle_map(hstdin);
797 hstdout = INVALID_HANDLE_VALUE;
798 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
799 hstdout = console_handle_map(hstdout);
802 hstderr = INVALID_HANDLE_VALUE;
803 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
804 hstderr = console_handle_map(hstderr);
806 params->hStdInput = hstdin;
807 params->hStdOutput = hstdout;
808 params->hStdError = hstderr;
810 RtlNormalizeProcessParams( params );
815 /***********************************************************************
816 * init_current_directory
818 * Initialize the current directory from the Unix cwd or the parent info.
820 static void init_current_directory( CURDIR *cur_dir )
822 UNICODE_STRING dir_str;
826 /* if we received a cur dir from the parent, try this first */
828 if (cur_dir->DosPath.Length)
830 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
833 /* now try to get it from the Unix cwd */
835 for (size = 256; ; size *= 2)
837 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
838 if (getcwd( cwd, size )) break;
839 HeapFree( GetProcessHeap(), 0, cwd );
840 if (errno == ERANGE) continue;
848 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
849 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
851 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
852 RtlInitUnicodeString( &dir_str, dirW );
853 RtlSetCurrentDirectory_U( &dir_str );
854 RtlFreeUnicodeString( &dir_str );
858 if (!cur_dir->DosPath.Length) /* still not initialized */
860 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
861 "starting in the Windows directory.\n", cwd ? cwd : "" );
862 RtlInitUnicodeString( &dir_str, DIR_Windows );
863 RtlSetCurrentDirectory_U( &dir_str );
865 HeapFree( GetProcessHeap(), 0, cwd );
868 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
869 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
873 /***********************************************************************
876 * Initialize the windows and system directories from the environment.
878 static void init_windows_dirs(void)
880 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
882 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
883 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
884 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
885 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m',0};
890 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
892 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
893 GetEnvironmentVariableW( windirW, buffer, len );
894 DIR_Windows = buffer;
896 else DIR_Windows = default_windirW;
898 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
900 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
901 GetEnvironmentVariableW( winsysdirW, buffer, len );
906 len = strlenW( DIR_Windows );
907 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
908 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
909 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
913 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
914 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
915 debugstr_w(DIR_Windows) );
916 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
917 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
918 debugstr_w(DIR_System) );
920 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
921 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
923 /* set the directories in ntdll too */
924 __wine_init_windows_dir( DIR_Windows, DIR_System );
928 /***********************************************************************
931 * Main process initialisation code
933 static BOOL process_init(void)
935 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
936 PEB *peb = NtCurrentTeb()->Peb;
937 extern void __wine_dbg_kernel32_init(void);
941 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
945 setlocale(LC_CTYPE,"");
947 if (!init_user_process_params( peb->ProcessParameters )) return FALSE;
949 kernel32_handle = GetModuleHandleW(kernel32W);
953 if (!peb->ProcessParameters->Environment)
955 /* Copy the parent environment */
956 if (!build_initial_environment( __wine_main_environ )) return FALSE;
958 /* convert old configuration to new format */
959 convert_old_config();
961 set_registry_environment();
965 init_current_directory( &peb->ProcessParameters->CurrentDirectory );
971 /***********************************************************************
974 * Startup routine of a new process. Runs on the new process stack.
976 static void start_process( void *arg )
980 PEB *peb = NtCurrentTeb()->Peb;
981 IMAGE_NT_HEADERS *nt;
982 LPTHREAD_START_ROUTINE entry;
984 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
986 nt = RtlImageNtHeader( peb->ImageBaseAddress );
987 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
988 nt->OptionalHeader.AddressOfEntryPoint);
991 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
992 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
994 SetLastError( 0 ); /* clear error code */
995 if (peb->BeingDebugged) DbgBreakPoint();
996 ExitProcess( entry( peb ) );
998 __EXCEPT(UnhandledExceptionFilter)
1000 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1006 /***********************************************************************
1007 * __wine_kernel_init
1009 * Wine initialisation: load and start the main exe file.
1011 void __wine_kernel_init(void)
1013 WCHAR *main_exe_name, *p;
1015 DWORD stack_size = 0;
1017 PEB *peb = NtCurrentTeb()->Peb;
1019 /* Initialize everything */
1020 if (!process_init()) exit(1);
1022 __wine_main_argv++; /* remove argv[0] (wine itself) */
1025 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1027 WCHAR buffer[MAX_PATH];
1028 WCHAR exe_nameW[MAX_PATH];
1030 if (!__wine_main_argv[0]) usage();
1031 if (__wine_main_argc == 1)
1033 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1034 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1037 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1038 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1040 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1043 if (main_exe_file == INVALID_HANDLE_VALUE)
1045 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1048 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1049 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1052 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1053 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1055 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1056 MODULE_get_dll_load_path(NULL) );
1057 VERSION_Init( main_exe_name );
1059 if (!main_exe_file) /* no file handle -> Winelib app */
1061 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1062 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1064 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1065 debugstr_w(main_exe_name), error );
1069 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1072 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1073 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1075 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1078 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1080 case BINARY_UNKNOWN:
1081 /* check for .com extension */
1082 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1084 MESSAGE( "wine: cannot determine executable type for %s\n",
1085 debugstr_w(main_exe_name) );
1092 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1093 CloseHandle( main_exe_file );
1097 __wine_main_argv[0] = "winevdm.exe";
1098 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1100 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1101 debugstr_w(main_exe_name), error );
1103 case BINARY_UNIX_EXE:
1104 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1106 case BINARY_UNIX_LIB:
1110 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1111 CloseHandle( main_exe_file );
1113 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1114 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1116 static const WCHAR soW[] = {'.','s','o',0};
1117 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1120 /* update the unicode string */
1121 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1123 HeapFree( GetProcessHeap(), 0, unix_name );
1126 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1132 /* build command line */
1133 set_library_wargv( __wine_main_argv );
1134 if (!build_command_line( __wine_main_wargv )) goto error;
1136 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1138 /* allocate main thread stack */
1139 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1141 /* switch to the new stack */
1142 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1145 ExitProcess( GetLastError() );
1149 /***********************************************************************
1152 * Build an argv array from a command-line.
1153 * 'reserved' is the number of args to reserve before the first one.
1155 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1159 char *arg,*s,*d,*cmdline;
1160 int in_quotes,bcount,len;
1162 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1163 if (!(cmdline = malloc(len))) return NULL;
1164 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1171 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1174 /* skip the remaining spaces */
1175 while (*s==' ' || *s=='\t') {
1182 } else if (*s=='\\') {
1183 /* '\', count them */
1185 } else if ((*s=='"') && ((bcount & 1)==0)) {
1187 in_quotes=!in_quotes;
1190 /* a regular character */
1195 argv=malloc(argc*sizeof(*argv));
1204 if ((*s==' ' || *s=='\t') && !in_quotes) {
1205 /* Close the argument and copy it */
1209 /* skip the remaining spaces */
1212 } while (*s==' ' || *s=='\t');
1214 /* Start with a new argument */
1217 } else if (*s=='\\') {
1221 } else if (*s=='"') {
1223 if ((bcount & 1)==0) {
1224 /* Preceded by an even number of '\', this is half that
1225 * number of '\', plus a '"' which we discard.
1229 in_quotes=!in_quotes;
1231 /* Preceded by an odd number of '\', this is half that
1232 * number of '\' followed by a '"'
1240 /* a regular character */
1255 /***********************************************************************
1258 * Allocate an environment string; helper for build_envp
1260 static char *alloc_env_string( const char *name, const char *value )
1262 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1263 strcpy( ret, name );
1264 strcat( ret, value );
1268 /***********************************************************************
1271 * Build the environment of a new child process.
1273 static char **build_envp( const WCHAR *envW )
1278 int count = 0, length;
1280 for (end = envW; *end; count++) end += strlenW(end) + 1;
1282 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1283 if (!(env = malloc( length ))) return NULL;
1284 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1288 if ((envp = malloc( count * sizeof(*envp) )))
1290 char **envptr = envp;
1292 /* some variables must not be modified, so we get them directly from the unix env */
1293 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1294 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1295 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1296 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1297 /* now put the Windows environment strings */
1298 for (p = env; *p; p += strlen(p) + 1)
1300 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1301 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1302 if (is_special_env_var( p )) /* prefix it with "WINE" */
1303 *envptr++ = alloc_env_string( "WINE", p );
1313 /***********************************************************************
1316 * Fork and exec a new Unix binary, checking for errors.
1318 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1319 const WCHAR *env, const char *newdir )
1324 if (!env) env = GetEnvironmentStringsW();
1328 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1331 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1332 if (!(pid = fork())) /* child */
1334 char **argv = build_argv( cmdline, 0 );
1335 char **envp = build_envp( env );
1338 /* Reset signals that we previously set to SIG_IGN */
1339 signal( SIGPIPE, SIG_DFL );
1340 signal( SIGCHLD, SIG_DFL );
1342 if (newdir) chdir(newdir);
1344 if (argv && envp) execve( filename, argv, envp );
1346 write( fd[1], &err, sizeof(err) );
1350 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1355 if (pid == -1) FILE_SetDosError();
1361 /***********************************************************************
1362 * create_user_params
1364 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1365 LPCWSTR cur_dir, LPWSTR env,
1366 const STARTUPINFOW *startup )
1368 RTL_USER_PROCESS_PARAMETERS *params;
1369 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1371 WCHAR buffer[MAX_PATH];
1373 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1374 lstrcpynW( buffer, filename, MAX_PATH );
1375 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1376 lstrcpynW( buffer, filename, MAX_PATH );
1377 RtlInitUnicodeString( &image_str, buffer );
1379 RtlInitUnicodeString( &cmdline_str, cmdline );
1380 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1381 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1382 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1383 if (startup->lpReserved2 && startup->cbReserved2)
1386 runtime.MaximumLength = startup->cbReserved2;
1387 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1390 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1391 cur_dir ? &curdir_str : NULL,
1393 startup->lpTitle ? &title : NULL,
1394 startup->lpDesktop ? &desktop : NULL,
1396 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1397 if (status != STATUS_SUCCESS)
1399 SetLastError( RtlNtStatusToDosError(status) );
1403 params->hStdInput = startup->hStdInput;
1404 params->hStdOutput = startup->hStdOutput;
1405 params->hStdError = startup->hStdError;
1406 params->dwX = startup->dwX;
1407 params->dwY = startup->dwY;
1408 params->dwXSize = startup->dwXSize;
1409 params->dwYSize = startup->dwYSize;
1410 params->dwXCountChars = startup->dwXCountChars;
1411 params->dwYCountChars = startup->dwYCountChars;
1412 params->dwFillAttribute = startup->dwFillAttribute;
1413 params->dwFlags = startup->dwFlags;
1414 params->wShowWindow = startup->wShowWindow;
1419 /***********************************************************************
1422 * Create a new process. If hFile is a valid handle we have an exe
1423 * file, otherwise it is a Winelib app.
1425 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1426 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1427 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1428 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1429 void *res_start, void *res_end )
1431 BOOL ret, success = FALSE;
1432 HANDLE process_info;
1434 RTL_USER_PROCESS_PARAMETERS *params;
1440 char preloader_reserve[64];
1442 if (!env) RtlAcquirePebLock();
1444 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, startup )))
1446 if (!env) RtlReleasePebLock();
1449 env_end = params->Environment;
1450 while (*env_end) env_end += strlenW(env_end) + 1;
1453 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1454 (unsigned long)res_start, (unsigned long)res_end, 0 );
1456 /* create the synchronization pipes */
1458 if (pipe( startfd ) == -1)
1460 if (!env) RtlReleasePebLock();
1461 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1462 RtlDestroyProcessParameters( params );
1465 if (pipe( execfd ) == -1)
1467 if (!env) RtlReleasePebLock();
1468 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1469 close( startfd[0] );
1470 close( startfd[1] );
1471 RtlDestroyProcessParameters( params );
1474 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1476 /* create the child process */
1478 if (!(pid = fork())) /* child */
1480 char **argv = build_argv( cmd_line, 1 );
1482 close( startfd[1] );
1485 /* wait for parent to tell us to start */
1486 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1488 close( startfd[0] );
1489 /* Reset signals that we previously set to SIG_IGN */
1490 signal( SIGPIPE, SIG_DFL );
1491 signal( SIGCHLD, SIG_DFL );
1493 putenv( preloader_reserve );
1494 if (unixdir) chdir(unixdir);
1498 /* first, try for a WINELOADER environment variable */
1499 const char *loader = getenv("WINELOADER");
1500 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1501 /* now use the standard search strategy */
1502 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1505 write( execfd[1], &err, sizeof(err) );
1509 /* this is the parent */
1511 close( startfd[0] );
1515 if (!env) RtlReleasePebLock();
1516 close( startfd[1] );
1519 RtlDestroyProcessParameters( params );
1523 /* create the process on the server side */
1525 SERVER_START_REQ( new_process )
1527 req->inherit_all = inherit;
1528 req->create_flags = flags;
1529 req->unix_pid = pid;
1530 req->exe_file = hFile;
1531 if (startup->dwFlags & STARTF_USESTDHANDLES)
1533 req->hstdin = startup->hStdInput;
1534 req->hstdout = startup->hStdOutput;
1535 req->hstderr = startup->hStdError;
1539 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1540 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1541 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1544 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1546 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1547 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1548 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1549 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1553 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1554 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1555 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1558 wine_server_add_data( req, params, params->Size );
1559 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1560 ret = !wine_server_call_err( req );
1561 process_info = reply->info;
1565 if (!env) RtlReleasePebLock();
1566 RtlDestroyProcessParameters( params );
1569 close( startfd[1] );
1574 /* tell child to start and wait for it to exec */
1576 write( startfd[1], &dummy, 1 );
1577 close( startfd[1] );
1579 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1584 CloseHandle( process_info );
1589 /* wait for the new process info to be ready */
1591 WaitForSingleObject( process_info, INFINITE );
1592 SERVER_START_REQ( get_new_process_info )
1594 req->info = process_info;
1595 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1596 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1597 if ((ret = !wine_server_call_err( req )))
1599 info->dwProcessId = (DWORD)reply->pid;
1600 info->dwThreadId = (DWORD)reply->tid;
1601 info->hProcess = reply->phandle;
1602 info->hThread = reply->thandle;
1603 success = reply->success;
1608 if (ret && !success) /* new process failed to start */
1611 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1612 CloseHandle( info->hThread );
1613 CloseHandle( info->hProcess );
1616 CloseHandle( process_info );
1621 /***********************************************************************
1622 * create_vdm_process
1624 * Create a new VDM process for a 16-bit or DOS application.
1626 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1627 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1628 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1629 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1631 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1634 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1635 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1639 SetLastError( ERROR_OUTOFMEMORY );
1642 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1643 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1644 flags, startup, info, unixdir, NULL, NULL );
1645 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1650 /***********************************************************************
1651 * create_cmd_process
1653 * Create a new cmd shell process for a .BAT file.
1655 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1656 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1657 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1658 LPPROCESS_INFORMATION info )
1661 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1662 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1663 WCHAR comspec[MAX_PATH];
1667 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1669 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1670 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1673 strcpyW( newcmdline, comspec );
1674 strcatW( newcmdline, slashcW );
1675 strcatW( newcmdline, cmd_line );
1676 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1677 flags, env, cur_dir, startup, info );
1678 HeapFree( GetProcessHeap(), 0, newcmdline );
1683 /*************************************************************************
1686 * Helper for CreateProcess: retrieve the file name to load from the
1687 * app name and command line. Store the file name in buffer, and
1688 * return a possibly modified command line.
1689 * Also returns a handle to the opened file if it's a Windows binary.
1691 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1692 int buflen, HANDLE *handle )
1694 static const WCHAR quotesW[] = {'"','%','s','"',0};
1696 WCHAR *name, *pos, *ret = NULL;
1699 /* if we have an app name, everything is easy */
1703 /* use the unmodified app name as file name */
1704 lstrcpynW( buffer, appname, buflen );
1705 *handle = open_exe_file( buffer );
1706 if (!(ret = cmdline) || !cmdline[0])
1708 /* no command-line, create one */
1709 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1710 sprintfW( ret, quotesW, appname );
1717 SetLastError( ERROR_INVALID_PARAMETER );
1721 /* first check for a quoted file name */
1723 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1725 int len = p - cmdline - 1;
1726 /* extract the quoted portion as file name */
1727 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1728 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1731 if (find_exe_file( name, buffer, buflen, handle ))
1732 ret = cmdline; /* no change necessary */
1736 /* now try the command-line word by word */
1738 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1745 do *pos++ = *p++; while (*p && *p != ' ');
1747 if (find_exe_file( name, buffer, buflen, handle ))
1754 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1756 /* now build a new command-line with quotes */
1758 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1760 sprintfW( ret, quotesW, name );
1764 HeapFree( GetProcessHeap(), 0, name );
1769 /**********************************************************************
1770 * CreateProcessA (KERNEL32.@)
1772 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1773 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1774 DWORD flags, LPVOID env, LPCSTR cur_dir,
1775 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1778 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1779 UNICODE_STRING desktopW, titleW;
1782 desktopW.Buffer = NULL;
1783 titleW.Buffer = NULL;
1784 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1785 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1786 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1788 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1789 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1791 memcpy( &infoW, startup_info, sizeof(infoW) );
1792 infoW.lpDesktop = desktopW.Buffer;
1793 infoW.lpTitle = titleW.Buffer;
1795 if (startup_info->lpReserved)
1796 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1797 debugstr_a(startup_info->lpReserved));
1799 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1800 inherit, flags, env, cur_dirW, &infoW, info );
1802 HeapFree( GetProcessHeap(), 0, app_nameW );
1803 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1804 HeapFree( GetProcessHeap(), 0, cur_dirW );
1805 RtlFreeUnicodeString( &desktopW );
1806 RtlFreeUnicodeString( &titleW );
1811 /**********************************************************************
1812 * CreateProcessW (KERNEL32.@)
1814 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1815 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1816 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1817 LPPROCESS_INFORMATION info )
1821 char *unixdir = NULL;
1822 WCHAR name[MAX_PATH];
1823 WCHAR *tidy_cmdline, *p, *envW = env;
1824 void *res_start, *res_end;
1826 /* Process the AppName and/or CmdLine to get module name and path */
1828 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1830 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1832 if (hFile == INVALID_HANDLE_VALUE) goto done;
1834 /* Warn if unsupported features are used */
1836 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1837 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1838 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1839 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1840 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1844 unixdir = wine_get_unix_file_name( cur_dir );
1848 WCHAR buf[MAX_PATH];
1849 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1852 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1857 while (*p) p += strlen(p) + 1;
1858 p++; /* final null */
1859 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1860 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1861 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1862 flags |= CREATE_UNICODE_ENVIRONMENT;
1865 info->hThread = info->hProcess = 0;
1866 info->dwProcessId = info->dwThreadId = 0;
1868 /* Determine executable type */
1870 if (!hFile) /* builtin exe */
1872 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1873 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1874 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1878 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1881 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1882 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1883 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1888 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1889 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1890 inherit, flags, startup_info, info, unixdir );
1893 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1894 SetLastError( ERROR_BAD_EXE_FORMAT );
1896 case BINARY_UNIX_LIB:
1897 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1898 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1899 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1901 case BINARY_UNKNOWN:
1902 /* check for .com or .bat extension */
1903 if ((p = strrchrW( name, '.' )))
1905 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1907 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1908 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1909 inherit, flags, startup_info, info, unixdir );
1912 if (!strcmpiW( p, batW ))
1914 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1915 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1916 inherit, flags, startup_info, info );
1921 case BINARY_UNIX_EXE:
1923 /* unknown file, try as unix executable */
1926 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1928 if ((unix_name = wine_get_unix_file_name( name )))
1930 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1931 HeapFree( GetProcessHeap(), 0, unix_name );
1936 CloseHandle( hFile );
1939 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1940 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1941 HeapFree( GetProcessHeap(), 0, unixdir );
1946 /***********************************************************************
1949 * Wrapper to call WaitForInputIdle USER function
1951 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1953 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1955 HMODULE mod = GetModuleHandleA( "user32.dll" );
1958 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1959 if (ptr) return ptr( process, timeout );
1965 /***********************************************************************
1966 * WinExec (KERNEL32.@)
1968 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1970 PROCESS_INFORMATION info;
1971 STARTUPINFOA startup;
1975 memset( &startup, 0, sizeof(startup) );
1976 startup.cb = sizeof(startup);
1977 startup.dwFlags = STARTF_USESHOWWINDOW;
1978 startup.wShowWindow = nCmdShow;
1980 /* cmdline needs to be writeable for CreateProcess */
1981 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1982 strcpy( cmdline, lpCmdLine );
1984 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1985 0, NULL, NULL, &startup, &info ))
1987 /* Give 30 seconds to the app to come up */
1988 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1989 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1991 /* Close off the handles */
1992 CloseHandle( info.hThread );
1993 CloseHandle( info.hProcess );
1995 else if ((ret = GetLastError()) >= 32)
1997 FIXME("Strange error set by CreateProcess: %d\n", ret );
2000 HeapFree( GetProcessHeap(), 0, cmdline );
2005 /**********************************************************************
2006 * LoadModule (KERNEL32.@)
2008 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2010 LOADPARMS32 *params = paramBlock;
2011 PROCESS_INFORMATION info;
2012 STARTUPINFOA startup;
2013 HINSTANCE hInstance;
2015 char filename[MAX_PATH];
2018 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2020 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2021 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2022 return (HINSTANCE)GetLastError();
2024 len = (BYTE)params->lpCmdLine[0];
2025 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2026 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2028 strcpy( cmdline, filename );
2029 p = cmdline + strlen(cmdline);
2031 memcpy( p, params->lpCmdLine + 1, len );
2034 memset( &startup, 0, sizeof(startup) );
2035 startup.cb = sizeof(startup);
2036 if (params->lpCmdShow)
2038 startup.dwFlags = STARTF_USESHOWWINDOW;
2039 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2042 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2043 params->lpEnvAddress, NULL, &startup, &info ))
2045 /* Give 30 seconds to the app to come up */
2046 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2047 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2048 hInstance = (HINSTANCE)33;
2049 /* Close off the handles */
2050 CloseHandle( info.hThread );
2051 CloseHandle( info.hProcess );
2053 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2055 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2056 hInstance = (HINSTANCE)11;
2059 HeapFree( GetProcessHeap(), 0, cmdline );
2064 /******************************************************************************
2065 * TerminateProcess (KERNEL32.@)
2067 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2069 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2070 if (status) SetLastError( RtlNtStatusToDosError(status) );
2075 /***********************************************************************
2076 * ExitProcess (KERNEL32.@)
2078 void WINAPI ExitProcess( DWORD status )
2080 LdrShutdownProcess();
2081 SERVER_START_REQ( terminate_process )
2083 /* send the exit code to the server */
2084 req->handle = GetCurrentProcess();
2085 req->exit_code = status;
2086 wine_server_call( req );
2093 /***********************************************************************
2094 * GetExitCodeProcess [KERNEL32.@]
2096 * Gets termination status of specified process
2102 BOOL WINAPI GetExitCodeProcess(
2103 HANDLE hProcess, /* [in] handle to the process */
2104 LPDWORD lpExitCode) /* [out] address to receive termination status */
2107 PROCESS_BASIC_INFORMATION pbi;
2109 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2111 if (status == STATUS_SUCCESS)
2113 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2116 SetLastError( RtlNtStatusToDosError(status) );
2121 /***********************************************************************
2122 * SetErrorMode (KERNEL32.@)
2124 UINT WINAPI SetErrorMode( UINT mode )
2126 UINT old = process_error_mode;
2127 process_error_mode = mode;
2132 /**********************************************************************
2133 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2135 * Allocates a thread local storage index
2138 * Success: TLS Index
2139 * Failure: 0xFFFFFFFF
2141 DWORD WINAPI TlsAlloc( void )
2144 PEB * const peb = NtCurrentTeb()->Peb;
2146 RtlAcquirePebLock();
2147 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2148 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2151 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2154 if (!NtCurrentTeb()->TlsExpansionSlots &&
2155 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2156 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2158 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2160 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2164 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2165 index += TLS_MINIMUM_AVAILABLE;
2168 else SetLastError( ERROR_NO_MORE_ITEMS );
2170 RtlReleasePebLock();
2175 /**********************************************************************
2176 * TlsFree [KERNEL32.@] Releases a TLS index.
2178 * Releases a thread local storage index, making it available for reuse
2184 BOOL WINAPI TlsFree(
2185 DWORD index) /* [in] TLS Index to free */
2189 RtlAcquirePebLock();
2190 if (index >= TLS_MINIMUM_AVAILABLE)
2192 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2193 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2197 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2198 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2200 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2201 else SetLastError( ERROR_INVALID_PARAMETER );
2202 RtlReleasePebLock();
2207 /**********************************************************************
2208 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2211 * Success: Value stored in calling thread's TLS slot for index
2212 * Failure: 0 and GetLastError() returns NO_ERROR
2214 LPVOID WINAPI TlsGetValue(
2215 DWORD index) /* [in] TLS index to retrieve value for */
2219 if (index < TLS_MINIMUM_AVAILABLE)
2221 ret = NtCurrentTeb()->TlsSlots[index];
2225 index -= TLS_MINIMUM_AVAILABLE;
2226 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2228 SetLastError( ERROR_INVALID_PARAMETER );
2231 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2232 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2234 SetLastError( ERROR_SUCCESS );
2239 /**********************************************************************
2240 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2246 BOOL WINAPI TlsSetValue(
2247 DWORD index, /* [in] TLS index to set value for */
2248 LPVOID value) /* [in] Value to be stored */
2250 if (index < TLS_MINIMUM_AVAILABLE)
2252 NtCurrentTeb()->TlsSlots[index] = value;
2256 index -= TLS_MINIMUM_AVAILABLE;
2257 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2259 SetLastError( ERROR_INVALID_PARAMETER );
2262 if (!NtCurrentTeb()->TlsExpansionSlots &&
2263 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2264 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2266 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2269 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2275 /***********************************************************************
2276 * GetProcessFlags (KERNEL32.@)
2278 DWORD WINAPI GetProcessFlags( DWORD processid )
2280 IMAGE_NT_HEADERS *nt;
2283 if (processid && processid != GetCurrentProcessId()) return 0;
2285 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2287 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2288 flags |= PDB32_CONSOLE_PROC;
2290 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2291 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2296 /***********************************************************************
2297 * GetProcessDword (KERNEL.485)
2298 * GetProcessDword (KERNEL32.18)
2299 * 'Of course you cannot directly access Windows internal structures'
2301 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2306 TRACE("(%ld, %d)\n", dwProcessID, offset );
2308 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2310 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2316 case GPD_APP_COMPAT_FLAGS:
2317 return GetAppCompatFlags16(0);
2318 case GPD_LOAD_DONE_EVENT:
2320 case GPD_HINSTANCE16:
2321 return GetTaskDS16();
2322 case GPD_WINDOWS_VERSION:
2323 return GetExeVersion16();
2325 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2327 return (DWORD)NtCurrentTeb()->Peb;
2328 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2329 GetStartupInfoW(&siw);
2330 return (DWORD)siw.hStdOutput;
2331 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2332 GetStartupInfoW(&siw);
2333 return (DWORD)siw.hStdInput;
2334 case GPD_STARTF_SHOWWINDOW:
2335 GetStartupInfoW(&siw);
2336 return siw.wShowWindow;
2337 case GPD_STARTF_SIZE:
2338 GetStartupInfoW(&siw);
2340 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2342 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2343 return MAKELONG( x, y );
2344 case GPD_STARTF_POSITION:
2345 GetStartupInfoW(&siw);
2347 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2349 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2350 return MAKELONG( x, y );
2351 case GPD_STARTF_FLAGS:
2352 GetStartupInfoW(&siw);
2357 return GetProcessFlags(0);
2359 return process_dword;
2361 ERR("Unknown offset %d\n", offset );
2366 /***********************************************************************
2367 * SetProcessDword (KERNEL.484)
2368 * 'Of course you cannot directly access Windows internal structures'
2370 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2372 TRACE("(%ld, %d)\n", dwProcessID, offset );
2374 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2376 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2382 case GPD_APP_COMPAT_FLAGS:
2383 case GPD_LOAD_DONE_EVENT:
2384 case GPD_HINSTANCE16:
2385 case GPD_WINDOWS_VERSION:
2388 case GPD_STARTF_SHELLDATA:
2389 case GPD_STARTF_HOTKEY:
2390 case GPD_STARTF_SHOWWINDOW:
2391 case GPD_STARTF_SIZE:
2392 case GPD_STARTF_POSITION:
2393 case GPD_STARTF_FLAGS:
2396 ERR("Not allowed to modify offset %d\n", offset );
2399 process_dword = value;
2402 ERR("Unknown offset %d\n", offset );
2408 /***********************************************************************
2409 * ExitProcess (KERNEL.466)
2411 void WINAPI ExitProcess16( WORD status )
2414 ReleaseThunkLock( &count );
2415 ExitProcess( status );
2419 /*********************************************************************
2420 * OpenProcess (KERNEL32.@)
2422 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2426 OBJECT_ATTRIBUTES attr;
2429 cid.UniqueProcess = (HANDLE)id;
2430 cid.UniqueThread = 0; /* FIXME ? */
2432 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2433 attr.RootDirectory = NULL;
2434 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2435 attr.SecurityDescriptor = NULL;
2436 attr.SecurityQualityOfService = NULL;
2437 attr.ObjectName = NULL;
2439 status = NtOpenProcess(&handle, access, &attr, &cid);
2440 if (status != STATUS_SUCCESS)
2442 SetLastError( RtlNtStatusToDosError(status) );
2449 /*********************************************************************
2450 * MapProcessHandle (KERNEL.483)
2451 * GetProcessId (KERNEL32.@)
2453 DWORD WINAPI GetProcessId( HANDLE hProcess )
2456 PROCESS_BASIC_INFORMATION pbi;
2458 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2460 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2461 SetLastError( RtlNtStatusToDosError(status) );
2466 /*********************************************************************
2467 * CloseW32Handle (KERNEL.474)
2468 * CloseHandle (KERNEL32.@)
2470 BOOL WINAPI CloseHandle( HANDLE handle )
2474 /* stdio handles need special treatment */
2475 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2476 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2477 (handle == (HANDLE)STD_ERROR_HANDLE))
2478 handle = GetStdHandle( (DWORD)handle );
2480 if (is_console_handle(handle))
2481 return CloseConsoleHandle(handle);
2483 status = NtClose( handle );
2484 if (status) SetLastError( RtlNtStatusToDosError(status) );
2489 /*********************************************************************
2490 * GetHandleInformation (KERNEL32.@)
2492 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2495 SERVER_START_REQ( set_handle_info )
2497 req->handle = handle;
2501 ret = !wine_server_call_err( req );
2502 if (ret && flags) *flags = reply->old_flags;
2509 /*********************************************************************
2510 * SetHandleInformation (KERNEL32.@)
2512 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2515 SERVER_START_REQ( set_handle_info )
2517 req->handle = handle;
2521 ret = !wine_server_call_err( req );
2528 /*********************************************************************
2529 * DuplicateHandle (KERNEL32.@)
2531 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2532 HANDLE dest_process, HANDLE *dest,
2533 DWORD access, BOOL inherit, DWORD options )
2537 if (is_console_handle(source))
2539 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2540 if (source_process != dest_process ||
2541 source_process != GetCurrentProcess())
2543 SetLastError(ERROR_INVALID_PARAMETER);
2546 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2547 return (*dest != INVALID_HANDLE_VALUE);
2549 status = NtDuplicateObject( source_process, source, dest_process, dest,
2550 access, inherit ? OBJ_INHERIT : 0, options );
2551 if (status) SetLastError( RtlNtStatusToDosError(status) );
2556 /***********************************************************************
2557 * ConvertToGlobalHandle (KERNEL.476)
2558 * ConvertToGlobalHandle (KERNEL32.@)
2560 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2562 HANDLE ret = INVALID_HANDLE_VALUE;
2563 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2564 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2569 /***********************************************************************
2570 * SetHandleContext (KERNEL32.@)
2572 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2574 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2575 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2576 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2581 /***********************************************************************
2582 * GetHandleContext (KERNEL32.@)
2584 DWORD WINAPI GetHandleContext(HANDLE hnd)
2586 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2587 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2588 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2593 /***********************************************************************
2594 * CreateSocketHandle (KERNEL32.@)
2596 HANDLE WINAPI CreateSocketHandle(void)
2598 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2599 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2600 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2601 return INVALID_HANDLE_VALUE;
2605 /***********************************************************************
2606 * SetPriorityClass (KERNEL32.@)
2608 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2611 SERVER_START_REQ( set_process_info )
2613 req->handle = hprocess;
2614 req->priority = priorityclass;
2615 req->mask = SET_PROCESS_INFO_PRIORITY;
2616 ret = !wine_server_call_err( req );
2623 /***********************************************************************
2624 * GetPriorityClass (KERNEL32.@)
2626 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2629 PROCESS_BASIC_INFORMATION pbi;
2631 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2633 if (status == STATUS_SUCCESS) return pbi.BasePriority;
2634 SetLastError( RtlNtStatusToDosError(status) );
2639 /***********************************************************************
2640 * SetProcessAffinityMask (KERNEL32.@)
2642 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2645 SERVER_START_REQ( set_process_info )
2647 req->handle = hProcess;
2648 req->affinity = affmask;
2649 req->mask = SET_PROCESS_INFO_AFFINITY;
2650 ret = !wine_server_call_err( req );
2657 /**********************************************************************
2658 * GetProcessAffinityMask (KERNEL32.@)
2660 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2661 LPDWORD lpProcessAffinityMask,
2662 LPDWORD lpSystemAffinityMask )
2665 SERVER_START_REQ( get_process_info )
2667 req->handle = hProcess;
2668 if (!wine_server_call_err( req ))
2670 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2671 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2680 /***********************************************************************
2681 * GetProcessVersion (KERNEL32.@)
2683 DWORD WINAPI GetProcessVersion( DWORD processid )
2685 IMAGE_NT_HEADERS *nt;
2687 if (processid && processid != GetCurrentProcessId())
2689 FIXME("should use ReadProcessMemory\n");
2692 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2693 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2694 nt->OptionalHeader.MinorSubsystemVersion);
2699 /***********************************************************************
2700 * SetProcessWorkingSetSize [KERNEL32.@]
2701 * Sets the min/max working set sizes for a specified process.
2704 * hProcess [I] Handle to the process of interest
2705 * minset [I] Specifies minimum working set size
2706 * maxset [I] Specifies maximum working set size
2712 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2715 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2716 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2717 /* Trim the working set to zero */
2718 /* Swap the process out of physical RAM */
2723 /***********************************************************************
2724 * GetProcessWorkingSetSize (KERNEL32.@)
2726 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2729 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2730 /* 32 MB working set size */
2731 if (minset) *minset = 32*1024*1024;
2732 if (maxset) *maxset = 32*1024*1024;
2737 /***********************************************************************
2738 * SetProcessShutdownParameters (KERNEL32.@)
2740 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2742 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2743 shutdown_flags = flags;
2744 shutdown_priority = level;
2749 /***********************************************************************
2750 * GetProcessShutdownParameters (KERNEL32.@)
2753 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2755 *lpdwLevel = shutdown_priority;
2756 *lpdwFlags = shutdown_flags;
2761 /***********************************************************************
2762 * GetProcessPriorityBoost (KERNEL32.@)
2764 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2766 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2768 /* Report that no boost is present.. */
2769 *pDisablePriorityBoost = FALSE;
2774 /***********************************************************************
2775 * SetProcessPriorityBoost (KERNEL32.@)
2777 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2779 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2780 /* Say we can do it. I doubt the program will notice that we don't. */
2785 /***********************************************************************
2786 * ReadProcessMemory (KERNEL32.@)
2788 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2789 SIZE_T *bytes_read )
2791 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2792 if (status) SetLastError( RtlNtStatusToDosError(status) );
2797 /***********************************************************************
2798 * WriteProcessMemory (KERNEL32.@)
2800 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2801 SIZE_T *bytes_written )
2803 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2804 if (status) SetLastError( RtlNtStatusToDosError(status) );
2809 /****************************************************************************
2810 * FlushInstructionCache (KERNEL32.@)
2812 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2815 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2816 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2817 if (status) SetLastError( RtlNtStatusToDosError(status) );
2822 /******************************************************************
2823 * GetProcessIoCounters (KERNEL32.@)
2825 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2829 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2830 ioc, sizeof(*ioc), NULL);
2831 if (status) SetLastError( RtlNtStatusToDosError(status) );
2835 /***********************************************************************
2836 * ProcessIdToSessionId (KERNEL32.@)
2837 * This function is available on Terminal Server 4SP4 and Windows 2000
2839 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2841 /* According to MSDN, if the calling process is not in a terminal
2842 * services environment, then the sessionid returned is zero.
2849 /***********************************************************************
2850 * RegisterServiceProcess (KERNEL.491)
2851 * RegisterServiceProcess (KERNEL32.@)
2853 * A service process calls this function to ensure that it continues to run
2854 * even after a user logged off.
2856 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2858 /* I don't think that Wine needs to do anything in this function */
2859 return 1; /* success */
2863 /***********************************************************************
2864 * GetCurrentProcess (KERNEL32.@)
2866 * Get a handle to the current process.
2872 * A handle representing the current process.
2874 #undef GetCurrentProcess
2875 HANDLE WINAPI GetCurrentProcess(void)
2877 return (HANDLE)0xffffffff;