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"
41 #include "kernel_private.h"
42 #include "wine/exception.h"
43 #include "wine/server.h"
44 #include "wine/unicode.h"
45 #include "wine/debug.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(process);
48 WINE_DECLARE_DEBUG_CHANNEL(file);
49 WINE_DECLARE_DEBUG_CHANNEL(server);
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 static unsigned int server_startticks;
68 int main_create_flags = 0;
69 HMODULE kernel32_handle = 0;
71 const WCHAR *DIR_Windows = NULL;
72 const WCHAR *DIR_System = NULL;
75 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
76 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
77 #define PDB32_DOS_PROC 0x0010 /* Dos process */
78 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
79 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
80 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
82 static const WCHAR comW[] = {'.','c','o','m',0};
83 static const WCHAR batW[] = {'.','b','a','t',0};
84 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
86 extern void SHELL_LoadRegistry(void);
87 extern void VOLUME_CreateDevices(void);
88 extern void VERSION_Init( const WCHAR *appname );
89 extern void LOCALE_Init(void);
91 /***********************************************************************
94 inline static int contains_path( LPCWSTR name )
96 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
100 /***********************************************************************
103 * Check if an environment variable needs to be handled specially when
104 * passed through the Unix environment (i.e. prefixed with "WINE").
106 inline static int is_special_env_var( const char *var )
108 return (!strncmp( var, "PATH=", sizeof("PATH=")-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,
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,
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,
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 )
307 IMAGE_NT_HEADERS *nt;
310 OBJECT_ATTRIBUTES attr;
315 attr.Length = sizeof(attr);
316 attr.RootDirectory = 0;
317 attr.ObjectName = NULL;
319 attr.SecurityDescriptor = NULL;
320 attr.SecurityQualityOfService = NULL;
323 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
324 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
328 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
329 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
335 nt = RtlImageNtHeader( module );
336 if (nt->OptionalHeader.AddressOfEntryPoint)
338 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
339 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
340 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
341 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
344 drive_type = GetDriveTypeW( name );
345 /* don't keep the file handle open on removable media */
346 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM)
348 CloseHandle( main_exe_file );
355 /***********************************************************************
356 * build_initial_environment
358 * Build the Win32 environment from the Unix environment
360 static BOOL build_initial_environment( char **environ )
367 /* Compute the total size of the Unix environment */
368 for (e = environ; *e; e++)
370 if (is_special_env_var( *e )) continue;
371 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
373 size *= sizeof(WCHAR);
375 /* Now allocate the environment */
376 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
377 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
380 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
381 endptr = p + size / sizeof(WCHAR);
383 /* And fill it with the Unix environment */
384 for (e = environ; *e; e++)
388 /* skip Unix special variables and use the Wine variants instead */
389 if (!strncmp( str, "WINE", 4 ))
391 if (is_special_env_var( str + 4 )) str += 4;
392 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
394 else if (is_special_env_var( str )) continue; /* skip it */
396 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
404 /***********************************************************************
405 * set_registry_variables
407 * Set environment variables by enumerating the values of a key;
408 * helper for set_registry_environment().
410 static void set_registry_variables( HKEY hkey )
412 UNICODE_STRING env_name, env_value;
416 char buffer[1024 + sizeof(KEY_VALUE_FULL_INFORMATION)];
417 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
419 for (index = 0; ; index++)
421 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
422 buffer, sizeof(buffer), &size );
423 if (status == STATUS_BUFFER_OVERFLOW) continue;
424 if (status != STATUS_SUCCESS) break;
425 if (info->Type != REG_SZ) continue; /* FIXME: handle REG_EXPAND_SZ */
426 env_name.Buffer = info->Name;
427 env_name.Length = env_name.MaximumLength = info->NameLength;
428 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
429 env_value.Length = env_value.MaximumLength = info->DataLength;
430 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
431 env_value.Length--; /* don't count terminating null if any */
432 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
437 /***********************************************************************
438 * set_registry_environment
440 * Set the environment variables specified in the registry.
442 static void set_registry_environment(void)
444 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
445 'S','y','s','t','e','m','\\',
446 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
447 'C','o','n','t','r','o','l','\\',
448 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
449 'E','n','v','i','r','o','n','m','e','n','t',0};
450 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
452 OBJECT_ATTRIBUTES attr;
453 UNICODE_STRING nameW;
456 attr.Length = sizeof(attr);
457 attr.RootDirectory = 0;
458 attr.ObjectName = &nameW;
460 attr.SecurityDescriptor = NULL;
461 attr.SecurityQualityOfService = NULL;
463 /* first the system environment variables */
464 RtlInitUnicodeString( &nameW, env_keyW );
465 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
467 set_registry_variables( hkey );
471 /* then the ones for the current user */
472 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, (HKEY *)&attr.RootDirectory ) != STATUS_SUCCESS) return;
473 RtlInitUnicodeString( &nameW, envW );
474 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
476 set_registry_variables( hkey );
479 NtClose( attr.RootDirectory );
483 /***********************************************************************
486 * Set the Wine library Unicode argv global variables.
488 static void set_library_wargv( char **argv )
495 for (argc = 0; argv[argc]; argc++)
496 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
498 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
499 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
500 p = (WCHAR *)(wargv + argc + 1);
501 for (argc = 0; argv[argc]; argc++)
503 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
509 __wine_main_wargv = wargv;
513 /***********************************************************************
516 * Build the command line of a process from the argv array.
518 * Note that it does NOT necessarily include the file name.
519 * Sometimes we don't even have any command line options at all.
521 * We must quote and escape characters so that the argv array can be rebuilt
522 * from the command line:
523 * - spaces and tabs must be quoted
525 * - quotes must be escaped
527 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
528 * resulting in an odd number of '\' followed by a '"'
531 * - '\'s that are not followed by a '"' can be left as is
535 static BOOL build_command_line( WCHAR **argv )
540 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
542 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
545 for (arg = argv; *arg; arg++)
547 int has_space,bcount;
553 if( !*a ) has_space=1;
558 if (*a==' ' || *a=='\t') {
560 } else if (*a=='"') {
561 /* doubling of '\' preceeding a '"',
562 * plus escaping of said '"'
570 len+=(a-*arg)+1 /* for the separating space */;
572 len+=2; /* for the quotes */
575 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
578 p = rupp->CommandLine.Buffer;
579 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
580 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
581 for (arg = argv; *arg; arg++)
583 int has_space,has_quote;
586 /* Check for quotes and spaces in this argument */
587 has_space=has_quote=0;
589 if( !*a ) has_space=1;
591 if (*a==' ' || *a=='\t') {
595 } else if (*a=='"') {
603 /* Now transfer it to the command line */
620 /* Double all the '\\' preceeding this '"', plus one */
621 for (i=0;i<=bcount;i++)
633 while ((*p=*x++)) p++;
639 if (p > rupp->CommandLine.Buffer)
640 p--; /* remove last space */
647 /* make sure the unicode string doesn't point beyond the end pointer */
648 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
650 if ((char *)str->Buffer >= end_ptr)
652 str->Length = str->MaximumLength = 0;
656 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
658 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
660 if (str->Length >= str->MaximumLength)
662 if (str->MaximumLength >= sizeof(WCHAR))
663 str->Length = str->MaximumLength - sizeof(WCHAR);
665 str->Length = str->MaximumLength = 0;
669 static void version(void)
671 MESSAGE( "%s\n", PACKAGE_STRING );
675 static void usage(void)
677 MESSAGE( "%s\n", PACKAGE_STRING );
678 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
679 MESSAGE( " wine --help Display this help and exit\n");
680 MESSAGE( " wine --version Output version information and exit\n");
685 /***********************************************************************
686 * init_user_process_params
688 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
690 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
695 RTL_USER_PROCESS_PARAMETERS *params;
698 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
699 MEM_COMMIT, PAGE_READWRITE )) != STATUS_SUCCESS)
702 SERVER_START_REQ( get_startup_info )
704 wine_server_set_reply( req, ptr, info_size );
705 wine_server_call( req );
706 info_size = wine_server_reply_size( reply );
711 params->Size = info_size;
712 params->AllocationSize = size;
714 /* make sure the strings are valid */
715 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
716 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
717 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
718 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
719 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
720 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
721 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
722 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
724 return RtlNormalizeProcessParams( params );
728 /***********************************************************************
729 * init_current_directory
731 * Initialize the current directory from the Unix cwd or the parent info.
733 static void init_current_directory( CURDIR *cur_dir )
735 UNICODE_STRING dir_str;
739 /* if we received a cur dir from the parent, try this first */
741 if (cur_dir->DosPath.Length)
743 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
746 /* now try to get it from the Unix cwd */
748 for (size = 256; ; size *= 2)
750 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
751 if (getcwd( cwd, size )) break;
752 HeapFree( GetProcessHeap(), 0, cwd );
753 if (errno == ERANGE) continue;
761 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
762 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
764 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
765 RtlInitUnicodeString( &dir_str, dirW );
766 RtlSetCurrentDirectory_U( &dir_str );
767 RtlFreeUnicodeString( &dir_str );
771 if (!cur_dir->DosPath.Length) /* still not initialized */
773 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
774 "starting in the Windows directory.\n", cwd ? cwd : "" );
775 RtlInitUnicodeString( &dir_str, DIR_Windows );
776 RtlSetCurrentDirectory_U( &dir_str );
778 if (cwd) HeapFree( GetProcessHeap(), 0, cwd );
781 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
782 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
786 /***********************************************************************
789 * Initialize the windows and system directories from the environment.
791 static void init_windows_dirs(void)
793 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
794 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
795 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
796 static const WCHAR default_sysdirW[] = {'c',':','\\','w','i','n','d','o','w','s','\\','s','y','s','t','e','m',0};
801 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
803 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
804 GetEnvironmentVariableW( windirW, buffer, len );
805 DIR_Windows = buffer;
809 DIR_Windows = default_windirW;
810 SetEnvironmentVariableW( windirW, DIR_Windows );
813 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
815 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
816 GetEnvironmentVariableW( winsysdirW, buffer, len );
821 DIR_System = default_sysdirW;
822 SetEnvironmentVariableW( winsysdirW, DIR_System );
825 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
826 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
827 debugstr_w(DIR_Windows) );
828 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
829 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
830 debugstr_w(DIR_System) );
832 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
833 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
837 /***********************************************************************
840 * Main process initialisation code
842 static BOOL process_init( char *argv[], char **environ )
844 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
846 size_t info_size = 0;
847 RTL_USER_PROCESS_PARAMETERS *params;
848 PEB *peb = NtCurrentTeb()->Peb;
849 HANDLE hstdin, hstdout, hstderr;
850 extern void __wine_dbg_kernel32_init(void);
854 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
858 setlocale(LC_CTYPE,"");
860 /* Retrieve startup info from the server */
861 SERVER_START_REQ( init_process )
864 req->ldt_copy = &wine_ldt_copy;
865 if ((ret = !wine_server_call_err( req )))
867 main_exe_file = reply->exe_file;
868 main_create_flags = reply->create_flags;
869 info_size = reply->info_size;
870 server_startticks = reply->server_start;
871 hstdin = reply->hstdin;
872 hstdout = reply->hstdout;
873 hstderr = reply->hstderr;
877 if (!ret) return FALSE;
881 params = peb->ProcessParameters;
883 /* This is wine specific: we have no parent (we're started from unix)
884 * so, create a simple console with bare handles to unix stdio
885 * input & output streams (aka simple console)
887 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, ¶ms->hStdInput );
888 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdOutput );
889 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdError );
891 params->CurrentDirectory.DosPath.Length = 0;
892 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
893 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
897 if (!(params = init_user_process_params( info_size ))) return FALSE;
898 peb->ProcessParameters = params;
900 /* convert value from server:
901 * + 0 => INVALID_HANDLE_VALUE
902 * + console handle need to be mapped
905 hstdin = INVALID_HANDLE_VALUE;
906 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
907 hstdin = console_handle_map(hstdin);
910 hstdout = INVALID_HANDLE_VALUE;
911 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
912 hstdout = console_handle_map(hstdout);
915 hstderr = INVALID_HANDLE_VALUE;
916 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
917 hstderr = console_handle_map(hstderr);
919 params->hStdInput = hstdin;
920 params->hStdOutput = hstdout;
921 params->hStdError = hstderr;
924 kernel32_handle = GetModuleHandleW(kernel32W);
928 /* Copy the parent environment */
929 if (!build_initial_environment( environ )) return FALSE;
931 /* Create device symlinks */
932 VOLUME_CreateDevices();
934 init_current_directory( ¶ms->CurrentDirectory );
936 /* registry initialisation */
937 SHELL_LoadRegistry();
939 /* global boot finished, the rest is process-local */
940 SERVER_START_REQ( boot_done )
942 req->debug_level = TRACE_ON(server);
943 wine_server_call( req );
947 if (!info_size) set_registry_environment();
955 /***********************************************************************
958 * Startup routine of a new process. Runs on the new process stack.
960 static void start_process( void *arg )
964 PEB *peb = NtCurrentTeb()->Peb;
965 IMAGE_NT_HEADERS *nt;
966 LPTHREAD_START_ROUTINE entry;
968 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
970 nt = RtlImageNtHeader( peb->ImageBaseAddress );
971 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
972 nt->OptionalHeader.AddressOfEntryPoint);
975 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
976 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
978 SetLastError( 0 ); /* clear error code */
979 if (peb->BeingDebugged) DbgBreakPoint();
980 ExitProcess( entry( peb ) );
982 __EXCEPT(UnhandledExceptionFilter)
984 TerminateThread( GetCurrentThread(), GetExceptionCode() );
990 /***********************************************************************
993 * Wine initialisation: load and start the main exe file.
995 void __wine_kernel_init(void)
997 WCHAR *main_exe_name, *p;
999 DWORD stack_size = 0;
1001 PEB *peb = NtCurrentTeb()->Peb;
1003 /* Initialize everything */
1004 if (!process_init( __wine_main_argv, __wine_main_environ )) exit(1);
1005 /* update argc in case options have been removed */
1006 for (__wine_main_argc = 0; __wine_main_argv[__wine_main_argc]; __wine_main_argc++) /*nothing*/;
1008 __wine_main_argv++; /* remove argv[0] (wine itself) */
1011 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1013 WCHAR buffer[MAX_PATH];
1014 WCHAR exe_nameW[MAX_PATH];
1016 if (!__wine_main_argv[0]) usage();
1017 if (__wine_main_argc == 1)
1019 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1020 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1023 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1024 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1026 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1029 if (main_exe_file == INVALID_HANDLE_VALUE)
1031 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1034 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1035 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1038 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1039 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1041 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1042 MODULE_get_dll_load_path(NULL) );
1043 VERSION_Init( main_exe_name );
1045 if (!main_exe_file) /* no file handle -> Winelib app */
1047 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1048 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1050 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1051 debugstr_w(main_exe_name), error );
1055 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1058 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1059 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1061 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1064 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1066 case BINARY_UNKNOWN:
1067 /* check for .com extension */
1068 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1070 MESSAGE( "wine: cannot determine executable type for %s\n",
1071 debugstr_w(main_exe_name) );
1077 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1078 CloseHandle( main_exe_file );
1082 __wine_main_argv[0] = "winevdm.exe";
1083 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1085 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1086 debugstr_w(main_exe_name), error );
1089 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
1091 case BINARY_UNIX_EXE:
1092 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1094 case BINARY_UNIX_LIB:
1098 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1099 CloseHandle( main_exe_file );
1101 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1102 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1104 static const WCHAR soW[] = {'.','s','o',0};
1105 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1108 /* update the unicode string */
1109 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1111 HeapFree( GetProcessHeap(), 0, unix_name );
1114 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1120 /* build command line */
1121 set_library_wargv( __wine_main_argv );
1122 if (!build_command_line( __wine_main_wargv )) goto error;
1124 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1126 /* allocate main thread stack */
1127 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1129 /* switch to the new stack */
1130 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1133 ExitProcess( GetLastError() );
1137 /***********************************************************************
1140 * Build an argv array from a command-line.
1141 * 'reserved' is the number of args to reserve before the first one.
1143 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1147 char *arg,*s,*d,*cmdline;
1148 int in_quotes,bcount,len;
1150 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1151 if (!(cmdline = malloc(len))) return NULL;
1152 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1159 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1162 /* skip the remaining spaces */
1163 while (*s==' ' || *s=='\t') {
1170 } else if (*s=='\\') {
1171 /* '\', count them */
1173 } else if ((*s=='"') && ((bcount & 1)==0)) {
1175 in_quotes=!in_quotes;
1178 /* a regular character */
1183 argv=malloc(argc*sizeof(*argv));
1192 if ((*s==' ' || *s=='\t') && !in_quotes) {
1193 /* Close the argument and copy it */
1197 /* skip the remaining spaces */
1200 } while (*s==' ' || *s=='\t');
1202 /* Start with a new argument */
1205 } else if (*s=='\\') {
1209 } else if (*s=='"') {
1211 if ((bcount & 1)==0) {
1212 /* Preceeded by an even number of '\', this is half that
1213 * number of '\', plus a '"' which we discard.
1217 in_quotes=!in_quotes;
1219 /* Preceeded by an odd number of '\', this is half that
1220 * number of '\' followed by a '"'
1228 /* a regular character */
1243 /***********************************************************************
1246 * Allocate an environment string; helper for build_envp
1248 static char *alloc_env_string( const char *name, const char *value )
1250 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1251 strcpy( ret, name );
1252 strcat( ret, value );
1256 /***********************************************************************
1259 * Build the environment of a new child process.
1261 static char **build_envp( const WCHAR *envW, char *extra_env )
1266 int count = 0, length;
1268 for (end = envW; *end; count++) end += strlenW(end) + 1;
1270 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1271 if (!(env = malloc( length ))) return NULL;
1272 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1274 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) count++;
1277 if ((envp = malloc( count * sizeof(*envp) )))
1279 char **envptr = envp;
1281 /* first the extra strings */
1283 for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = alloc_env_string( "", p );
1284 /* then put PATH, TEMP, TMP, HOME and WINEPREFIX from the unix env */
1285 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1286 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1287 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1288 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1289 if ((p = getenv("WINEPREFIX"))) *envptr++ = alloc_env_string( "WINEPREFIX=", p );
1290 /* now put the Windows environment strings */
1291 for (p = env; *p; p += strlen(p) + 1)
1293 if (is_special_env_var( p )) /* prefix it with "WINE" */
1294 *envptr++ = alloc_env_string( "WINE", p );
1295 else if (strncmp( p, "HOME=", 5 ) &&
1296 strncmp( p, "WINEPRELOADRESERVE=", 19 ) &&
1297 strncmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
1305 /***********************************************************************
1308 * Fork and exec a new Unix binary, checking for errors.
1310 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1311 const WCHAR *env, const char *newdir )
1316 if (!env) env = GetEnvironmentStringsW();
1320 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1323 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1324 if (!(pid = fork())) /* child */
1326 char **argv = build_argv( cmdline, 0 );
1327 char **envp = build_envp( env, NULL );
1330 /* Reset signals that we previously set to SIG_IGN */
1331 signal( SIGPIPE, SIG_DFL );
1332 signal( SIGCHLD, SIG_DFL );
1334 if (newdir) chdir(newdir);
1336 if (argv && envp) execve( filename, argv, envp );
1338 write( fd[1], &err, sizeof(err) );
1342 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1347 if (pid == -1) FILE_SetDosError();
1353 /***********************************************************************
1354 * create_user_params
1356 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1357 LPCWSTR cur_dir, const STARTUPINFOW *startup )
1359 RTL_USER_PROCESS_PARAMETERS *params;
1360 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title;
1362 WCHAR buffer[MAX_PATH];
1364 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1365 lstrcpynW( buffer, filename, MAX_PATH );
1366 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1367 lstrcpynW( buffer, filename, MAX_PATH );
1368 RtlInitUnicodeString( &image_str, buffer );
1370 RtlInitUnicodeString( &cmdline_str, cmdline );
1371 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1372 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1373 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1375 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1376 cur_dir ? &curdir_str : NULL,
1378 startup->lpTitle ? &title : NULL,
1379 startup->lpDesktop ? &desktop : NULL,
1381 if (status != STATUS_SUCCESS)
1383 SetLastError( RtlNtStatusToDosError(status) );
1387 params->Environment = NULL; /* we pass it through the Unix environment */
1388 params->hStdInput = startup->hStdInput;
1389 params->hStdOutput = startup->hStdOutput;
1390 params->hStdError = startup->hStdError;
1391 params->dwX = startup->dwX;
1392 params->dwY = startup->dwY;
1393 params->dwXSize = startup->dwXSize;
1394 params->dwYSize = startup->dwYSize;
1395 params->dwXCountChars = startup->dwXCountChars;
1396 params->dwYCountChars = startup->dwYCountChars;
1397 params->dwFillAttribute = startup->dwFillAttribute;
1398 params->dwFlags = startup->dwFlags;
1399 params->wShowWindow = startup->wShowWindow;
1404 /***********************************************************************
1407 * Create a new process. If hFile is a valid handle we have an exe
1408 * file, otherwise it is a Winelib app.
1410 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1411 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1412 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1413 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1414 void *res_start, void *res_end )
1416 BOOL ret, success = FALSE;
1417 HANDLE process_info;
1418 RTL_USER_PROCESS_PARAMETERS *params;
1424 char preloader_reserve[64];
1426 if (!env) env = GetEnvironmentStringsW();
1428 if (!(params = create_user_params( filename, cmd_line, cur_dir, startup )))
1431 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1432 (unsigned long)res_start, (unsigned long)res_end, 0 );
1434 /* create the synchronization pipes */
1436 if (pipe( startfd ) == -1)
1438 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1439 RtlDestroyProcessParameters( params );
1442 if (pipe( execfd ) == -1)
1444 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1445 close( startfd[0] );
1446 close( startfd[1] );
1447 RtlDestroyProcessParameters( params );
1450 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1452 /* create the child process */
1454 if (!(pid = fork())) /* child */
1456 char **argv = build_argv( cmd_line, 1 );
1457 char **envp = build_envp( env, preloader_reserve );
1459 close( startfd[1] );
1462 /* wait for parent to tell us to start */
1463 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1465 close( startfd[0] );
1466 /* Reset signals that we previously set to SIG_IGN */
1467 signal( SIGPIPE, SIG_DFL );
1468 signal( SIGCHLD, SIG_DFL );
1470 if (unixdir) chdir(unixdir);
1474 /* first, try for a WINELOADER environment variable */
1475 const char *loader = getenv("WINELOADER");
1476 if (loader) wine_exec_wine_binary( loader, argv, envp, TRUE );
1477 /* now use the standard search strategy */
1478 wine_exec_wine_binary( NULL, argv, envp, TRUE );
1481 write( execfd[1], &err, sizeof(err) );
1485 /* this is the parent */
1487 close( startfd[0] );
1491 close( startfd[1] );
1494 RtlDestroyProcessParameters( params );
1498 /* create the process on the server side */
1500 SERVER_START_REQ( new_process )
1502 req->inherit_all = inherit;
1503 req->create_flags = flags;
1504 req->unix_pid = pid;
1505 req->exe_file = hFile;
1506 if (startup->dwFlags & STARTF_USESTDHANDLES)
1508 req->hstdin = startup->hStdInput;
1509 req->hstdout = startup->hStdOutput;
1510 req->hstderr = startup->hStdError;
1514 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1515 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1516 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1519 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1521 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1522 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1523 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1524 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1528 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1529 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1530 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1533 wine_server_add_data( req, params, params->Size );
1534 ret = !wine_server_call_err( req );
1535 process_info = reply->info;
1539 RtlDestroyProcessParameters( params );
1542 close( startfd[1] );
1547 /* tell child to start and wait for it to exec */
1549 write( startfd[1], &dummy, 1 );
1550 close( startfd[1] );
1552 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1557 CloseHandle( process_info );
1562 /* wait for the new process info to be ready */
1564 WaitForSingleObject( process_info, INFINITE );
1565 SERVER_START_REQ( get_new_process_info )
1567 req->info = process_info;
1568 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1569 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1570 if ((ret = !wine_server_call_err( req )))
1572 info->dwProcessId = (DWORD)reply->pid;
1573 info->dwThreadId = (DWORD)reply->tid;
1574 info->hProcess = reply->phandle;
1575 info->hThread = reply->thandle;
1576 success = reply->success;
1581 if (ret && !success) /* new process failed to start */
1584 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1585 CloseHandle( info->hThread );
1586 CloseHandle( info->hProcess );
1589 CloseHandle( process_info );
1594 /***********************************************************************
1595 * create_vdm_process
1597 * Create a new VDM process for a 16-bit or DOS application.
1599 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1600 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1601 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1602 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1604 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1607 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1608 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1612 SetLastError( ERROR_OUTOFMEMORY );
1615 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1616 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1617 flags, startup, info, unixdir, NULL, NULL );
1618 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1623 /***********************************************************************
1624 * create_cmd_process
1626 * Create a new cmd shell process for a .BAT file.
1628 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1629 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1630 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1631 LPPROCESS_INFORMATION info )
1634 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1635 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1636 WCHAR comspec[MAX_PATH];
1640 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1642 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1643 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1646 strcpyW( newcmdline, comspec );
1647 strcatW( newcmdline, slashcW );
1648 strcatW( newcmdline, cmd_line );
1649 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1650 flags, env, cur_dir, startup, info );
1651 HeapFree( GetProcessHeap(), 0, newcmdline );
1656 /*************************************************************************
1659 * Helper for CreateProcess: retrieve the file name to load from the
1660 * app name and command line. Store the file name in buffer, and
1661 * return a possibly modified command line.
1662 * Also returns a handle to the opened file if it's a Windows binary.
1664 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1665 int buflen, HANDLE *handle )
1667 static const WCHAR quotesW[] = {'"','%','s','"',0};
1669 WCHAR *name, *pos, *ret = NULL;
1672 /* if we have an app name, everything is easy */
1676 /* use the unmodified app name as file name */
1677 lstrcpynW( buffer, appname, buflen );
1678 *handle = open_exe_file( buffer );
1679 if (!(ret = cmdline) || !cmdline[0])
1681 /* no command-line, create one */
1682 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1683 sprintfW( ret, quotesW, appname );
1690 SetLastError( ERROR_INVALID_PARAMETER );
1694 /* first check for a quoted file name */
1696 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1698 int len = p - cmdline - 1;
1699 /* extract the quoted portion as file name */
1700 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1701 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1704 if (find_exe_file( name, buffer, buflen, handle ))
1705 ret = cmdline; /* no change necessary */
1709 /* now try the command-line word by word */
1711 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1718 do *pos++ = *p++; while (*p && *p != ' ');
1720 if (find_exe_file( name, buffer, buflen, handle ))
1727 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1729 /* now build a new command-line with quotes */
1731 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1733 sprintfW( ret, quotesW, name );
1737 HeapFree( GetProcessHeap(), 0, name );
1742 /**********************************************************************
1743 * CreateProcessA (KERNEL32.@)
1745 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1746 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1747 DWORD flags, LPVOID env, LPCSTR cur_dir,
1748 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1751 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1752 UNICODE_STRING desktopW, titleW;
1755 desktopW.Buffer = NULL;
1756 titleW.Buffer = NULL;
1757 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1758 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1759 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1761 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1762 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1764 memcpy( &infoW, startup_info, sizeof(infoW) );
1765 infoW.lpDesktop = desktopW.Buffer;
1766 infoW.lpTitle = titleW.Buffer;
1768 if (startup_info->lpReserved)
1769 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1770 debugstr_a(startup_info->lpReserved));
1772 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1773 inherit, flags, env, cur_dirW, &infoW, info );
1775 if (app_nameW) HeapFree( GetProcessHeap(), 0, app_nameW );
1776 if (cmd_lineW) HeapFree( GetProcessHeap(), 0, cmd_lineW );
1777 if (cur_dirW) HeapFree( GetProcessHeap(), 0, cur_dirW );
1778 RtlFreeUnicodeString( &desktopW );
1779 RtlFreeUnicodeString( &titleW );
1784 /**********************************************************************
1785 * CreateProcessW (KERNEL32.@)
1787 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1788 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1789 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1790 LPPROCESS_INFORMATION info )
1794 char *unixdir = NULL;
1795 WCHAR name[MAX_PATH];
1796 WCHAR *tidy_cmdline, *p, *envW = env;
1797 void *res_start, *res_end;
1799 /* Process the AppName and/or CmdLine to get module name and path */
1801 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1803 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1805 if (hFile == INVALID_HANDLE_VALUE) goto done;
1807 /* Warn if unsupported features are used */
1809 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1810 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1811 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1812 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1813 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1817 unixdir = wine_get_unix_file_name( cur_dir );
1821 WCHAR buf[MAX_PATH];
1822 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1825 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1830 while (*p) p += strlen(p) + 1;
1831 p++; /* final null */
1832 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1833 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1834 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1835 flags |= CREATE_UNICODE_ENVIRONMENT;
1838 info->hThread = info->hProcess = 0;
1839 info->dwProcessId = info->dwThreadId = 0;
1841 /* Determine executable type */
1843 if (!hFile) /* builtin exe */
1845 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1846 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1847 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1851 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1854 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1855 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1856 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1860 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1861 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1862 inherit, flags, startup_info, info, unixdir );
1865 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1866 SetLastError( ERROR_BAD_EXE_FORMAT );
1869 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1870 SetLastError( ERROR_BAD_EXE_FORMAT );
1872 case BINARY_UNIX_LIB:
1873 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1874 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1875 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1877 case BINARY_UNKNOWN:
1878 /* check for .com or .bat extension */
1879 if ((p = strrchrW( name, '.' )))
1881 if (!strcmpiW( p, comW ))
1883 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1884 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1885 inherit, flags, startup_info, info, unixdir );
1888 if (!strcmpiW( p, batW ))
1890 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1891 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1892 inherit, flags, startup_info, info );
1897 case BINARY_UNIX_EXE:
1899 /* unknown file, try as unix executable */
1902 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1904 if ((unix_name = wine_get_unix_file_name( name )))
1906 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1907 HeapFree( GetProcessHeap(), 0, unix_name );
1912 CloseHandle( hFile );
1915 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1916 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1917 if (unixdir) HeapFree( GetProcessHeap(), 0, unixdir );
1922 /***********************************************************************
1925 * Wrapper to call WaitForInputIdle USER function
1927 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1929 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1931 HMODULE mod = GetModuleHandleA( "user32.dll" );
1934 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1935 if (ptr) return ptr( process, timeout );
1941 /***********************************************************************
1942 * WinExec (KERNEL32.@)
1944 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1946 PROCESS_INFORMATION info;
1947 STARTUPINFOA startup;
1951 memset( &startup, 0, sizeof(startup) );
1952 startup.cb = sizeof(startup);
1953 startup.dwFlags = STARTF_USESHOWWINDOW;
1954 startup.wShowWindow = nCmdShow;
1956 /* cmdline needs to be writeable for CreateProcess */
1957 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1958 strcpy( cmdline, lpCmdLine );
1960 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1961 0, NULL, NULL, &startup, &info ))
1963 /* Give 30 seconds to the app to come up */
1964 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1965 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1967 /* Close off the handles */
1968 CloseHandle( info.hThread );
1969 CloseHandle( info.hProcess );
1971 else if ((ret = GetLastError()) >= 32)
1973 FIXME("Strange error set by CreateProcess: %d\n", ret );
1976 HeapFree( GetProcessHeap(), 0, cmdline );
1981 /**********************************************************************
1982 * LoadModule (KERNEL32.@)
1984 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1986 LOADPARMS32 *params = paramBlock;
1987 PROCESS_INFORMATION info;
1988 STARTUPINFOA startup;
1989 HINSTANCE hInstance;
1991 char filename[MAX_PATH];
1994 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1996 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1997 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1998 return (HINSTANCE)GetLastError();
2000 len = (BYTE)params->lpCmdLine[0];
2001 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2002 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2004 strcpy( cmdline, filename );
2005 p = cmdline + strlen(cmdline);
2007 memcpy( p, params->lpCmdLine + 1, len );
2010 memset( &startup, 0, sizeof(startup) );
2011 startup.cb = sizeof(startup);
2012 if (params->lpCmdShow)
2014 startup.dwFlags = STARTF_USESHOWWINDOW;
2015 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2018 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2019 params->lpEnvAddress, NULL, &startup, &info ))
2021 /* Give 30 seconds to the app to come up */
2022 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2023 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2024 hInstance = (HINSTANCE)33;
2025 /* Close off the handles */
2026 CloseHandle( info.hThread );
2027 CloseHandle( info.hProcess );
2029 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2031 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2032 hInstance = (HINSTANCE)11;
2035 HeapFree( GetProcessHeap(), 0, cmdline );
2040 /******************************************************************************
2041 * TerminateProcess (KERNEL32.@)
2043 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2045 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2046 if (status) SetLastError( RtlNtStatusToDosError(status) );
2051 /***********************************************************************
2052 * ExitProcess (KERNEL32.@)
2054 void WINAPI ExitProcess( DWORD status )
2056 LdrShutdownProcess();
2057 SERVER_START_REQ( terminate_process )
2059 /* send the exit code to the server */
2060 req->handle = GetCurrentProcess();
2061 req->exit_code = status;
2062 wine_server_call( req );
2069 /***********************************************************************
2070 * GetExitCodeProcess [KERNEL32.@]
2072 * Gets termination status of specified process
2078 BOOL WINAPI GetExitCodeProcess(
2079 HANDLE hProcess, /* [in] handle to the process */
2080 LPDWORD lpExitCode) /* [out] address to receive termination status */
2083 SERVER_START_REQ( get_process_info )
2085 req->handle = hProcess;
2086 ret = !wine_server_call_err( req );
2087 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
2094 /***********************************************************************
2095 * SetErrorMode (KERNEL32.@)
2097 UINT WINAPI SetErrorMode( UINT mode )
2099 UINT old = process_error_mode;
2100 process_error_mode = mode;
2105 /**********************************************************************
2106 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2108 * Allocates a thread local storage index
2111 * Success: TLS Index
2112 * Failure: 0xFFFFFFFF
2114 DWORD WINAPI TlsAlloc( void )
2118 RtlAcquirePebLock();
2119 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
2120 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2121 else SetLastError( ERROR_NO_MORE_ITEMS );
2122 RtlReleasePebLock();
2127 /**********************************************************************
2128 * TlsFree [KERNEL32.@] Releases a TLS index.
2130 * Releases a thread local storage index, making it available for reuse
2136 BOOL WINAPI TlsFree(
2137 DWORD index) /* [in] TLS Index to free */
2141 RtlAcquirePebLock();
2142 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2145 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2146 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2148 else SetLastError( ERROR_INVALID_PARAMETER );
2149 RtlReleasePebLock();
2154 /**********************************************************************
2155 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2158 * Success: Value stored in calling thread's TLS slot for index
2159 * Failure: 0 and GetLastError returns NO_ERROR
2161 LPVOID WINAPI TlsGetValue(
2162 DWORD index) /* [in] TLS index to retrieve value for */
2164 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2166 SetLastError( ERROR_INVALID_PARAMETER );
2169 SetLastError( ERROR_SUCCESS );
2170 return NtCurrentTeb()->TlsSlots[index];
2174 /**********************************************************************
2175 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2181 BOOL WINAPI TlsSetValue(
2182 DWORD index, /* [in] TLS index to set value for */
2183 LPVOID value) /* [in] Value to be stored */
2185 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2187 SetLastError( ERROR_INVALID_PARAMETER );
2190 NtCurrentTeb()->TlsSlots[index] = value;
2195 /***********************************************************************
2196 * GetProcessFlags (KERNEL32.@)
2198 DWORD WINAPI GetProcessFlags( DWORD processid )
2200 IMAGE_NT_HEADERS *nt;
2203 if (processid && processid != GetCurrentProcessId()) return 0;
2205 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2207 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2208 flags |= PDB32_CONSOLE_PROC;
2210 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2211 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2216 /***********************************************************************
2217 * GetProcessDword (KERNEL.485)
2218 * GetProcessDword (KERNEL32.18)
2219 * 'Of course you cannot directly access Windows internal structures'
2221 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2226 TRACE("(%ld, %d)\n", dwProcessID, offset );
2228 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2230 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2236 case GPD_APP_COMPAT_FLAGS:
2237 return GetAppCompatFlags16(0);
2238 case GPD_LOAD_DONE_EVENT:
2240 case GPD_HINSTANCE16:
2241 return GetTaskDS16();
2242 case GPD_WINDOWS_VERSION:
2243 return GetExeVersion16();
2245 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2247 return (DWORD)NtCurrentTeb()->Peb;
2248 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2249 GetStartupInfoW(&siw);
2250 return (DWORD)siw.hStdOutput;
2251 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2252 GetStartupInfoW(&siw);
2253 return (DWORD)siw.hStdInput;
2254 case GPD_STARTF_SHOWWINDOW:
2255 GetStartupInfoW(&siw);
2256 return siw.wShowWindow;
2257 case GPD_STARTF_SIZE:
2258 GetStartupInfoW(&siw);
2260 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2262 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2263 return MAKELONG( x, y );
2264 case GPD_STARTF_POSITION:
2265 GetStartupInfoW(&siw);
2267 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2269 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2270 return MAKELONG( x, y );
2271 case GPD_STARTF_FLAGS:
2272 GetStartupInfoW(&siw);
2277 return GetProcessFlags(0);
2279 return process_dword;
2281 ERR("Unknown offset %d\n", offset );
2286 /***********************************************************************
2287 * SetProcessDword (KERNEL.484)
2288 * 'Of course you cannot directly access Windows internal structures'
2290 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2292 TRACE("(%ld, %d)\n", dwProcessID, offset );
2294 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2296 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2302 case GPD_APP_COMPAT_FLAGS:
2303 case GPD_LOAD_DONE_EVENT:
2304 case GPD_HINSTANCE16:
2305 case GPD_WINDOWS_VERSION:
2308 case GPD_STARTF_SHELLDATA:
2309 case GPD_STARTF_HOTKEY:
2310 case GPD_STARTF_SHOWWINDOW:
2311 case GPD_STARTF_SIZE:
2312 case GPD_STARTF_POSITION:
2313 case GPD_STARTF_FLAGS:
2316 ERR("Not allowed to modify offset %d\n", offset );
2319 process_dword = value;
2322 ERR("Unknown offset %d\n", offset );
2328 /***********************************************************************
2329 * ExitProcess (KERNEL.466)
2331 void WINAPI ExitProcess16( WORD status )
2334 ReleaseThunkLock( &count );
2335 ExitProcess( status );
2339 /*********************************************************************
2340 * OpenProcess (KERNEL32.@)
2342 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2345 SERVER_START_REQ( open_process )
2348 req->access = access;
2349 req->inherit = inherit;
2350 if (!wine_server_call_err( req )) ret = reply->handle;
2357 /*********************************************************************
2358 * MapProcessHandle (KERNEL.483)
2360 DWORD WINAPI MapProcessHandle( HANDLE handle )
2363 SERVER_START_REQ( get_process_info )
2365 req->handle = handle;
2366 if (!wine_server_call_err( req )) ret = reply->pid;
2373 /*********************************************************************
2374 * CloseW32Handle (KERNEL.474)
2375 * CloseHandle (KERNEL32.@)
2377 BOOL WINAPI CloseHandle( HANDLE handle )
2381 /* stdio handles need special treatment */
2382 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2383 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2384 (handle == (HANDLE)STD_ERROR_HANDLE))
2385 handle = GetStdHandle( (DWORD)handle );
2387 if (is_console_handle(handle))
2388 return CloseConsoleHandle(handle);
2390 status = NtClose( handle );
2391 if (status) SetLastError( RtlNtStatusToDosError(status) );
2396 /*********************************************************************
2397 * GetHandleInformation (KERNEL32.@)
2399 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2402 SERVER_START_REQ( set_handle_info )
2404 req->handle = handle;
2408 ret = !wine_server_call_err( req );
2409 if (ret && flags) *flags = reply->old_flags;
2416 /*********************************************************************
2417 * SetHandleInformation (KERNEL32.@)
2419 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2422 SERVER_START_REQ( set_handle_info )
2424 req->handle = handle;
2428 ret = !wine_server_call_err( req );
2435 /*********************************************************************
2436 * DuplicateHandle (KERNEL32.@)
2438 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2439 HANDLE dest_process, HANDLE *dest,
2440 DWORD access, BOOL inherit, DWORD options )
2444 if (is_console_handle(source))
2446 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2447 if (source_process != dest_process ||
2448 source_process != GetCurrentProcess())
2450 SetLastError(ERROR_INVALID_PARAMETER);
2453 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2454 return (*dest != INVALID_HANDLE_VALUE);
2456 status = NtDuplicateObject( source_process, source, dest_process, dest,
2457 access, inherit ? OBJ_INHERIT : 0, options );
2458 if (status) SetLastError( RtlNtStatusToDosError(status) );
2463 /***********************************************************************
2464 * ConvertToGlobalHandle (KERNEL.476)
2465 * ConvertToGlobalHandle (KERNEL32.@)
2467 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2469 HANDLE ret = INVALID_HANDLE_VALUE;
2470 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2471 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2476 /***********************************************************************
2477 * SetHandleContext (KERNEL32.@)
2479 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2481 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2482 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2483 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2488 /***********************************************************************
2489 * GetHandleContext (KERNEL32.@)
2491 DWORD WINAPI GetHandleContext(HANDLE hnd)
2493 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2494 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2495 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2500 /***********************************************************************
2501 * CreateSocketHandle (KERNEL32.@)
2503 HANDLE WINAPI CreateSocketHandle(void)
2505 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2506 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2507 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2508 return INVALID_HANDLE_VALUE;
2512 /***********************************************************************
2513 * SetPriorityClass (KERNEL32.@)
2515 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2518 SERVER_START_REQ( set_process_info )
2520 req->handle = hprocess;
2521 req->priority = priorityclass;
2522 req->mask = SET_PROCESS_INFO_PRIORITY;
2523 ret = !wine_server_call_err( req );
2530 /***********************************************************************
2531 * GetPriorityClass (KERNEL32.@)
2533 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2536 SERVER_START_REQ( get_process_info )
2538 req->handle = hprocess;
2539 if (!wine_server_call_err( req )) ret = reply->priority;
2546 /***********************************************************************
2547 * SetProcessAffinityMask (KERNEL32.@)
2549 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2552 SERVER_START_REQ( set_process_info )
2554 req->handle = hProcess;
2555 req->affinity = affmask;
2556 req->mask = SET_PROCESS_INFO_AFFINITY;
2557 ret = !wine_server_call_err( req );
2564 /**********************************************************************
2565 * GetProcessAffinityMask (KERNEL32.@)
2567 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2568 LPDWORD lpProcessAffinityMask,
2569 LPDWORD lpSystemAffinityMask )
2572 SERVER_START_REQ( get_process_info )
2574 req->handle = hProcess;
2575 if (!wine_server_call_err( req ))
2577 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2578 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2587 /***********************************************************************
2588 * GetProcessVersion (KERNEL32.@)
2590 DWORD WINAPI GetProcessVersion( DWORD processid )
2592 IMAGE_NT_HEADERS *nt;
2594 if (processid && processid != GetCurrentProcessId())
2596 FIXME("should use ReadProcessMemory\n");
2599 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2600 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2601 nt->OptionalHeader.MinorSubsystemVersion);
2606 /***********************************************************************
2607 * SetProcessWorkingSetSize [KERNEL32.@]
2608 * Sets the min/max working set sizes for a specified process.
2611 * hProcess [I] Handle to the process of interest
2612 * minset [I] Specifies minimum working set size
2613 * maxset [I] Specifies maximum working set size
2617 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2620 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2621 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2622 /* Trim the working set to zero */
2623 /* Swap the process out of physical RAM */
2628 /***********************************************************************
2629 * GetProcessWorkingSetSize (KERNEL32.@)
2631 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2634 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2635 /* 32 MB working set size */
2636 if (minset) *minset = 32*1024*1024;
2637 if (maxset) *maxset = 32*1024*1024;
2642 /***********************************************************************
2643 * SetProcessShutdownParameters (KERNEL32.@)
2645 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2647 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2648 shutdown_flags = flags;
2649 shutdown_priority = level;
2654 /***********************************************************************
2655 * GetProcessShutdownParameters (KERNEL32.@)
2658 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2660 *lpdwLevel = shutdown_priority;
2661 *lpdwFlags = shutdown_flags;
2666 /***********************************************************************
2667 * GetProcessPriorityBoost (KERNEL32.@)
2669 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2671 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2673 /* Report that no boost is present.. */
2674 *pDisablePriorityBoost = FALSE;
2679 /***********************************************************************
2680 * SetProcessPriorityBoost (KERNEL32.@)
2682 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2684 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2685 /* Say we can do it. I doubt the program will notice that we don't. */
2690 /***********************************************************************
2691 * ReadProcessMemory (KERNEL32.@)
2693 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2694 SIZE_T *bytes_read )
2696 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2697 if (status) SetLastError( RtlNtStatusToDosError(status) );
2702 /***********************************************************************
2703 * WriteProcessMemory (KERNEL32.@)
2705 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2706 SIZE_T *bytes_written )
2708 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2709 if (status) SetLastError( RtlNtStatusToDosError(status) );
2714 /****************************************************************************
2715 * FlushInstructionCache (KERNEL32.@)
2717 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2719 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2720 FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2725 /******************************************************************
2726 * GetProcessIoCounters (KERNEL32.@)
2728 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2732 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2733 ioc, sizeof(*ioc), NULL);
2734 if (status) SetLastError( RtlNtStatusToDosError(status) );
2738 /***********************************************************************
2739 * ProcessIdToSessionId (KERNEL32.@)
2740 * This function is available on Terminal Server 4SP4 and Windows 2000
2742 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2744 /* According to MSDN, if the calling process is not in a terminal
2745 * services environment, then the sessionid returned is zero.
2752 /***********************************************************************
2753 * RegisterServiceProcess (KERNEL.491)
2754 * RegisterServiceProcess (KERNEL32.@)
2756 * A service process calls this function to ensure that it continues to run
2757 * even after a user logged off.
2759 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2761 /* I don't think that Wine needs to do anything in that function */
2762 return 1; /* success */
2766 /***********************************************************************
2767 * GetSystemMSecCount (SYSTEM.6)
2768 * GetTickCount (KERNEL32.@)
2770 * Returns the number of milliseconds, modulo 2^32, since the start
2771 * of the wineserver.
2773 DWORD WINAPI GetTickCount(void)
2776 gettimeofday( &t, NULL );
2777 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2781 /***********************************************************************
2782 * GetCurrentProcess (KERNEL32.@)
2784 #undef GetCurrentProcess
2785 HANDLE WINAPI GetCurrentProcess(void)
2787 return (HANDLE)0xffffffff;