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(server);
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 static unsigned int server_startticks;
69 int main_create_flags = 0;
70 HMODULE kernel32_handle = 0;
72 const WCHAR *DIR_Windows = NULL;
73 const WCHAR *DIR_System = NULL;
76 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
77 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
78 #define PDB32_DOS_PROC 0x0010 /* Dos process */
79 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
80 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
81 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
83 static const WCHAR comW[] = {'.','c','o','m',0};
84 static const WCHAR batW[] = {'.','b','a','t',0};
85 static const WCHAR pifW[] = {'.','p','i','f',0};
86 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
88 extern void SHELL_LoadRegistry(void);
89 extern void VOLUME_CreateDevices(void);
90 extern void VERSION_Init( const WCHAR *appname );
91 extern void LOCALE_Init(void);
93 /***********************************************************************
96 inline static int contains_path( LPCWSTR name )
98 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
102 /***********************************************************************
105 * Check if an environment variable needs to be handled specially when
106 * passed through the Unix environment (i.e. prefixed with "WINE").
108 inline static int is_special_env_var( const char *var )
110 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
111 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
112 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
113 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
117 /***************************************************************************
120 * Get the path of a builtin module when the native file does not exist.
122 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
125 UINT len = strlenW( DIR_System );
127 if (contains_path( libname ))
129 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
130 filename, &file_part ) > size * sizeof(WCHAR))
131 return FALSE; /* too long */
133 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
135 while (filename[len] == '\\') len++;
136 if (filename + len != file_part) return FALSE;
140 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
141 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
142 file_part = filename + len;
143 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
144 strcpyW( file_part, libname );
146 if (ext && !strchrW( file_part, '.' ))
148 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
149 return FALSE; /* too long */
150 strcatW( file_part, ext );
156 /***********************************************************************
157 * open_builtin_exe_file
159 * Open an exe file for a builtin exe.
161 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
162 int test_only, int *file_exists )
164 char exename[MAX_PATH];
168 if ((p = strrchrW( name, '/' ))) name = p + 1;
169 if ((p = strrchrW( name, '\\' ))) name = p + 1;
171 /* we don't want to depend on the current codepage here */
172 len = strlenW( name ) + 1;
173 if (len >= sizeof(exename)) return NULL;
174 for (i = 0; i < len; i++)
176 if (name[i] > 127) return NULL;
177 exename[i] = (char)name[i];
178 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
180 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
184 /***********************************************************************
187 * Open a specific exe file, taking load order into account.
188 * Returns the file handle or 0 for a builtin exe.
190 static HANDLE open_exe_file( const WCHAR *name )
192 enum loadorder_type loadorder[LOADORDER_NTYPES];
193 WCHAR buffer[MAX_PATH];
197 TRACE("looking for %s\n", debugstr_w(name) );
199 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
200 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
202 /* file doesn't exist, check for builtin */
203 if (!contains_path( name )) goto error;
204 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
208 MODULE_GetLoadOrderW( loadorder, NULL, name );
210 for(i = 0; i < LOADORDER_NTYPES; i++)
212 if (loadorder[i] == LOADORDER_INVALID) break;
216 TRACE( "Trying native exe %s\n", debugstr_w(name) );
217 if (handle != INVALID_HANDLE_VALUE) return handle;
220 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
221 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
224 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
231 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
234 SetLastError( ERROR_FILE_NOT_FOUND );
235 return INVALID_HANDLE_VALUE;
239 /***********************************************************************
242 * Open an exe file, and return the full name and file handle.
243 * Returns FALSE if file could not be found.
244 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
245 * If file is a builtin exe, returns TRUE and sets handle to 0.
247 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
249 static const WCHAR exeW[] = {'.','e','x','e',0};
251 enum loadorder_type loadorder[LOADORDER_NTYPES];
254 TRACE("looking for %s\n", debugstr_w(name) );
256 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
257 !get_builtin_path( name, exeW, buffer, buflen ))
259 /* no builtin found, try native without extension in case it is a Unix app */
261 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
263 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
264 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
265 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
271 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
273 for(i = 0; i < LOADORDER_NTYPES; i++)
275 if (loadorder[i] == LOADORDER_INVALID) break;
279 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
280 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
281 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
283 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
286 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
287 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
298 SetLastError( ERROR_FILE_NOT_FOUND );
303 /**********************************************************************
306 * Load a PE format EXE file.
308 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
311 FILE_FS_DEVICE_INFORMATION device_info;
312 IMAGE_NT_HEADERS *nt;
315 OBJECT_ATTRIBUTES attr;
319 attr.Length = sizeof(attr);
320 attr.RootDirectory = 0;
321 attr.ObjectName = NULL;
323 attr.SecurityDescriptor = NULL;
324 attr.SecurityQualityOfService = NULL;
327 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
328 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
332 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
333 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
339 nt = RtlImageNtHeader( module );
340 if (nt->OptionalHeader.AddressOfEntryPoint)
342 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
343 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
344 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
345 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
348 if (NtQueryVolumeInformationFile( file, &io, &device_info, sizeof(device_info),
349 FileFsDeviceInformation ) == STATUS_SUCCESS)
351 /* don't keep the file handle open on removable media */
352 if (device_info.Characteristics & FILE_REMOVABLE_MEDIA)
354 CloseHandle( main_exe_file );
362 /***********************************************************************
363 * build_initial_environment
365 * Build the Win32 environment from the Unix environment
367 static BOOL build_initial_environment( char **environ )
374 /* Compute the total size of the Unix environment */
375 for (e = environ; *e; e++)
377 if (is_special_env_var( *e )) continue;
378 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
380 size *= sizeof(WCHAR);
382 /* Now allocate the environment */
384 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
385 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
388 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
389 endptr = p + size / sizeof(WCHAR);
391 /* And fill it with the Unix environment */
392 for (e = environ; *e; e++)
396 /* skip Unix special variables and use the Wine variants instead */
397 if (!strncmp( str, "WINE", 4 ))
399 if (is_special_env_var( str + 4 )) str += 4;
400 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
402 else if (is_special_env_var( str )) continue; /* skip it */
404 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
412 /***********************************************************************
413 * set_registry_variables
415 * Set environment variables by enumerating the values of a key;
416 * helper for set_registry_environment().
417 * Note that Windows happily truncates the value if it's too big.
419 static void set_registry_variables( HKEY hkey, ULONG type )
421 UNICODE_STRING env_name, env_value;
425 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
426 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
428 for (index = 0; ; index++)
430 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
431 buffer, sizeof(buffer), &size );
432 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
434 if (info->Type != type)
436 env_name.Buffer = info->Name;
437 env_name.Length = env_name.MaximumLength = info->NameLength;
438 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
439 env_value.Length = env_value.MaximumLength = info->DataLength;
440 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
441 env_value.Length--; /* don't count terminating null if any */
442 if (info->Type == REG_EXPAND_SZ)
444 WCHAR buf_expanded[1024];
445 UNICODE_STRING env_expanded;
446 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
447 env_expanded.Buffer=buf_expanded;
448 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
449 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
450 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
454 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
460 /***********************************************************************
461 * set_registry_environment
463 * Set the environment variables specified in the registry.
465 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
466 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
467 * on the order in which the variables are processed. But on Windows it
468 * does not really matter since they only use %SystemDrive% and
469 * %SystemRoot% which are predefined. But Wine defines these in the
470 * registry, so we need two passes.
472 static void set_registry_environment(void)
474 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
475 'S','y','s','t','e','m','\\',
476 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
477 'C','o','n','t','r','o','l','\\',
478 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
479 'E','n','v','i','r','o','n','m','e','n','t',0};
480 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
482 OBJECT_ATTRIBUTES attr;
483 UNICODE_STRING nameW;
486 attr.Length = sizeof(attr);
487 attr.RootDirectory = 0;
488 attr.ObjectName = &nameW;
490 attr.SecurityDescriptor = NULL;
491 attr.SecurityQualityOfService = NULL;
493 /* first the system environment variables */
494 RtlInitUnicodeString( &nameW, env_keyW );
495 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
497 set_registry_variables( hkey, REG_SZ );
498 set_registry_variables( hkey, REG_EXPAND_SZ );
502 /* then the ones for the current user */
503 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, (HKEY *)&attr.RootDirectory ) != STATUS_SUCCESS) return;
504 RtlInitUnicodeString( &nameW, envW );
505 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
507 set_registry_variables( hkey, REG_SZ );
508 set_registry_variables( hkey, REG_EXPAND_SZ );
511 NtClose( attr.RootDirectory );
515 /***********************************************************************
518 * Set the Wine library Unicode argv global variables.
520 static void set_library_wargv( char **argv )
528 for (argc = 0; argv[argc]; argc++)
529 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
531 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
532 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
533 p = (WCHAR *)(wargv + argc + 1);
534 for (argc = 0; argv[argc]; argc++)
536 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
543 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
545 for (argc = 0; wargv[argc]; argc++)
546 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
548 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
549 q = (char *)(argv + argc + 1);
550 for (argc = 0; wargv[argc]; argc++)
552 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
559 __wine_main_argv = argv;
560 __wine_main_wargv = wargv;
564 /***********************************************************************
567 * Build the command line of a process from the argv array.
569 * Note that it does NOT necessarily include the file name.
570 * Sometimes we don't even have any command line options at all.
572 * We must quote and escape characters so that the argv array can be rebuilt
573 * from the command line:
574 * - spaces and tabs must be quoted
576 * - quotes must be escaped
578 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
579 * resulting in an odd number of '\' followed by a '"'
582 * - '\'s that are not followed by a '"' can be left as is
586 static BOOL build_command_line( WCHAR **argv )
591 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
593 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
596 for (arg = argv; *arg; arg++)
598 int has_space,bcount;
604 if( !*a ) has_space=1;
609 if (*a==' ' || *a=='\t') {
611 } else if (*a=='"') {
612 /* doubling of '\' preceding a '"',
613 * plus escaping of said '"'
621 len+=(a-*arg)+1 /* for the separating space */;
623 len+=2; /* for the quotes */
626 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
629 p = rupp->CommandLine.Buffer;
630 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
631 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
632 for (arg = argv; *arg; arg++)
634 int has_space,has_quote;
637 /* Check for quotes and spaces in this argument */
638 has_space=has_quote=0;
640 if( !*a ) has_space=1;
642 if (*a==' ' || *a=='\t') {
646 } else if (*a=='"') {
654 /* Now transfer it to the command line */
671 /* Double all the '\\' preceding this '"', plus one */
672 for (i=0;i<=bcount;i++)
684 while ((*p=*x++)) p++;
690 if (p > rupp->CommandLine.Buffer)
691 p--; /* remove last space */
698 /* make sure the unicode string doesn't point beyond the end pointer */
699 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
701 if ((char *)str->Buffer >= end_ptr)
703 str->Length = str->MaximumLength = 0;
707 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
709 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
711 if (str->Length >= str->MaximumLength)
713 if (str->MaximumLength >= sizeof(WCHAR))
714 str->Length = str->MaximumLength - sizeof(WCHAR);
716 str->Length = str->MaximumLength = 0;
720 static void version(void)
722 MESSAGE( "%s\n", PACKAGE_STRING );
726 static void usage(void)
728 MESSAGE( "%s\n", PACKAGE_STRING );
729 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
730 MESSAGE( " wine --help Display this help and exit\n");
731 MESSAGE( " wine --version Output version information and exit\n");
736 /***********************************************************************
737 * init_user_process_params
739 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
741 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
744 DWORD size, env_size;
745 RTL_USER_PROCESS_PARAMETERS *params;
749 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &size,
750 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
753 SERVER_START_REQ( get_startup_info )
755 wine_server_set_reply( req, ptr, info_size );
756 wine_server_call( req );
757 info_size = wine_server_reply_size( reply );
762 params->AllocationSize = size;
763 if (params->Size > info_size) params->Size = info_size;
765 /* make sure the strings are valid */
766 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
767 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
768 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
769 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
770 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
771 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
772 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
773 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
775 /* environment needs to be a separate memory block */
776 env_size = info_size - params->Size;
777 if (!env_size) env_size = 1;
779 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
780 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
782 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
783 params->Environment = ptr;
785 return RtlNormalizeProcessParams( params );
789 /***********************************************************************
790 * init_current_directory
792 * Initialize the current directory from the Unix cwd or the parent info.
794 static void init_current_directory( CURDIR *cur_dir )
796 UNICODE_STRING dir_str;
800 /* if we received a cur dir from the parent, try this first */
802 if (cur_dir->DosPath.Length)
804 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
807 /* now try to get it from the Unix cwd */
809 for (size = 256; ; size *= 2)
811 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
812 if (getcwd( cwd, size )) break;
813 HeapFree( GetProcessHeap(), 0, cwd );
814 if (errno == ERANGE) continue;
822 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
823 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
825 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
826 RtlInitUnicodeString( &dir_str, dirW );
827 RtlSetCurrentDirectory_U( &dir_str );
828 RtlFreeUnicodeString( &dir_str );
832 if (!cur_dir->DosPath.Length) /* still not initialized */
834 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
835 "starting in the Windows directory.\n", cwd ? cwd : "" );
836 RtlInitUnicodeString( &dir_str, DIR_Windows );
837 RtlSetCurrentDirectory_U( &dir_str );
839 HeapFree( GetProcessHeap(), 0, cwd );
842 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
843 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
847 /***********************************************************************
850 * Initialize the windows and system directories from the environment.
852 static void init_windows_dirs(void)
854 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
856 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
857 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
858 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
859 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m',0};
864 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
866 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
867 GetEnvironmentVariableW( windirW, buffer, len );
868 DIR_Windows = buffer;
870 else DIR_Windows = default_windirW;
872 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
874 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
875 GetEnvironmentVariableW( winsysdirW, buffer, len );
880 len = strlenW( DIR_Windows );
881 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
882 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
883 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
887 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
888 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
889 debugstr_w(DIR_Windows) );
890 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
891 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
892 debugstr_w(DIR_System) );
894 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
895 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
897 /* set the directories in ntdll too */
898 __wine_init_windows_dir( DIR_Windows, DIR_System );
902 /***********************************************************************
905 * Main process initialisation code
907 static BOOL process_init(void)
909 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
911 size_t info_size = 0;
912 RTL_USER_PROCESS_PARAMETERS *params;
913 PEB *peb = NtCurrentTeb()->Peb;
914 HANDLE hstdin, hstdout, hstderr;
915 extern void __wine_dbg_kernel32_init(void);
919 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
923 setlocale(LC_CTYPE,"");
925 /* Retrieve startup info from the server */
926 SERVER_START_REQ( init_process )
929 req->ldt_copy = &wine_ldt_copy;
930 if ((ret = !wine_server_call_err( req )))
932 main_exe_file = reply->exe_file;
933 main_create_flags = reply->create_flags;
934 info_size = reply->info_size;
935 server_startticks = reply->server_start;
936 hstdin = reply->hstdin;
937 hstdout = reply->hstdout;
938 hstderr = reply->hstderr;
942 if (!ret) return FALSE;
946 params = peb->ProcessParameters;
948 /* This is wine specific: we have no parent (we're started from unix)
949 * so, create a simple console with bare handles to unix stdio
950 * input & output streams (aka simple console)
952 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, ¶ms->hStdInput );
953 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdOutput );
954 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdError );
956 params->CurrentDirectory.DosPath.Length = 0;
957 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
958 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
962 if (!(params = init_user_process_params( info_size ))) return FALSE;
963 peb->ProcessParameters = params;
965 /* convert value from server:
966 * + 0 => INVALID_HANDLE_VALUE
967 * + console handle need to be mapped
970 hstdin = INVALID_HANDLE_VALUE;
971 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
972 hstdin = console_handle_map(hstdin);
975 hstdout = INVALID_HANDLE_VALUE;
976 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
977 hstdout = console_handle_map(hstdout);
980 hstderr = INVALID_HANDLE_VALUE;
981 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
982 hstderr = console_handle_map(hstderr);
984 params->hStdInput = hstdin;
985 params->hStdOutput = hstdout;
986 params->hStdError = hstderr;
989 kernel32_handle = GetModuleHandleW(kernel32W);
995 /* Copy the parent environment */
996 if (!build_initial_environment( __wine_main_environ )) return FALSE;
998 /* Create device symlinks */
999 VOLUME_CreateDevices();
1001 /* registry initialisation */
1002 SHELL_LoadRegistry();
1004 /* global boot finished, the rest is process-local */
1005 SERVER_START_REQ( boot_done )
1007 req->debug_level = TRACE_ON(server);
1008 wine_server_call( req );
1012 set_registry_environment();
1015 init_windows_dirs();
1016 init_current_directory( ¶ms->CurrentDirectory );
1022 /***********************************************************************
1025 * Startup routine of a new process. Runs on the new process stack.
1027 static void start_process( void *arg )
1031 PEB *peb = NtCurrentTeb()->Peb;
1032 IMAGE_NT_HEADERS *nt;
1033 LPTHREAD_START_ROUTINE entry;
1035 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
1037 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1038 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1039 nt->OptionalHeader.AddressOfEntryPoint);
1041 if (TRACE_ON(relay))
1042 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1043 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1045 SetLastError( 0 ); /* clear error code */
1046 if (peb->BeingDebugged) DbgBreakPoint();
1047 ExitProcess( entry( peb ) );
1049 __EXCEPT(UnhandledExceptionFilter)
1051 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1057 /***********************************************************************
1058 * __wine_kernel_init
1060 * Wine initialisation: load and start the main exe file.
1062 void __wine_kernel_init(void)
1064 WCHAR *main_exe_name, *p;
1066 DWORD stack_size = 0;
1068 PEB *peb = NtCurrentTeb()->Peb;
1070 /* Initialize everything */
1071 if (!process_init()) exit(1);
1073 __wine_main_argv++; /* remove argv[0] (wine itself) */
1076 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1078 WCHAR buffer[MAX_PATH];
1079 WCHAR exe_nameW[MAX_PATH];
1081 if (!__wine_main_argv[0]) usage();
1082 if (__wine_main_argc == 1)
1084 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1085 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1088 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1089 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1091 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1094 if (main_exe_file == INVALID_HANDLE_VALUE)
1096 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1099 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1100 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1103 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1104 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1106 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1107 MODULE_get_dll_load_path(NULL) );
1108 VERSION_Init( main_exe_name );
1110 if (!main_exe_file) /* no file handle -> Winelib app */
1112 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1113 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1115 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1116 debugstr_w(main_exe_name), error );
1120 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1123 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1124 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1126 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1129 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1131 case BINARY_UNKNOWN:
1132 /* check for .com extension */
1133 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1135 MESSAGE( "wine: cannot determine executable type for %s\n",
1136 debugstr_w(main_exe_name) );
1143 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1144 CloseHandle( main_exe_file );
1148 __wine_main_argv[0] = "winevdm.exe";
1149 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1151 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1152 debugstr_w(main_exe_name), error );
1154 case BINARY_UNIX_EXE:
1155 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1157 case BINARY_UNIX_LIB:
1161 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1162 CloseHandle( main_exe_file );
1164 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1165 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1167 static const WCHAR soW[] = {'.','s','o',0};
1168 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1171 /* update the unicode string */
1172 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1174 HeapFree( GetProcessHeap(), 0, unix_name );
1177 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1183 /* build command line */
1184 set_library_wargv( __wine_main_argv );
1185 if (!build_command_line( __wine_main_wargv )) goto error;
1187 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1189 /* allocate main thread stack */
1190 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1192 /* switch to the new stack */
1193 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1196 ExitProcess( GetLastError() );
1200 /***********************************************************************
1203 * Build an argv array from a command-line.
1204 * 'reserved' is the number of args to reserve before the first one.
1206 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1210 char *arg,*s,*d,*cmdline;
1211 int in_quotes,bcount,len;
1213 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1214 if (!(cmdline = malloc(len))) return NULL;
1215 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1222 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1225 /* skip the remaining spaces */
1226 while (*s==' ' || *s=='\t') {
1233 } else if (*s=='\\') {
1234 /* '\', count them */
1236 } else if ((*s=='"') && ((bcount & 1)==0)) {
1238 in_quotes=!in_quotes;
1241 /* a regular character */
1246 argv=malloc(argc*sizeof(*argv));
1255 if ((*s==' ' || *s=='\t') && !in_quotes) {
1256 /* Close the argument and copy it */
1260 /* skip the remaining spaces */
1263 } while (*s==' ' || *s=='\t');
1265 /* Start with a new argument */
1268 } else if (*s=='\\') {
1272 } else if (*s=='"') {
1274 if ((bcount & 1)==0) {
1275 /* Preceded by an even number of '\', this is half that
1276 * number of '\', plus a '"' which we discard.
1280 in_quotes=!in_quotes;
1282 /* Preceded by an odd number of '\', this is half that
1283 * number of '\' followed by a '"'
1291 /* a regular character */
1306 /***********************************************************************
1309 * Allocate an environment string; helper for build_envp
1311 static char *alloc_env_string( const char *name, const char *value )
1313 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1314 strcpy( ret, name );
1315 strcat( ret, value );
1319 /***********************************************************************
1322 * Build the environment of a new child process.
1324 static char **build_envp( const WCHAR *envW )
1329 int count = 0, length;
1331 for (end = envW; *end; count++) end += strlenW(end) + 1;
1333 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1334 if (!(env = malloc( length ))) return NULL;
1335 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1339 if ((envp = malloc( count * sizeof(*envp) )))
1341 char **envptr = envp;
1343 /* some variables must not be modified, so we get them directly from the unix env */
1344 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1345 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1346 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1347 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1348 /* now put the Windows environment strings */
1349 for (p = env; *p; p += strlen(p) + 1)
1351 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1352 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1353 if (is_special_env_var( p )) /* prefix it with "WINE" */
1354 *envptr++ = alloc_env_string( "WINE", p );
1364 /***********************************************************************
1367 * Fork and exec a new Unix binary, checking for errors.
1369 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1370 const WCHAR *env, const char *newdir )
1375 if (!env) env = GetEnvironmentStringsW();
1379 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1382 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1383 if (!(pid = fork())) /* child */
1385 char **argv = build_argv( cmdline, 0 );
1386 char **envp = build_envp( env );
1389 /* Reset signals that we previously set to SIG_IGN */
1390 signal( SIGPIPE, SIG_DFL );
1391 signal( SIGCHLD, SIG_DFL );
1393 if (newdir) chdir(newdir);
1395 if (argv && envp) execve( filename, argv, envp );
1397 write( fd[1], &err, sizeof(err) );
1401 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1406 if (pid == -1) FILE_SetDosError();
1412 /***********************************************************************
1413 * create_user_params
1415 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1416 LPCWSTR cur_dir, LPWSTR env,
1417 const STARTUPINFOW *startup )
1419 RTL_USER_PROCESS_PARAMETERS *params;
1420 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1422 WCHAR buffer[MAX_PATH];
1424 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1425 lstrcpynW( buffer, filename, MAX_PATH );
1426 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1427 lstrcpynW( buffer, filename, MAX_PATH );
1428 RtlInitUnicodeString( &image_str, buffer );
1430 RtlInitUnicodeString( &cmdline_str, cmdline );
1431 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1432 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1433 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1434 if (startup->lpReserved2 && startup->cbReserved2)
1437 runtime.MaximumLength = startup->cbReserved2;
1438 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1441 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1442 cur_dir ? &curdir_str : NULL,
1444 startup->lpTitle ? &title : NULL,
1445 startup->lpDesktop ? &desktop : NULL,
1447 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1448 if (status != STATUS_SUCCESS)
1450 SetLastError( RtlNtStatusToDosError(status) );
1454 params->hStdInput = startup->hStdInput;
1455 params->hStdOutput = startup->hStdOutput;
1456 params->hStdError = startup->hStdError;
1457 params->dwX = startup->dwX;
1458 params->dwY = startup->dwY;
1459 params->dwXSize = startup->dwXSize;
1460 params->dwYSize = startup->dwYSize;
1461 params->dwXCountChars = startup->dwXCountChars;
1462 params->dwYCountChars = startup->dwYCountChars;
1463 params->dwFillAttribute = startup->dwFillAttribute;
1464 params->dwFlags = startup->dwFlags;
1465 params->wShowWindow = startup->wShowWindow;
1470 /***********************************************************************
1473 * Create a new process. If hFile is a valid handle we have an exe
1474 * file, otherwise it is a Winelib app.
1476 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1477 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1478 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1479 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1480 void *res_start, void *res_end )
1482 BOOL ret, success = FALSE;
1483 HANDLE process_info;
1485 RTL_USER_PROCESS_PARAMETERS *params;
1491 char preloader_reserve[64];
1493 if (!env) RtlAcquirePebLock();
1495 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, startup )))
1497 if (!env) RtlReleasePebLock();
1500 env_end = params->Environment;
1501 while (*env_end) env_end += strlenW(env_end) + 1;
1504 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1505 (unsigned long)res_start, (unsigned long)res_end, 0 );
1507 /* create the synchronization pipes */
1509 if (pipe( startfd ) == -1)
1511 if (!env) RtlReleasePebLock();
1512 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1513 RtlDestroyProcessParameters( params );
1516 if (pipe( execfd ) == -1)
1518 if (!env) RtlReleasePebLock();
1519 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1520 close( startfd[0] );
1521 close( startfd[1] );
1522 RtlDestroyProcessParameters( params );
1525 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1527 /* create the child process */
1529 if (!(pid = fork())) /* child */
1531 char **argv = build_argv( cmd_line, 1 );
1533 close( startfd[1] );
1536 /* wait for parent to tell us to start */
1537 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1539 close( startfd[0] );
1540 /* Reset signals that we previously set to SIG_IGN */
1541 signal( SIGPIPE, SIG_DFL );
1542 signal( SIGCHLD, SIG_DFL );
1544 putenv( preloader_reserve );
1545 if (unixdir) chdir(unixdir);
1549 /* first, try for a WINELOADER environment variable */
1550 const char *loader = getenv("WINELOADER");
1551 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1552 /* now use the standard search strategy */
1553 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1556 write( execfd[1], &err, sizeof(err) );
1560 /* this is the parent */
1562 close( startfd[0] );
1566 if (!env) RtlReleasePebLock();
1567 close( startfd[1] );
1570 RtlDestroyProcessParameters( params );
1574 /* create the process on the server side */
1576 SERVER_START_REQ( new_process )
1578 req->inherit_all = inherit;
1579 req->create_flags = flags;
1580 req->unix_pid = pid;
1581 req->exe_file = hFile;
1582 if (startup->dwFlags & STARTF_USESTDHANDLES)
1584 req->hstdin = startup->hStdInput;
1585 req->hstdout = startup->hStdOutput;
1586 req->hstderr = startup->hStdError;
1590 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1591 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1592 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1595 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1597 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1598 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1599 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1600 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1604 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1605 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1606 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1609 wine_server_add_data( req, params, params->Size );
1610 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1611 ret = !wine_server_call_err( req );
1612 process_info = reply->info;
1616 if (!env) RtlReleasePebLock();
1617 RtlDestroyProcessParameters( params );
1620 close( startfd[1] );
1625 /* tell child to start and wait for it to exec */
1627 write( startfd[1], &dummy, 1 );
1628 close( startfd[1] );
1630 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1635 CloseHandle( process_info );
1640 /* wait for the new process info to be ready */
1642 WaitForSingleObject( process_info, INFINITE );
1643 SERVER_START_REQ( get_new_process_info )
1645 req->info = process_info;
1646 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1647 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1648 if ((ret = !wine_server_call_err( req )))
1650 info->dwProcessId = (DWORD)reply->pid;
1651 info->dwThreadId = (DWORD)reply->tid;
1652 info->hProcess = reply->phandle;
1653 info->hThread = reply->thandle;
1654 success = reply->success;
1659 if (ret && !success) /* new process failed to start */
1662 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1663 CloseHandle( info->hThread );
1664 CloseHandle( info->hProcess );
1667 CloseHandle( process_info );
1672 /***********************************************************************
1673 * create_vdm_process
1675 * Create a new VDM process for a 16-bit or DOS application.
1677 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1678 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1679 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1680 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1682 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1685 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1686 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1690 SetLastError( ERROR_OUTOFMEMORY );
1693 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1694 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1695 flags, startup, info, unixdir, NULL, NULL );
1696 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1701 /***********************************************************************
1702 * create_cmd_process
1704 * Create a new cmd shell process for a .BAT file.
1706 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1707 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1708 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1709 LPPROCESS_INFORMATION info )
1712 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1713 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1714 WCHAR comspec[MAX_PATH];
1718 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1720 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1721 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1724 strcpyW( newcmdline, comspec );
1725 strcatW( newcmdline, slashcW );
1726 strcatW( newcmdline, cmd_line );
1727 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1728 flags, env, cur_dir, startup, info );
1729 HeapFree( GetProcessHeap(), 0, newcmdline );
1734 /*************************************************************************
1737 * Helper for CreateProcess: retrieve the file name to load from the
1738 * app name and command line. Store the file name in buffer, and
1739 * return a possibly modified command line.
1740 * Also returns a handle to the opened file if it's a Windows binary.
1742 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1743 int buflen, HANDLE *handle )
1745 static const WCHAR quotesW[] = {'"','%','s','"',0};
1747 WCHAR *name, *pos, *ret = NULL;
1750 /* if we have an app name, everything is easy */
1754 /* use the unmodified app name as file name */
1755 lstrcpynW( buffer, appname, buflen );
1756 *handle = open_exe_file( buffer );
1757 if (!(ret = cmdline) || !cmdline[0])
1759 /* no command-line, create one */
1760 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1761 sprintfW( ret, quotesW, appname );
1768 SetLastError( ERROR_INVALID_PARAMETER );
1772 /* first check for a quoted file name */
1774 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1776 int len = p - cmdline - 1;
1777 /* extract the quoted portion as file name */
1778 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1779 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1782 if (find_exe_file( name, buffer, buflen, handle ))
1783 ret = cmdline; /* no change necessary */
1787 /* now try the command-line word by word */
1789 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1796 do *pos++ = *p++; while (*p && *p != ' ');
1798 if (find_exe_file( name, buffer, buflen, handle ))
1805 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1807 /* now build a new command-line with quotes */
1809 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1811 sprintfW( ret, quotesW, name );
1815 HeapFree( GetProcessHeap(), 0, name );
1820 /**********************************************************************
1821 * CreateProcessA (KERNEL32.@)
1823 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1824 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1825 DWORD flags, LPVOID env, LPCSTR cur_dir,
1826 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1829 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1830 UNICODE_STRING desktopW, titleW;
1833 desktopW.Buffer = NULL;
1834 titleW.Buffer = NULL;
1835 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1836 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1837 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1839 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1840 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1842 memcpy( &infoW, startup_info, sizeof(infoW) );
1843 infoW.lpDesktop = desktopW.Buffer;
1844 infoW.lpTitle = titleW.Buffer;
1846 if (startup_info->lpReserved)
1847 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1848 debugstr_a(startup_info->lpReserved));
1850 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1851 inherit, flags, env, cur_dirW, &infoW, info );
1853 HeapFree( GetProcessHeap(), 0, app_nameW );
1854 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1855 HeapFree( GetProcessHeap(), 0, cur_dirW );
1856 RtlFreeUnicodeString( &desktopW );
1857 RtlFreeUnicodeString( &titleW );
1862 /**********************************************************************
1863 * CreateProcessW (KERNEL32.@)
1865 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1866 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1867 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1868 LPPROCESS_INFORMATION info )
1872 char *unixdir = NULL;
1873 WCHAR name[MAX_PATH];
1874 WCHAR *tidy_cmdline, *p, *envW = env;
1875 void *res_start, *res_end;
1877 /* Process the AppName and/or CmdLine to get module name and path */
1879 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1881 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1883 if (hFile == INVALID_HANDLE_VALUE) goto done;
1885 /* Warn if unsupported features are used */
1887 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1888 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1889 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1890 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1891 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1895 unixdir = wine_get_unix_file_name( cur_dir );
1899 WCHAR buf[MAX_PATH];
1900 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1903 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1908 while (*p) p += strlen(p) + 1;
1909 p++; /* final null */
1910 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1911 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1912 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1913 flags |= CREATE_UNICODE_ENVIRONMENT;
1916 info->hThread = info->hProcess = 0;
1917 info->dwProcessId = info->dwThreadId = 0;
1919 /* Determine executable type */
1921 if (!hFile) /* builtin exe */
1923 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1924 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1925 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1929 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1932 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1933 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1934 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1939 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1940 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1941 inherit, flags, startup_info, info, unixdir );
1944 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1945 SetLastError( ERROR_BAD_EXE_FORMAT );
1947 case BINARY_UNIX_LIB:
1948 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1949 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1950 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1952 case BINARY_UNKNOWN:
1953 /* check for .com or .bat extension */
1954 if ((p = strrchrW( name, '.' )))
1956 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1958 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1959 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1960 inherit, flags, startup_info, info, unixdir );
1963 if (!strcmpiW( p, batW ))
1965 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1966 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1967 inherit, flags, startup_info, info );
1972 case BINARY_UNIX_EXE:
1974 /* unknown file, try as unix executable */
1977 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1979 if ((unix_name = wine_get_unix_file_name( name )))
1981 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1982 HeapFree( GetProcessHeap(), 0, unix_name );
1987 CloseHandle( hFile );
1990 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1991 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1992 HeapFree( GetProcessHeap(), 0, unixdir );
1997 /***********************************************************************
2000 * Wrapper to call WaitForInputIdle USER function
2002 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2004 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2006 HMODULE mod = GetModuleHandleA( "user32.dll" );
2009 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2010 if (ptr) return ptr( process, timeout );
2016 /***********************************************************************
2017 * WinExec (KERNEL32.@)
2019 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2021 PROCESS_INFORMATION info;
2022 STARTUPINFOA startup;
2026 memset( &startup, 0, sizeof(startup) );
2027 startup.cb = sizeof(startup);
2028 startup.dwFlags = STARTF_USESHOWWINDOW;
2029 startup.wShowWindow = nCmdShow;
2031 /* cmdline needs to be writeable for CreateProcess */
2032 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2033 strcpy( cmdline, lpCmdLine );
2035 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2036 0, NULL, NULL, &startup, &info ))
2038 /* Give 30 seconds to the app to come up */
2039 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2040 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2042 /* Close off the handles */
2043 CloseHandle( info.hThread );
2044 CloseHandle( info.hProcess );
2046 else if ((ret = GetLastError()) >= 32)
2048 FIXME("Strange error set by CreateProcess: %d\n", ret );
2051 HeapFree( GetProcessHeap(), 0, cmdline );
2056 /**********************************************************************
2057 * LoadModule (KERNEL32.@)
2059 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2061 LOADPARMS32 *params = paramBlock;
2062 PROCESS_INFORMATION info;
2063 STARTUPINFOA startup;
2064 HINSTANCE hInstance;
2066 char filename[MAX_PATH];
2069 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2071 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2072 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2073 return (HINSTANCE)GetLastError();
2075 len = (BYTE)params->lpCmdLine[0];
2076 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2077 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2079 strcpy( cmdline, filename );
2080 p = cmdline + strlen(cmdline);
2082 memcpy( p, params->lpCmdLine + 1, len );
2085 memset( &startup, 0, sizeof(startup) );
2086 startup.cb = sizeof(startup);
2087 if (params->lpCmdShow)
2089 startup.dwFlags = STARTF_USESHOWWINDOW;
2090 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2093 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2094 params->lpEnvAddress, NULL, &startup, &info ))
2096 /* Give 30 seconds to the app to come up */
2097 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2098 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2099 hInstance = (HINSTANCE)33;
2100 /* Close off the handles */
2101 CloseHandle( info.hThread );
2102 CloseHandle( info.hProcess );
2104 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2106 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2107 hInstance = (HINSTANCE)11;
2110 HeapFree( GetProcessHeap(), 0, cmdline );
2115 /******************************************************************************
2116 * TerminateProcess (KERNEL32.@)
2118 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2120 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2121 if (status) SetLastError( RtlNtStatusToDosError(status) );
2126 /***********************************************************************
2127 * ExitProcess (KERNEL32.@)
2129 void WINAPI ExitProcess( DWORD status )
2131 LdrShutdownProcess();
2132 SERVER_START_REQ( terminate_process )
2134 /* send the exit code to the server */
2135 req->handle = GetCurrentProcess();
2136 req->exit_code = status;
2137 wine_server_call( req );
2144 /***********************************************************************
2145 * GetExitCodeProcess [KERNEL32.@]
2147 * Gets termination status of specified process
2153 BOOL WINAPI GetExitCodeProcess(
2154 HANDLE hProcess, /* [in] handle to the process */
2155 LPDWORD lpExitCode) /* [out] address to receive termination status */
2158 PROCESS_BASIC_INFORMATION pbi;
2160 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2162 if (status == STATUS_SUCCESS)
2164 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2167 SetLastError( RtlNtStatusToDosError(status) );
2172 /***********************************************************************
2173 * SetErrorMode (KERNEL32.@)
2175 UINT WINAPI SetErrorMode( UINT mode )
2177 UINT old = process_error_mode;
2178 process_error_mode = mode;
2183 /**********************************************************************
2184 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2186 * Allocates a thread local storage index
2189 * Success: TLS Index
2190 * Failure: 0xFFFFFFFF
2192 DWORD WINAPI TlsAlloc( void )
2195 PEB * const peb = NtCurrentTeb()->Peb;
2197 RtlAcquirePebLock();
2198 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2199 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2202 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2205 if (!NtCurrentTeb()->TlsExpansionSlots &&
2206 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2207 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2209 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2211 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2215 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2216 index += TLS_MINIMUM_AVAILABLE;
2219 else SetLastError( ERROR_NO_MORE_ITEMS );
2221 RtlReleasePebLock();
2226 /**********************************************************************
2227 * TlsFree [KERNEL32.@] Releases a TLS index.
2229 * Releases a thread local storage index, making it available for reuse
2235 BOOL WINAPI TlsFree(
2236 DWORD index) /* [in] TLS Index to free */
2240 RtlAcquirePebLock();
2241 if (index >= TLS_MINIMUM_AVAILABLE)
2243 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2244 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2248 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2249 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2251 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2252 else SetLastError( ERROR_INVALID_PARAMETER );
2253 RtlReleasePebLock();
2258 /**********************************************************************
2259 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2262 * Success: Value stored in calling thread's TLS slot for index
2263 * Failure: 0 and GetLastError() returns NO_ERROR
2265 LPVOID WINAPI TlsGetValue(
2266 DWORD index) /* [in] TLS index to retrieve value for */
2270 if (index < TLS_MINIMUM_AVAILABLE)
2272 ret = NtCurrentTeb()->TlsSlots[index];
2276 index -= TLS_MINIMUM_AVAILABLE;
2277 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2279 SetLastError( ERROR_INVALID_PARAMETER );
2282 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2283 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2285 SetLastError( ERROR_SUCCESS );
2290 /**********************************************************************
2291 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2297 BOOL WINAPI TlsSetValue(
2298 DWORD index, /* [in] TLS index to set value for */
2299 LPVOID value) /* [in] Value to be stored */
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 )
2476 SERVER_START_REQ( open_process )
2479 req->access = access;
2480 req->inherit = inherit;
2481 if (!wine_server_call_err( req )) ret = reply->handle;
2488 /*********************************************************************
2489 * MapProcessHandle (KERNEL.483)
2490 * GetProcessId (KERNEL32.@)
2492 DWORD WINAPI GetProcessId( HANDLE hProcess )
2495 PROCESS_BASIC_INFORMATION pbi;
2497 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2499 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2500 SetLastError( RtlNtStatusToDosError(status) );
2505 /*********************************************************************
2506 * CloseW32Handle (KERNEL.474)
2507 * CloseHandle (KERNEL32.@)
2509 BOOL WINAPI CloseHandle( HANDLE handle )
2513 /* stdio handles need special treatment */
2514 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2515 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2516 (handle == (HANDLE)STD_ERROR_HANDLE))
2517 handle = GetStdHandle( (DWORD)handle );
2519 if (is_console_handle(handle))
2520 return CloseConsoleHandle(handle);
2522 status = NtClose( handle );
2523 if (status) SetLastError( RtlNtStatusToDosError(status) );
2528 /*********************************************************************
2529 * GetHandleInformation (KERNEL32.@)
2531 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2534 SERVER_START_REQ( set_handle_info )
2536 req->handle = handle;
2540 ret = !wine_server_call_err( req );
2541 if (ret && flags) *flags = reply->old_flags;
2548 /*********************************************************************
2549 * SetHandleInformation (KERNEL32.@)
2551 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2554 SERVER_START_REQ( set_handle_info )
2556 req->handle = handle;
2560 ret = !wine_server_call_err( req );
2567 /*********************************************************************
2568 * DuplicateHandle (KERNEL32.@)
2570 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2571 HANDLE dest_process, HANDLE *dest,
2572 DWORD access, BOOL inherit, DWORD options )
2576 if (is_console_handle(source))
2578 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2579 if (source_process != dest_process ||
2580 source_process != GetCurrentProcess())
2582 SetLastError(ERROR_INVALID_PARAMETER);
2585 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2586 return (*dest != INVALID_HANDLE_VALUE);
2588 status = NtDuplicateObject( source_process, source, dest_process, dest,
2589 access, inherit ? OBJ_INHERIT : 0, options );
2590 if (status) SetLastError( RtlNtStatusToDosError(status) );
2595 /***********************************************************************
2596 * ConvertToGlobalHandle (KERNEL.476)
2597 * ConvertToGlobalHandle (KERNEL32.@)
2599 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2601 HANDLE ret = INVALID_HANDLE_VALUE;
2602 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2603 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2608 /***********************************************************************
2609 * SetHandleContext (KERNEL32.@)
2611 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2613 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2614 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2615 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2620 /***********************************************************************
2621 * GetHandleContext (KERNEL32.@)
2623 DWORD WINAPI GetHandleContext(HANDLE hnd)
2625 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2626 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2627 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2632 /***********************************************************************
2633 * CreateSocketHandle (KERNEL32.@)
2635 HANDLE WINAPI CreateSocketHandle(void)
2637 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2638 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2639 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2640 return INVALID_HANDLE_VALUE;
2644 /***********************************************************************
2645 * SetPriorityClass (KERNEL32.@)
2647 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2650 SERVER_START_REQ( set_process_info )
2652 req->handle = hprocess;
2653 req->priority = priorityclass;
2654 req->mask = SET_PROCESS_INFO_PRIORITY;
2655 ret = !wine_server_call_err( req );
2662 /***********************************************************************
2663 * GetPriorityClass (KERNEL32.@)
2665 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2668 PROCESS_BASIC_INFORMATION pbi;
2670 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2672 if (status == STATUS_SUCCESS) return pbi.BasePriority;
2673 SetLastError( RtlNtStatusToDosError(status) );
2678 /***********************************************************************
2679 * SetProcessAffinityMask (KERNEL32.@)
2681 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2684 SERVER_START_REQ( set_process_info )
2686 req->handle = hProcess;
2687 req->affinity = affmask;
2688 req->mask = SET_PROCESS_INFO_AFFINITY;
2689 ret = !wine_server_call_err( req );
2696 /**********************************************************************
2697 * GetProcessAffinityMask (KERNEL32.@)
2699 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2700 LPDWORD lpProcessAffinityMask,
2701 LPDWORD lpSystemAffinityMask )
2704 SERVER_START_REQ( get_process_info )
2706 req->handle = hProcess;
2707 if (!wine_server_call_err( req ))
2709 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2710 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2719 /***********************************************************************
2720 * GetProcessVersion (KERNEL32.@)
2722 DWORD WINAPI GetProcessVersion( DWORD processid )
2724 IMAGE_NT_HEADERS *nt;
2726 if (processid && processid != GetCurrentProcessId())
2728 FIXME("should use ReadProcessMemory\n");
2731 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2732 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2733 nt->OptionalHeader.MinorSubsystemVersion);
2738 /***********************************************************************
2739 * SetProcessWorkingSetSize [KERNEL32.@]
2740 * Sets the min/max working set sizes for a specified process.
2743 * hProcess [I] Handle to the process of interest
2744 * minset [I] Specifies minimum working set size
2745 * maxset [I] Specifies maximum working set size
2751 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2754 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2755 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2756 /* Trim the working set to zero */
2757 /* Swap the process out of physical RAM */
2762 /***********************************************************************
2763 * GetProcessWorkingSetSize (KERNEL32.@)
2765 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2768 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2769 /* 32 MB working set size */
2770 if (minset) *minset = 32*1024*1024;
2771 if (maxset) *maxset = 32*1024*1024;
2776 /***********************************************************************
2777 * SetProcessShutdownParameters (KERNEL32.@)
2779 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2781 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2782 shutdown_flags = flags;
2783 shutdown_priority = level;
2788 /***********************************************************************
2789 * GetProcessShutdownParameters (KERNEL32.@)
2792 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2794 *lpdwLevel = shutdown_priority;
2795 *lpdwFlags = shutdown_flags;
2800 /***********************************************************************
2801 * GetProcessPriorityBoost (KERNEL32.@)
2803 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2805 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2807 /* Report that no boost is present.. */
2808 *pDisablePriorityBoost = FALSE;
2813 /***********************************************************************
2814 * SetProcessPriorityBoost (KERNEL32.@)
2816 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2818 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2819 /* Say we can do it. I doubt the program will notice that we don't. */
2824 /***********************************************************************
2825 * ReadProcessMemory (KERNEL32.@)
2827 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2828 SIZE_T *bytes_read )
2830 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2831 if (status) SetLastError( RtlNtStatusToDosError(status) );
2836 /***********************************************************************
2837 * WriteProcessMemory (KERNEL32.@)
2839 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2840 SIZE_T *bytes_written )
2842 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2843 if (status) SetLastError( RtlNtStatusToDosError(status) );
2848 /****************************************************************************
2849 * FlushInstructionCache (KERNEL32.@)
2851 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2854 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2855 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2856 if (status) SetLastError( RtlNtStatusToDosError(status) );
2861 /******************************************************************
2862 * GetProcessIoCounters (KERNEL32.@)
2864 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2868 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2869 ioc, sizeof(*ioc), NULL);
2870 if (status) SetLastError( RtlNtStatusToDosError(status) );
2874 /***********************************************************************
2875 * ProcessIdToSessionId (KERNEL32.@)
2876 * This function is available on Terminal Server 4SP4 and Windows 2000
2878 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2880 /* According to MSDN, if the calling process is not in a terminal
2881 * services environment, then the sessionid returned is zero.
2888 /***********************************************************************
2889 * RegisterServiceProcess (KERNEL.491)
2890 * RegisterServiceProcess (KERNEL32.@)
2892 * A service process calls this function to ensure that it continues to run
2893 * even after a user logged off.
2895 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2897 /* I don't think that Wine needs to do anything in this function */
2898 return 1; /* success */
2902 /***********************************************************************
2903 * GetSystemMSecCount (SYSTEM.6)
2904 * GetTickCount (KERNEL32.@)
2906 * Get the number of milliseconds the system has been running.
2912 * The current tick count.
2915 * -The value returned will wrap arounf every 2^32 milliseconds.
2916 * -Under Windows, tick 0 is the moment at which the system is rebooted.
2917 * Under Wine, tick 0 begins at the moment the wineserver process is started,
2919 DWORD WINAPI GetTickCount(void)
2922 gettimeofday( &t, NULL );
2923 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2927 /***********************************************************************
2928 * GetCurrentProcess (KERNEL32.@)
2930 * Get a handle to the current process.
2936 * A handle representing the current process.
2938 #undef GetCurrentProcess
2939 HANDLE WINAPI GetCurrentProcess(void)
2941 return (HANDLE)0xffffffff;