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;
393 else if (is_special_env_var( str )) continue; /* skip it */
395 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
403 /***********************************************************************
404 * set_registry_variables
406 * Set environment variables by enumerating the values of a key;
407 * helper for set_registry_environment().
409 static void set_registry_variables( HKEY hkey )
411 UNICODE_STRING env_name, env_value;
415 char buffer[1024 + sizeof(KEY_VALUE_FULL_INFORMATION)];
416 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
418 for (index = 0; ; index++)
420 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
421 buffer, sizeof(buffer), &size );
422 if (status == STATUS_BUFFER_OVERFLOW) continue;
423 if (status != STATUS_SUCCESS) break;
424 if (info->Type != REG_SZ) continue; /* FIXME: handle REG_EXPAND_SZ */
425 env_name.Buffer = info->Name;
426 env_name.Length = env_name.MaximumLength = info->NameLength;
427 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
428 env_value.Length = env_value.MaximumLength = info->DataLength;
429 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
430 env_value.Length--; /* don't count terminating null if any */
431 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
436 /***********************************************************************
437 * set_registry_environment
439 * Set the environment variables specified in the registry.
441 static void set_registry_environment(void)
443 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
444 'S','y','s','t','e','m','\\',
445 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
446 'C','o','n','t','r','o','l','\\',
447 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
448 'E','n','v','i','r','o','n','m','e','n','t',0};
449 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
451 OBJECT_ATTRIBUTES attr;
452 UNICODE_STRING nameW;
455 attr.Length = sizeof(attr);
456 attr.RootDirectory = 0;
457 attr.ObjectName = &nameW;
459 attr.SecurityDescriptor = NULL;
460 attr.SecurityQualityOfService = NULL;
462 /* first the system environment variables */
463 RtlInitUnicodeString( &nameW, env_keyW );
464 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
466 set_registry_variables( hkey );
470 /* then the ones for the current user */
471 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, (HKEY *)&attr.RootDirectory ) != STATUS_SUCCESS) return;
472 RtlInitUnicodeString( &nameW, envW );
473 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
475 set_registry_variables( hkey );
478 NtClose( attr.RootDirectory );
482 /***********************************************************************
485 * Set the Wine library Unicode argv global variables.
487 static void set_library_wargv( char **argv )
494 for (argc = 0; argv[argc]; argc++)
495 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
497 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
498 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
499 p = (WCHAR *)(wargv + argc + 1);
500 for (argc = 0; argv[argc]; argc++)
502 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
508 __wine_main_wargv = wargv;
512 /***********************************************************************
515 * Build the command line of a process from the argv array.
517 * Note that it does NOT necessarily include the file name.
518 * Sometimes we don't even have any command line options at all.
520 * We must quote and escape characters so that the argv array can be rebuilt
521 * from the command line:
522 * - spaces and tabs must be quoted
524 * - quotes must be escaped
526 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
527 * resulting in an odd number of '\' followed by a '"'
530 * - '\'s that are not followed by a '"' can be left as is
534 static BOOL build_command_line( WCHAR **argv )
539 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
541 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
544 for (arg = argv; *arg; arg++)
546 int has_space,bcount;
552 if( !*a ) has_space=1;
557 if (*a==' ' || *a=='\t') {
559 } else if (*a=='"') {
560 /* doubling of '\' preceeding a '"',
561 * plus escaping of said '"'
569 len+=(a-*arg)+1 /* for the separating space */;
571 len+=2; /* for the quotes */
574 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
577 p = rupp->CommandLine.Buffer;
578 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
579 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
580 for (arg = argv; *arg; arg++)
582 int has_space,has_quote;
585 /* Check for quotes and spaces in this argument */
586 has_space=has_quote=0;
588 if( !*a ) has_space=1;
590 if (*a==' ' || *a=='\t') {
594 } else if (*a=='"') {
602 /* Now transfer it to the command line */
619 /* Double all the '\\' preceeding this '"', plus one */
620 for (i=0;i<=bcount;i++)
632 while ((*p=*x++)) p++;
638 if (p > rupp->CommandLine.Buffer)
639 p--; /* remove last space */
646 /* make sure the unicode string doesn't point beyond the end pointer */
647 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
649 if ((char *)str->Buffer >= end_ptr)
651 str->Length = str->MaximumLength = 0;
655 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
657 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
659 if (str->Length >= str->MaximumLength)
661 if (str->MaximumLength >= sizeof(WCHAR))
662 str->Length = str->MaximumLength - sizeof(WCHAR);
664 str->Length = str->MaximumLength = 0;
668 static void version(void)
670 MESSAGE( "%s\n", PACKAGE_STRING );
674 static void usage(void)
676 MESSAGE( "%s\n", PACKAGE_STRING );
677 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
678 MESSAGE( " wine --help Display this help and exit\n");
679 MESSAGE( " wine --version Output version information and exit\n");
684 /***********************************************************************
685 * init_user_process_params
687 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
689 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
694 RTL_USER_PROCESS_PARAMETERS *params;
697 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
698 MEM_COMMIT, PAGE_READWRITE )) != STATUS_SUCCESS)
701 SERVER_START_REQ( get_startup_info )
703 wine_server_set_reply( req, ptr, info_size );
704 wine_server_call( req );
705 info_size = wine_server_reply_size( reply );
710 params->Size = info_size;
711 params->AllocationSize = size;
713 /* make sure the strings are valid */
714 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
715 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
716 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
717 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
718 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
719 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
720 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
721 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
723 return RtlNormalizeProcessParams( params );
727 /***********************************************************************
728 * init_current_directory
730 * Initialize the current directory from the Unix cwd or the parent info.
732 static void init_current_directory( CURDIR *cur_dir )
734 UNICODE_STRING dir_str;
738 /* if we received a cur dir from the parent, try this first */
740 if (cur_dir->DosPath.Length)
742 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
745 /* now try to get it from the Unix cwd */
747 for (size = 256; ; size *= 2)
749 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
750 if (getcwd( cwd, size )) break;
751 HeapFree( GetProcessHeap(), 0, cwd );
752 if (errno == ERANGE) continue;
760 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
761 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
763 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
764 RtlInitUnicodeString( &dir_str, dirW );
765 RtlSetCurrentDirectory_U( &dir_str );
766 RtlFreeUnicodeString( &dir_str );
770 if (!cur_dir->DosPath.Length) /* still not initialized */
772 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
773 "starting in the Windows directory.\n", cwd ? cwd : "" );
774 RtlInitUnicodeString( &dir_str, DIR_Windows );
775 RtlSetCurrentDirectory_U( &dir_str );
777 if (cwd) HeapFree( GetProcessHeap(), 0, cwd );
780 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
781 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
785 /***********************************************************************
788 * Initialize the windows and system directories from the environment.
790 static void init_windows_dirs(void)
792 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
793 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
794 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
795 static const WCHAR default_sysdirW[] = {'c',':','\\','w','i','n','d','o','w','s','\\','s','y','s','t','e','m',0};
800 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
802 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
803 GetEnvironmentVariableW( windirW, buffer, len );
804 DIR_Windows = buffer;
808 DIR_Windows = default_windirW;
809 SetEnvironmentVariableW( windirW, DIR_Windows );
812 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
814 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
815 GetEnvironmentVariableW( winsysdirW, buffer, len );
820 DIR_System = default_sysdirW;
821 SetEnvironmentVariableW( winsysdirW, DIR_System );
824 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
825 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
826 debugstr_w(DIR_Windows) );
827 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
828 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
829 debugstr_w(DIR_System) );
831 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
832 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
836 /***********************************************************************
839 * Main process initialisation code
841 static BOOL process_init( char *argv[], char **environ )
843 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
845 size_t info_size = 0;
846 RTL_USER_PROCESS_PARAMETERS *params;
847 PEB *peb = NtCurrentTeb()->Peb;
848 HANDLE hstdin, hstdout, hstderr;
849 extern void __wine_dbg_kernel32_init(void);
853 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
857 setlocale(LC_CTYPE,"");
859 /* Retrieve startup info from the server */
860 SERVER_START_REQ( init_process )
863 req->ldt_copy = &wine_ldt_copy;
864 if ((ret = !wine_server_call_err( req )))
866 main_exe_file = reply->exe_file;
867 main_create_flags = reply->create_flags;
868 info_size = reply->info_size;
869 server_startticks = reply->server_start;
870 hstdin = reply->hstdin;
871 hstdout = reply->hstdout;
872 hstderr = reply->hstderr;
876 if (!ret) return FALSE;
880 params = peb->ProcessParameters;
882 /* This is wine specific: we have no parent (we're started from unix)
883 * so, create a simple console with bare handles to unix stdio
884 * input & output streams (aka simple console)
886 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, ¶ms->hStdInput );
887 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdOutput );
888 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdError );
890 params->CurrentDirectory.DosPath.Length = 0;
891 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
892 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
896 if (!(params = init_user_process_params( info_size ))) return FALSE;
897 peb->ProcessParameters = params;
899 /* convert value from server:
900 * + 0 => INVALID_HANDLE_VALUE
901 * + console handle need to be mapped
904 hstdin = INVALID_HANDLE_VALUE;
905 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
906 hstdin = console_handle_map(hstdin);
909 hstdout = INVALID_HANDLE_VALUE;
910 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
911 hstdout = console_handle_map(hstdout);
914 hstderr = INVALID_HANDLE_VALUE;
915 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
916 hstderr = console_handle_map(hstderr);
918 params->hStdInput = hstdin;
919 params->hStdOutput = hstdout;
920 params->hStdError = hstderr;
923 kernel32_handle = GetModuleHandleW(kernel32W);
927 /* Copy the parent environment */
928 if (!build_initial_environment( environ )) return FALSE;
930 /* Create device symlinks */
931 VOLUME_CreateDevices();
933 init_current_directory( ¶ms->CurrentDirectory );
935 /* registry initialisation */
936 SHELL_LoadRegistry();
938 /* global boot finished, the rest is process-local */
939 SERVER_START_REQ( boot_done )
941 req->debug_level = TRACE_ON(server);
942 wine_server_call( req );
946 if (!info_size) set_registry_environment();
954 /***********************************************************************
957 * Startup routine of a new process. Runs on the new process stack.
959 static void start_process( void *arg )
963 PEB *peb = NtCurrentTeb()->Peb;
964 IMAGE_NT_HEADERS *nt;
965 LPTHREAD_START_ROUTINE entry;
967 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
969 nt = RtlImageNtHeader( peb->ImageBaseAddress );
970 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
971 nt->OptionalHeader.AddressOfEntryPoint);
974 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
975 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
977 SetLastError( 0 ); /* clear error code */
978 if (peb->BeingDebugged) DbgBreakPoint();
979 ExitProcess( entry( peb ) );
981 __EXCEPT(UnhandledExceptionFilter)
983 TerminateThread( GetCurrentThread(), GetExceptionCode() );
989 /***********************************************************************
992 * Wine initialisation: load and start the main exe file.
994 void __wine_kernel_init(void)
996 WCHAR *main_exe_name, *p;
998 DWORD stack_size = 0;
1000 PEB *peb = NtCurrentTeb()->Peb;
1002 /* Initialize everything */
1003 if (!process_init( __wine_main_argv, __wine_main_environ )) exit(1);
1004 /* update argc in case options have been removed */
1005 for (__wine_main_argc = 0; __wine_main_argv[__wine_main_argc]; __wine_main_argc++) /*nothing*/;
1007 __wine_main_argv++; /* remove argv[0] (wine itself) */
1010 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1012 WCHAR buffer[MAX_PATH];
1013 WCHAR exe_nameW[MAX_PATH];
1015 if (!__wine_main_argv[0]) usage();
1016 if (__wine_main_argc == 1)
1018 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1019 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1022 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1023 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1025 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1028 if (main_exe_file == INVALID_HANDLE_VALUE)
1030 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1033 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1034 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1037 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1038 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1040 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1041 MODULE_get_dll_load_path(NULL) );
1042 VERSION_Init( main_exe_name );
1044 if (!main_exe_file) /* no file handle -> Winelib app */
1046 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1047 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1049 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1050 debugstr_w(main_exe_name), error );
1054 switch( MODULE_GetBinaryType( main_exe_file ))
1057 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1058 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1060 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1063 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1065 case BINARY_UNKNOWN:
1066 /* check for .com extension */
1067 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1069 MESSAGE( "wine: cannot determine executable type for %s\n",
1070 debugstr_w(main_exe_name) );
1076 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1077 CloseHandle( main_exe_file );
1081 __wine_main_argv[0] = "winevdm.exe";
1082 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1084 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1085 debugstr_w(main_exe_name), error );
1088 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
1090 case BINARY_UNIX_EXE:
1091 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1093 case BINARY_UNIX_LIB:
1097 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1098 CloseHandle( main_exe_file );
1100 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1101 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1103 static const WCHAR soW[] = {'.','s','o',0};
1104 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1107 /* update the unicode string */
1108 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1110 HeapFree( GetProcessHeap(), 0, unix_name );
1113 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1119 wine_free_pe_load_area(); /* the main binary is loaded, we don't need this anymore */
1121 /* build command line */
1122 set_library_wargv( __wine_main_argv );
1123 if (!build_command_line( __wine_main_wargv )) goto error;
1125 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1127 /* allocate main thread stack */
1128 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1130 /* switch to the new stack */
1131 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1134 ExitProcess( GetLastError() );
1138 /***********************************************************************
1141 * Build an argv array from a command-line.
1142 * 'reserved' is the number of args to reserve before the first one.
1144 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1148 char *arg,*s,*d,*cmdline;
1149 int in_quotes,bcount,len;
1151 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1152 if (!(cmdline = malloc(len))) return NULL;
1153 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1160 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1163 /* skip the remaining spaces */
1164 while (*s==' ' || *s=='\t') {
1171 } else if (*s=='\\') {
1172 /* '\', count them */
1174 } else if ((*s=='"') && ((bcount & 1)==0)) {
1176 in_quotes=!in_quotes;
1179 /* a regular character */
1184 argv=malloc(argc*sizeof(*argv));
1193 if ((*s==' ' || *s=='\t') && !in_quotes) {
1194 /* Close the argument and copy it */
1198 /* skip the remaining spaces */
1201 } while (*s==' ' || *s=='\t');
1203 /* Start with a new argument */
1206 } else if (*s=='\\') {
1210 } else if (*s=='"') {
1212 if ((bcount & 1)==0) {
1213 /* Preceeded by an even number of '\', this is half that
1214 * number of '\', plus a '"' which we discard.
1218 in_quotes=!in_quotes;
1220 /* Preceeded by an odd number of '\', this is half that
1221 * number of '\' followed by a '"'
1229 /* a regular character */
1244 /***********************************************************************
1247 * Allocate an environment string; helper for build_envp
1249 static char *alloc_env_string( const char *name, const char *value )
1251 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1252 strcpy( ret, name );
1253 strcat( ret, value );
1257 /***********************************************************************
1260 * Build the environment of a new child process.
1262 static char **build_envp( const WCHAR *envW )
1267 int count = 0, length;
1269 for (p = envW; *p; count++) p += strlenW(p) + 1;
1271 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, NULL, 0, NULL, NULL );
1272 if (!(env = malloc( length ))) return NULL;
1273 WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, env, length, NULL, NULL );
1277 if ((envp = malloc( count * sizeof(*envp) )))
1279 char **envptr = envp;
1282 /* then put PATH, TEMP, TMP, HOME and WINEPREFIX from the unix env */
1283 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1284 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1285 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1286 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1287 if ((p = getenv("WINEPREFIX"))) *envptr++ = alloc_env_string( "WINEPREFIX=", p );
1288 /* now put the Windows environment strings */
1289 for (p = env; *p; p += strlen(p) + 1)
1291 if (is_special_env_var( p )) /* prefix it with "WINE" */
1292 *envptr++ = alloc_env_string( "WINE", p );
1293 else if (strncmp( p, "HOME=", 5 ) &&
1294 strncmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
1302 /***********************************************************************
1305 * Fork and exec a new Unix binary, checking for errors.
1307 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1308 const WCHAR *env, const char *newdir )
1313 if (!env) env = GetEnvironmentStringsW();
1317 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1320 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1321 if (!(pid = fork())) /* child */
1323 char **argv = build_argv( cmdline, 0 );
1324 char **envp = build_envp( env );
1327 /* Reset signals that we previously set to SIG_IGN */
1328 signal( SIGPIPE, SIG_DFL );
1329 signal( SIGCHLD, SIG_DFL );
1331 if (newdir) chdir(newdir);
1333 if (argv && envp) execve( filename, argv, envp );
1335 write( fd[1], &err, sizeof(err) );
1339 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1344 if (pid == -1) FILE_SetDosError();
1350 /***********************************************************************
1351 * create_user_params
1353 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1354 LPCWSTR cur_dir, const STARTUPINFOW *startup )
1356 RTL_USER_PROCESS_PARAMETERS *params;
1357 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title;
1359 WCHAR buffer[MAX_PATH];
1361 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1362 lstrcpynW( buffer, filename, MAX_PATH );
1363 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1364 lstrcpynW( buffer, filename, MAX_PATH );
1365 RtlInitUnicodeString( &image_str, buffer );
1367 RtlInitUnicodeString( &cmdline_str, cmdline );
1368 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1369 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1370 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1372 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1373 cur_dir ? &curdir_str : NULL,
1375 startup->lpTitle ? &title : NULL,
1376 startup->lpDesktop ? &desktop : NULL,
1378 if (status != STATUS_SUCCESS)
1380 SetLastError( RtlNtStatusToDosError(status) );
1384 params->Environment = NULL; /* we pass it through the Unix environment */
1385 params->hStdInput = startup->hStdInput;
1386 params->hStdOutput = startup->hStdOutput;
1387 params->hStdError = startup->hStdError;
1388 params->dwX = startup->dwX;
1389 params->dwY = startup->dwY;
1390 params->dwXSize = startup->dwXSize;
1391 params->dwYSize = startup->dwYSize;
1392 params->dwXCountChars = startup->dwXCountChars;
1393 params->dwYCountChars = startup->dwYCountChars;
1394 params->dwFillAttribute = startup->dwFillAttribute;
1395 params->dwFlags = startup->dwFlags;
1396 params->wShowWindow = startup->wShowWindow;
1401 /***********************************************************************
1404 * Create a new process. If hFile is a valid handle we have an exe
1405 * file, otherwise it is a Winelib app.
1407 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1408 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1409 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1410 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1412 BOOL ret, success = FALSE;
1413 HANDLE process_info;
1414 RTL_USER_PROCESS_PARAMETERS *params;
1421 if (!env) env = GetEnvironmentStringsW();
1423 if (!(params = create_user_params( filename, cmd_line, cur_dir, startup )))
1426 /* create the synchronization pipes */
1428 if (pipe( startfd ) == -1)
1430 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1431 RtlDestroyProcessParameters( params );
1434 if (pipe( execfd ) == -1)
1436 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1437 close( startfd[0] );
1438 close( startfd[1] );
1439 RtlDestroyProcessParameters( params );
1442 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1444 /* create the child process */
1446 if (!(pid = fork())) /* child */
1448 char **argv = build_argv( cmd_line, 1 );
1449 char **envp = build_envp( env );
1451 close( startfd[1] );
1454 /* wait for parent to tell us to start */
1455 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1457 close( startfd[0] );
1458 /* Reset signals that we previously set to SIG_IGN */
1459 signal( SIGPIPE, SIG_DFL );
1460 signal( SIGCHLD, SIG_DFL );
1462 if (unixdir) chdir(unixdir);
1466 /* first, try for a WINELOADER environment variable */
1467 argv[0] = getenv("WINELOADER");
1468 if (argv[0]) execve( argv[0], argv, envp );
1469 /* now use the standard search strategy */
1470 wine_exec_wine_binary( NULL, argv, envp );
1473 write( execfd[1], &err, sizeof(err) );
1477 /* this is the parent */
1479 close( startfd[0] );
1483 close( startfd[1] );
1486 RtlDestroyProcessParameters( params );
1490 /* create the process on the server side */
1492 SERVER_START_REQ( new_process )
1494 req->inherit_all = inherit;
1495 req->create_flags = flags;
1496 req->unix_pid = pid;
1497 req->exe_file = hFile;
1498 if (startup->dwFlags & STARTF_USESTDHANDLES)
1500 req->hstdin = startup->hStdInput;
1501 req->hstdout = startup->hStdOutput;
1502 req->hstderr = startup->hStdError;
1506 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1507 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1508 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1511 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1513 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1514 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1515 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1516 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1520 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1521 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1522 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1525 wine_server_add_data( req, params, params->Size );
1526 ret = !wine_server_call_err( req );
1527 process_info = reply->info;
1531 RtlDestroyProcessParameters( params );
1534 close( startfd[1] );
1539 /* tell child to start and wait for it to exec */
1541 write( startfd[1], &dummy, 1 );
1542 close( startfd[1] );
1544 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1549 CloseHandle( process_info );
1554 /* wait for the new process info to be ready */
1556 WaitForSingleObject( process_info, INFINITE );
1557 SERVER_START_REQ( get_new_process_info )
1559 req->info = process_info;
1560 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1561 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1562 if ((ret = !wine_server_call_err( req )))
1564 info->dwProcessId = (DWORD)reply->pid;
1565 info->dwThreadId = (DWORD)reply->tid;
1566 info->hProcess = reply->phandle;
1567 info->hThread = reply->thandle;
1568 success = reply->success;
1573 if (ret && !success) /* new process failed to start */
1576 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1577 CloseHandle( info->hThread );
1578 CloseHandle( info->hProcess );
1581 CloseHandle( process_info );
1586 /***********************************************************************
1587 * create_vdm_process
1589 * Create a new VDM process for a 16-bit or DOS application.
1591 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1592 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1593 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1594 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1596 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1599 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1600 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1604 SetLastError( ERROR_OUTOFMEMORY );
1607 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1608 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1609 flags, startup, info, unixdir );
1610 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1615 /***********************************************************************
1616 * create_cmd_process
1618 * Create a new cmd shell process for a .BAT file.
1620 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1621 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1622 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1623 LPPROCESS_INFORMATION info )
1626 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1627 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1628 WCHAR comspec[MAX_PATH];
1632 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1634 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1635 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1638 strcpyW( newcmdline, comspec );
1639 strcatW( newcmdline, slashcW );
1640 strcatW( newcmdline, cmd_line );
1641 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1642 flags, env, cur_dir, startup, info );
1643 HeapFree( GetProcessHeap(), 0, newcmdline );
1648 /*************************************************************************
1651 * Helper for CreateProcess: retrieve the file name to load from the
1652 * app name and command line. Store the file name in buffer, and
1653 * return a possibly modified command line.
1654 * Also returns a handle to the opened file if it's a Windows binary.
1656 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1657 int buflen, HANDLE *handle )
1659 static const WCHAR quotesW[] = {'"','%','s','"',0};
1661 WCHAR *name, *pos, *ret = NULL;
1664 /* if we have an app name, everything is easy */
1668 /* use the unmodified app name as file name */
1669 lstrcpynW( buffer, appname, buflen );
1670 *handle = open_exe_file( buffer );
1671 if (!(ret = cmdline) || !cmdline[0])
1673 /* no command-line, create one */
1674 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1675 sprintfW( ret, quotesW, appname );
1682 SetLastError( ERROR_INVALID_PARAMETER );
1686 /* first check for a quoted file name */
1688 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1690 int len = p - cmdline - 1;
1691 /* extract the quoted portion as file name */
1692 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1693 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1696 if (find_exe_file( name, buffer, buflen, handle ))
1697 ret = cmdline; /* no change necessary */
1701 /* now try the command-line word by word */
1703 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1710 do *pos++ = *p++; while (*p && *p != ' ');
1712 if (find_exe_file( name, buffer, buflen, handle ))
1719 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1721 /* now build a new command-line with quotes */
1723 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1725 sprintfW( ret, quotesW, name );
1729 HeapFree( GetProcessHeap(), 0, name );
1734 /**********************************************************************
1735 * CreateProcessA (KERNEL32.@)
1737 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1738 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1739 DWORD flags, LPVOID env, LPCSTR cur_dir,
1740 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1743 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1744 UNICODE_STRING desktopW, titleW;
1747 desktopW.Buffer = NULL;
1748 titleW.Buffer = NULL;
1749 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1750 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1751 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1753 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1754 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1756 memcpy( &infoW, startup_info, sizeof(infoW) );
1757 infoW.lpDesktop = desktopW.Buffer;
1758 infoW.lpTitle = titleW.Buffer;
1760 if (startup_info->lpReserved)
1761 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1762 debugstr_a(startup_info->lpReserved));
1764 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1765 inherit, flags, env, cur_dirW, &infoW, info );
1767 if (app_nameW) HeapFree( GetProcessHeap(), 0, app_nameW );
1768 if (cmd_lineW) HeapFree( GetProcessHeap(), 0, cmd_lineW );
1769 if (cur_dirW) HeapFree( GetProcessHeap(), 0, cur_dirW );
1770 RtlFreeUnicodeString( &desktopW );
1771 RtlFreeUnicodeString( &titleW );
1776 /**********************************************************************
1777 * CreateProcessW (KERNEL32.@)
1779 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1780 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1781 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1782 LPPROCESS_INFORMATION info )
1786 char *unixdir = NULL;
1787 WCHAR name[MAX_PATH];
1788 WCHAR *tidy_cmdline, *p, *envW = env;
1790 /* Process the AppName and/or CmdLine to get module name and path */
1792 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1794 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1796 if (hFile == INVALID_HANDLE_VALUE) goto done;
1798 /* Warn if unsupported features are used */
1800 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1801 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1802 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1803 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1804 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1808 unixdir = wine_get_unix_file_name( cur_dir );
1812 WCHAR buf[MAX_PATH];
1813 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1816 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1821 while (*p) p += strlen(p) + 1;
1822 p++; /* final null */
1823 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1824 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1825 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1826 flags |= CREATE_UNICODE_ENVIRONMENT;
1829 info->hThread = info->hProcess = 0;
1830 info->dwProcessId = info->dwThreadId = 0;
1832 /* Determine executable type */
1834 if (!hFile) /* builtin exe */
1836 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1837 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1838 inherit, flags, startup_info, info, unixdir );
1842 switch( MODULE_GetBinaryType( hFile ))
1845 TRACE( "starting %s as Win32 binary\n", debugstr_w(name) );
1846 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1847 inherit, flags, startup_info, info, unixdir );
1851 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1852 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1853 inherit, flags, startup_info, info, unixdir );
1856 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1857 SetLastError( ERROR_BAD_EXE_FORMAT );
1860 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1861 SetLastError( ERROR_BAD_EXE_FORMAT );
1863 case BINARY_UNIX_LIB:
1864 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1865 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1866 inherit, flags, startup_info, info, unixdir );
1868 case BINARY_UNKNOWN:
1869 /* check for .com or .bat extension */
1870 if ((p = strrchrW( name, '.' )))
1872 if (!strcmpiW( p, comW ))
1874 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1875 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1876 inherit, flags, startup_info, info, unixdir );
1879 if (!strcmpiW( p, batW ))
1881 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1882 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1883 inherit, flags, startup_info, info );
1888 case BINARY_UNIX_EXE:
1890 /* unknown file, try as unix executable */
1893 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1895 if ((unix_name = wine_get_unix_file_name( name )))
1897 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1898 HeapFree( GetProcessHeap(), 0, unix_name );
1903 CloseHandle( hFile );
1906 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1907 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1908 if (unixdir) HeapFree( GetProcessHeap(), 0, unixdir );
1913 /***********************************************************************
1916 * Wrapper to call WaitForInputIdle USER function
1918 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1920 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1922 HMODULE mod = GetModuleHandleA( "user32.dll" );
1925 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1926 if (ptr) return ptr( process, timeout );
1932 /***********************************************************************
1933 * WinExec (KERNEL32.@)
1935 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1937 PROCESS_INFORMATION info;
1938 STARTUPINFOA startup;
1942 memset( &startup, 0, sizeof(startup) );
1943 startup.cb = sizeof(startup);
1944 startup.dwFlags = STARTF_USESHOWWINDOW;
1945 startup.wShowWindow = nCmdShow;
1947 /* cmdline needs to be writeable for CreateProcess */
1948 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1949 strcpy( cmdline, lpCmdLine );
1951 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1952 0, NULL, NULL, &startup, &info ))
1954 /* Give 30 seconds to the app to come up */
1955 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1956 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1958 /* Close off the handles */
1959 CloseHandle( info.hThread );
1960 CloseHandle( info.hProcess );
1962 else if ((ret = GetLastError()) >= 32)
1964 FIXME("Strange error set by CreateProcess: %d\n", ret );
1967 HeapFree( GetProcessHeap(), 0, cmdline );
1972 /**********************************************************************
1973 * LoadModule (KERNEL32.@)
1975 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1977 LOADPARMS32 *params = paramBlock;
1978 PROCESS_INFORMATION info;
1979 STARTUPINFOA startup;
1980 HINSTANCE hInstance;
1982 char filename[MAX_PATH];
1985 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1987 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1988 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1989 return (HINSTANCE)GetLastError();
1991 len = (BYTE)params->lpCmdLine[0];
1992 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1993 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1995 strcpy( cmdline, filename );
1996 p = cmdline + strlen(cmdline);
1998 memcpy( p, params->lpCmdLine + 1, len );
2001 memset( &startup, 0, sizeof(startup) );
2002 startup.cb = sizeof(startup);
2003 if (params->lpCmdShow)
2005 startup.dwFlags = STARTF_USESHOWWINDOW;
2006 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2009 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2010 params->lpEnvAddress, NULL, &startup, &info ))
2012 /* Give 30 seconds to the app to come up */
2013 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2014 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2015 hInstance = (HINSTANCE)33;
2016 /* Close off the handles */
2017 CloseHandle( info.hThread );
2018 CloseHandle( info.hProcess );
2020 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2022 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2023 hInstance = (HINSTANCE)11;
2026 HeapFree( GetProcessHeap(), 0, cmdline );
2031 /******************************************************************************
2032 * TerminateProcess (KERNEL32.@)
2034 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2036 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2037 if (status) SetLastError( RtlNtStatusToDosError(status) );
2042 /***********************************************************************
2043 * ExitProcess (KERNEL32.@)
2045 void WINAPI ExitProcess( DWORD status )
2047 LdrShutdownProcess();
2048 SERVER_START_REQ( terminate_process )
2050 /* send the exit code to the server */
2051 req->handle = GetCurrentProcess();
2052 req->exit_code = status;
2053 wine_server_call( req );
2060 /***********************************************************************
2061 * GetExitCodeProcess [KERNEL32.@]
2063 * Gets termination status of specified process
2069 BOOL WINAPI GetExitCodeProcess(
2070 HANDLE hProcess, /* [in] handle to the process */
2071 LPDWORD lpExitCode) /* [out] address to receive termination status */
2074 SERVER_START_REQ( get_process_info )
2076 req->handle = hProcess;
2077 ret = !wine_server_call_err( req );
2078 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
2085 /***********************************************************************
2086 * SetErrorMode (KERNEL32.@)
2088 UINT WINAPI SetErrorMode( UINT mode )
2090 UINT old = process_error_mode;
2091 process_error_mode = mode;
2096 /**********************************************************************
2097 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2099 * Allocates a thread local storage index
2102 * Success: TLS Index
2103 * Failure: 0xFFFFFFFF
2105 DWORD WINAPI TlsAlloc( void )
2109 RtlAcquirePebLock();
2110 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
2111 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2112 else SetLastError( ERROR_NO_MORE_ITEMS );
2113 RtlReleasePebLock();
2118 /**********************************************************************
2119 * TlsFree [KERNEL32.@] Releases a TLS index.
2121 * Releases a thread local storage index, making it available for reuse
2127 BOOL WINAPI TlsFree(
2128 DWORD index) /* [in] TLS Index to free */
2132 RtlAcquirePebLock();
2133 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2136 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2137 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2139 else SetLastError( ERROR_INVALID_PARAMETER );
2140 RtlReleasePebLock();
2145 /**********************************************************************
2146 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2149 * Success: Value stored in calling thread's TLS slot for index
2150 * Failure: 0 and GetLastError returns NO_ERROR
2152 LPVOID WINAPI TlsGetValue(
2153 DWORD index) /* [in] TLS index to retrieve value for */
2155 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2157 SetLastError( ERROR_INVALID_PARAMETER );
2160 SetLastError( ERROR_SUCCESS );
2161 return NtCurrentTeb()->TlsSlots[index];
2165 /**********************************************************************
2166 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2172 BOOL WINAPI TlsSetValue(
2173 DWORD index, /* [in] TLS index to set value for */
2174 LPVOID value) /* [in] Value to be stored */
2176 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2178 SetLastError( ERROR_INVALID_PARAMETER );
2181 NtCurrentTeb()->TlsSlots[index] = value;
2186 /***********************************************************************
2187 * GetProcessFlags (KERNEL32.@)
2189 DWORD WINAPI GetProcessFlags( DWORD processid )
2191 IMAGE_NT_HEADERS *nt;
2194 if (processid && processid != GetCurrentProcessId()) return 0;
2196 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2198 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2199 flags |= PDB32_CONSOLE_PROC;
2201 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2202 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2207 /***********************************************************************
2208 * GetProcessDword (KERNEL.485)
2209 * GetProcessDword (KERNEL32.18)
2210 * 'Of course you cannot directly access Windows internal structures'
2212 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2217 TRACE("(%ld, %d)\n", dwProcessID, offset );
2219 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2221 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2227 case GPD_APP_COMPAT_FLAGS:
2228 return GetAppCompatFlags16(0);
2229 case GPD_LOAD_DONE_EVENT:
2231 case GPD_HINSTANCE16:
2232 return GetTaskDS16();
2233 case GPD_WINDOWS_VERSION:
2234 return GetExeVersion16();
2236 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2238 return (DWORD)NtCurrentTeb()->Peb;
2239 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2240 GetStartupInfoW(&siw);
2241 return (DWORD)siw.hStdOutput;
2242 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2243 GetStartupInfoW(&siw);
2244 return (DWORD)siw.hStdInput;
2245 case GPD_STARTF_SHOWWINDOW:
2246 GetStartupInfoW(&siw);
2247 return siw.wShowWindow;
2248 case GPD_STARTF_SIZE:
2249 GetStartupInfoW(&siw);
2251 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2253 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2254 return MAKELONG( x, y );
2255 case GPD_STARTF_POSITION:
2256 GetStartupInfoW(&siw);
2258 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2260 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2261 return MAKELONG( x, y );
2262 case GPD_STARTF_FLAGS:
2263 GetStartupInfoW(&siw);
2268 return GetProcessFlags(0);
2270 return process_dword;
2272 ERR("Unknown offset %d\n", offset );
2277 /***********************************************************************
2278 * SetProcessDword (KERNEL.484)
2279 * 'Of course you cannot directly access Windows internal structures'
2281 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2283 TRACE("(%ld, %d)\n", dwProcessID, offset );
2285 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2287 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2293 case GPD_APP_COMPAT_FLAGS:
2294 case GPD_LOAD_DONE_EVENT:
2295 case GPD_HINSTANCE16:
2296 case GPD_WINDOWS_VERSION:
2299 case GPD_STARTF_SHELLDATA:
2300 case GPD_STARTF_HOTKEY:
2301 case GPD_STARTF_SHOWWINDOW:
2302 case GPD_STARTF_SIZE:
2303 case GPD_STARTF_POSITION:
2304 case GPD_STARTF_FLAGS:
2307 ERR("Not allowed to modify offset %d\n", offset );
2310 process_dword = value;
2313 ERR("Unknown offset %d\n", offset );
2319 /***********************************************************************
2320 * ExitProcess (KERNEL.466)
2322 void WINAPI ExitProcess16( WORD status )
2325 ReleaseThunkLock( &count );
2326 ExitProcess( status );
2330 /*********************************************************************
2331 * OpenProcess (KERNEL32.@)
2333 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2336 SERVER_START_REQ( open_process )
2339 req->access = access;
2340 req->inherit = inherit;
2341 if (!wine_server_call_err( req )) ret = reply->handle;
2348 /*********************************************************************
2349 * MapProcessHandle (KERNEL.483)
2351 DWORD WINAPI MapProcessHandle( HANDLE handle )
2354 SERVER_START_REQ( get_process_info )
2356 req->handle = handle;
2357 if (!wine_server_call_err( req )) ret = reply->pid;
2364 /*********************************************************************
2365 * CloseW32Handle (KERNEL.474)
2366 * CloseHandle (KERNEL32.@)
2368 BOOL WINAPI CloseHandle( HANDLE handle )
2372 /* stdio handles need special treatment */
2373 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2374 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2375 (handle == (HANDLE)STD_ERROR_HANDLE))
2376 handle = GetStdHandle( (DWORD)handle );
2378 if (is_console_handle(handle))
2379 return CloseConsoleHandle(handle);
2381 status = NtClose( handle );
2382 if (status) SetLastError( RtlNtStatusToDosError(status) );
2387 /*********************************************************************
2388 * GetHandleInformation (KERNEL32.@)
2390 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2393 SERVER_START_REQ( set_handle_info )
2395 req->handle = handle;
2399 ret = !wine_server_call_err( req );
2400 if (ret && flags) *flags = reply->old_flags;
2407 /*********************************************************************
2408 * SetHandleInformation (KERNEL32.@)
2410 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2413 SERVER_START_REQ( set_handle_info )
2415 req->handle = handle;
2419 ret = !wine_server_call_err( req );
2426 /*********************************************************************
2427 * DuplicateHandle (KERNEL32.@)
2429 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2430 HANDLE dest_process, HANDLE *dest,
2431 DWORD access, BOOL inherit, DWORD options )
2435 if (is_console_handle(source))
2437 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2438 if (source_process != dest_process ||
2439 source_process != GetCurrentProcess())
2441 SetLastError(ERROR_INVALID_PARAMETER);
2444 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2445 return (*dest != INVALID_HANDLE_VALUE);
2447 status = NtDuplicateObject( source_process, source, dest_process, dest,
2448 access, inherit ? OBJ_INHERIT : 0, options );
2449 if (status) SetLastError( RtlNtStatusToDosError(status) );
2454 /***********************************************************************
2455 * ConvertToGlobalHandle (KERNEL.476)
2456 * ConvertToGlobalHandle (KERNEL32.@)
2458 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2460 HANDLE ret = INVALID_HANDLE_VALUE;
2461 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2462 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2467 /***********************************************************************
2468 * SetHandleContext (KERNEL32.@)
2470 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2472 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2473 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2474 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2479 /***********************************************************************
2480 * GetHandleContext (KERNEL32.@)
2482 DWORD WINAPI GetHandleContext(HANDLE hnd)
2484 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2485 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2486 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2491 /***********************************************************************
2492 * CreateSocketHandle (KERNEL32.@)
2494 HANDLE WINAPI CreateSocketHandle(void)
2496 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2497 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2498 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2499 return INVALID_HANDLE_VALUE;
2503 /***********************************************************************
2504 * SetPriorityClass (KERNEL32.@)
2506 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2509 SERVER_START_REQ( set_process_info )
2511 req->handle = hprocess;
2512 req->priority = priorityclass;
2513 req->mask = SET_PROCESS_INFO_PRIORITY;
2514 ret = !wine_server_call_err( req );
2521 /***********************************************************************
2522 * GetPriorityClass (KERNEL32.@)
2524 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2527 SERVER_START_REQ( get_process_info )
2529 req->handle = hprocess;
2530 if (!wine_server_call_err( req )) ret = reply->priority;
2537 /***********************************************************************
2538 * SetProcessAffinityMask (KERNEL32.@)
2540 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2543 SERVER_START_REQ( set_process_info )
2545 req->handle = hProcess;
2546 req->affinity = affmask;
2547 req->mask = SET_PROCESS_INFO_AFFINITY;
2548 ret = !wine_server_call_err( req );
2555 /**********************************************************************
2556 * GetProcessAffinityMask (KERNEL32.@)
2558 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2559 LPDWORD lpProcessAffinityMask,
2560 LPDWORD lpSystemAffinityMask )
2563 SERVER_START_REQ( get_process_info )
2565 req->handle = hProcess;
2566 if (!wine_server_call_err( req ))
2568 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2569 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2578 /***********************************************************************
2579 * GetProcessVersion (KERNEL32.@)
2581 DWORD WINAPI GetProcessVersion( DWORD processid )
2583 IMAGE_NT_HEADERS *nt;
2585 if (processid && processid != GetCurrentProcessId())
2587 FIXME("should use ReadProcessMemory\n");
2590 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2591 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2592 nt->OptionalHeader.MinorSubsystemVersion);
2597 /***********************************************************************
2598 * SetProcessWorkingSetSize [KERNEL32.@]
2599 * Sets the min/max working set sizes for a specified process.
2602 * hProcess [I] Handle to the process of interest
2603 * minset [I] Specifies minimum working set size
2604 * maxset [I] Specifies maximum working set size
2608 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2611 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2612 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2613 /* Trim the working set to zero */
2614 /* Swap the process out of physical RAM */
2619 /***********************************************************************
2620 * GetProcessWorkingSetSize (KERNEL32.@)
2622 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2625 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2626 /* 32 MB working set size */
2627 if (minset) *minset = 32*1024*1024;
2628 if (maxset) *maxset = 32*1024*1024;
2633 /***********************************************************************
2634 * SetProcessShutdownParameters (KERNEL32.@)
2636 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2638 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2639 shutdown_flags = flags;
2640 shutdown_priority = level;
2645 /***********************************************************************
2646 * GetProcessShutdownParameters (KERNEL32.@)
2649 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2651 *lpdwLevel = shutdown_priority;
2652 *lpdwFlags = shutdown_flags;
2657 /***********************************************************************
2658 * GetProcessPriorityBoost (KERNEL32.@)
2660 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2662 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2664 /* Report that no boost is present.. */
2665 *pDisablePriorityBoost = FALSE;
2670 /***********************************************************************
2671 * SetProcessPriorityBoost (KERNEL32.@)
2673 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2675 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2676 /* Say we can do it. I doubt the program will notice that we don't. */
2681 /***********************************************************************
2682 * ReadProcessMemory (KERNEL32.@)
2684 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2685 SIZE_T *bytes_read )
2687 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2688 if (status) SetLastError( RtlNtStatusToDosError(status) );
2693 /***********************************************************************
2694 * WriteProcessMemory (KERNEL32.@)
2696 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2697 SIZE_T *bytes_written )
2699 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2700 if (status) SetLastError( RtlNtStatusToDosError(status) );
2705 /****************************************************************************
2706 * FlushInstructionCache (KERNEL32.@)
2708 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2710 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2711 FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2716 /******************************************************************
2717 * GetProcessIoCounters (KERNEL32.@)
2719 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2723 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2724 ioc, sizeof(*ioc), NULL);
2725 if (status) SetLastError( RtlNtStatusToDosError(status) );
2729 /***********************************************************************
2730 * ProcessIdToSessionId (KERNEL32.@)
2731 * This function is available on Terminal Server 4SP4 and Windows 2000
2733 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2735 /* According to MSDN, if the calling process is not in a terminal
2736 * services environment, then the sessionid returned is zero.
2743 /***********************************************************************
2744 * RegisterServiceProcess (KERNEL.491)
2745 * RegisterServiceProcess (KERNEL32.@)
2747 * A service process calls this function to ensure that it continues to run
2748 * even after a user logged off.
2750 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2752 /* I don't think that Wine needs to do anything in that function */
2753 return 1; /* success */
2757 /***********************************************************************
2758 * GetSystemMSecCount (SYSTEM.6)
2759 * GetTickCount (KERNEL32.@)
2761 * Returns the number of milliseconds, modulo 2^32, since the start
2762 * of the wineserver.
2764 DWORD WINAPI GetTickCount(void)
2767 gettimeofday( &t, NULL );
2768 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2772 /***********************************************************************
2773 * GetCurrentProcess (KERNEL32.@)
2775 #undef GetCurrentProcess
2776 HANDLE WINAPI GetCurrentProcess(void)
2778 return (HANDLE)0xffffffff;