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, "HOME=", sizeof("HOME=")-1 ) ||
110 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
111 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
115 /***************************************************************************
118 * Get the path of a builtin module when the native file does not exist.
120 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
123 UINT len = strlenW( DIR_System );
125 if (contains_path( libname ))
127 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
128 filename, &file_part ) > size * sizeof(WCHAR))
129 return FALSE; /* too long */
131 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
133 while (filename[len] == '\\') len++;
134 if (filename + len != file_part) return FALSE;
138 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
139 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
140 file_part = filename + len;
141 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
142 strcpyW( file_part, libname );
144 if (ext && !strchrW( file_part, '.' ))
146 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
147 return FALSE; /* too long */
148 strcatW( file_part, ext );
154 /***********************************************************************
155 * open_builtin_exe_file
157 * Open an exe file for a builtin exe.
159 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
160 int test_only, int *file_exists )
162 char exename[MAX_PATH];
166 if ((p = strrchrW( name, '/' ))) name = p + 1;
167 if ((p = strrchrW( name, '\\' ))) name = p + 1;
169 /* we don't want to depend on the current codepage here */
170 len = strlenW( name ) + 1;
171 if (len >= sizeof(exename)) return NULL;
172 for (i = 0; i < len; i++)
174 if (name[i] > 127) return NULL;
175 exename[i] = (char)name[i];
176 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
178 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
182 /***********************************************************************
185 * Open a specific exe file, taking load order into account.
186 * Returns the file handle or 0 for a builtin exe.
188 static HANDLE open_exe_file( const WCHAR *name )
190 enum loadorder_type loadorder[LOADORDER_NTYPES];
191 WCHAR buffer[MAX_PATH];
195 TRACE("looking for %s\n", debugstr_w(name) );
197 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ,
198 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
200 /* file doesn't exist, check for builtin */
201 if (!contains_path( name )) goto error;
202 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
206 MODULE_GetLoadOrderW( loadorder, NULL, name );
208 for(i = 0; i < LOADORDER_NTYPES; i++)
210 if (loadorder[i] == LOADORDER_INVALID) break;
214 TRACE( "Trying native exe %s\n", debugstr_w(name) );
215 if (handle != INVALID_HANDLE_VALUE) return handle;
218 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
219 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
222 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
229 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
232 SetLastError( ERROR_FILE_NOT_FOUND );
233 return INVALID_HANDLE_VALUE;
237 /***********************************************************************
240 * Open an exe file, and return the full name and file handle.
241 * Returns FALSE if file could not be found.
242 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
243 * If file is a builtin exe, returns TRUE and sets handle to 0.
245 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
247 static const WCHAR exeW[] = {'.','e','x','e',0};
249 enum loadorder_type loadorder[LOADORDER_NTYPES];
252 TRACE("looking for %s\n", debugstr_w(name) );
254 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
255 !get_builtin_path( name, exeW, buffer, buflen ))
257 /* no builtin found, try native without extension in case it is a Unix app */
259 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
261 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
262 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
263 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
269 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
271 for(i = 0; i < LOADORDER_NTYPES; i++)
273 if (loadorder[i] == LOADORDER_INVALID) break;
277 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
278 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
279 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
281 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
284 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
285 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
296 SetLastError( ERROR_FILE_NOT_FOUND );
301 /**********************************************************************
304 * Load a PE format EXE file.
306 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
308 IMAGE_NT_HEADERS *nt;
311 OBJECT_ATTRIBUTES attr;
316 attr.Length = sizeof(attr);
317 attr.RootDirectory = 0;
318 attr.ObjectName = NULL;
320 attr.SecurityDescriptor = NULL;
321 attr.SecurityQualityOfService = NULL;
324 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
325 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
329 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
330 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
336 nt = RtlImageNtHeader( module );
337 if (nt->OptionalHeader.AddressOfEntryPoint)
339 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
340 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
341 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
342 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
345 drive_type = GetDriveTypeW( name );
346 /* don't keep the file handle open on removable media */
347 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM)
349 CloseHandle( main_exe_file );
356 /***********************************************************************
357 * build_initial_environment
359 * Build the Win32 environment from the Unix environment
361 static BOOL build_initial_environment( char **environ )
368 /* Compute the total size of the Unix environment */
369 for (e = environ; *e; e++)
371 if (is_special_env_var( *e )) continue;
372 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
374 size *= sizeof(WCHAR);
376 /* Now allocate the environment */
377 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
378 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
381 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
382 endptr = p + size / sizeof(WCHAR);
384 /* And fill it with the Unix environment */
385 for (e = environ; *e; e++)
389 /* skip Unix special variables and use the Wine variants instead */
390 if (!strncmp( str, "WINE", 4 ))
392 if (is_special_env_var( str + 4 )) str += 4;
393 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
395 else if (is_special_env_var( str )) continue; /* skip it */
397 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
405 /***********************************************************************
406 * set_registry_variables
408 * Set environment variables by enumerating the values of a key;
409 * helper for set_registry_environment().
411 static void set_registry_variables( HKEY hkey )
413 UNICODE_STRING env_name, env_value;
417 char buffer[1024 + sizeof(KEY_VALUE_FULL_INFORMATION)];
418 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
420 for (index = 0; ; index++)
422 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
423 buffer, sizeof(buffer), &size );
424 if (status == STATUS_BUFFER_OVERFLOW) continue;
425 if (status != STATUS_SUCCESS) break;
426 if (info->Type != REG_SZ) continue; /* FIXME: handle REG_EXPAND_SZ */
427 env_name.Buffer = info->Name;
428 env_name.Length = env_name.MaximumLength = info->NameLength;
429 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
430 env_value.Length = env_value.MaximumLength = info->DataLength;
431 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
432 env_value.Length--; /* don't count terminating null if any */
433 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
438 /***********************************************************************
439 * set_registry_environment
441 * Set the environment variables specified in the registry.
443 static void set_registry_environment(void)
445 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
446 'S','y','s','t','e','m','\\',
447 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
448 'C','o','n','t','r','o','l','\\',
449 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
450 'E','n','v','i','r','o','n','m','e','n','t',0};
451 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
453 OBJECT_ATTRIBUTES attr;
454 UNICODE_STRING nameW;
457 attr.Length = sizeof(attr);
458 attr.RootDirectory = 0;
459 attr.ObjectName = &nameW;
461 attr.SecurityDescriptor = NULL;
462 attr.SecurityQualityOfService = NULL;
464 /* first the system environment variables */
465 RtlInitUnicodeString( &nameW, env_keyW );
466 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
468 set_registry_variables( hkey );
472 /* then the ones for the current user */
473 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, (HKEY *)&attr.RootDirectory ) != STATUS_SUCCESS) return;
474 RtlInitUnicodeString( &nameW, envW );
475 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
477 set_registry_variables( hkey );
480 NtClose( attr.RootDirectory );
484 /***********************************************************************
487 * Set the Wine library Unicode argv global variables.
489 static void set_library_wargv( char **argv )
497 for (argc = 0; argv[argc]; argc++)
498 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
500 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
501 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
502 p = (WCHAR *)(wargv + argc + 1);
503 for (argc = 0; argv[argc]; argc++)
505 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
512 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
514 for (argc = 0; wargv[argc]; argc++)
515 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
517 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
518 q = (char *)(argv + argc + 1);
519 for (argc = 0; wargv[argc]; argc++)
521 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
528 __wine_main_argv = argv;
529 __wine_main_wargv = wargv;
533 /***********************************************************************
536 * Build the command line of a process from the argv array.
538 * Note that it does NOT necessarily include the file name.
539 * Sometimes we don't even have any command line options at all.
541 * We must quote and escape characters so that the argv array can be rebuilt
542 * from the command line:
543 * - spaces and tabs must be quoted
545 * - quotes must be escaped
547 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
548 * resulting in an odd number of '\' followed by a '"'
551 * - '\'s that are not followed by a '"' can be left as is
555 static BOOL build_command_line( WCHAR **argv )
560 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
562 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
565 for (arg = argv; *arg; arg++)
567 int has_space,bcount;
573 if( !*a ) has_space=1;
578 if (*a==' ' || *a=='\t') {
580 } else if (*a=='"') {
581 /* doubling of '\' preceeding a '"',
582 * plus escaping of said '"'
590 len+=(a-*arg)+1 /* for the separating space */;
592 len+=2; /* for the quotes */
595 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
598 p = rupp->CommandLine.Buffer;
599 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
600 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
601 for (arg = argv; *arg; arg++)
603 int has_space,has_quote;
606 /* Check for quotes and spaces in this argument */
607 has_space=has_quote=0;
609 if( !*a ) has_space=1;
611 if (*a==' ' || *a=='\t') {
615 } else if (*a=='"') {
623 /* Now transfer it to the command line */
640 /* Double all the '\\' preceeding this '"', plus one */
641 for (i=0;i<=bcount;i++)
653 while ((*p=*x++)) p++;
659 if (p > rupp->CommandLine.Buffer)
660 p--; /* remove last space */
667 /* make sure the unicode string doesn't point beyond the end pointer */
668 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
670 if ((char *)str->Buffer >= end_ptr)
672 str->Length = str->MaximumLength = 0;
676 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
678 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
680 if (str->Length >= str->MaximumLength)
682 if (str->MaximumLength >= sizeof(WCHAR))
683 str->Length = str->MaximumLength - sizeof(WCHAR);
685 str->Length = str->MaximumLength = 0;
689 static void version(void)
691 MESSAGE( "%s\n", PACKAGE_STRING );
695 static void usage(void)
697 MESSAGE( "%s\n", PACKAGE_STRING );
698 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
699 MESSAGE( " wine --help Display this help and exit\n");
700 MESSAGE( " wine --version Output version information and exit\n");
705 /***********************************************************************
706 * init_user_process_params
708 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
710 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
713 DWORD size, env_size;
714 RTL_USER_PROCESS_PARAMETERS *params;
717 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
718 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
721 SERVER_START_REQ( get_startup_info )
723 wine_server_set_reply( req, ptr, info_size );
724 wine_server_call( req );
725 info_size = wine_server_reply_size( reply );
730 params->AllocationSize = size;
731 if (params->Size > info_size) params->Size = info_size;
733 /* make sure the strings are valid */
734 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
735 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
736 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
737 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
738 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
739 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
740 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
741 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
743 /* environment needs to be a separate memory block */
744 env_size = info_size - params->Size;
745 if (!env_size) env_size = 1;
746 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &env_size,
747 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
749 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
750 params->Environment = ptr;
752 return RtlNormalizeProcessParams( params );
756 /***********************************************************************
757 * init_current_directory
759 * Initialize the current directory from the Unix cwd or the parent info.
761 static void init_current_directory( CURDIR *cur_dir )
763 UNICODE_STRING dir_str;
767 /* if we received a cur dir from the parent, try this first */
769 if (cur_dir->DosPath.Length)
771 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
774 /* now try to get it from the Unix cwd */
776 for (size = 256; ; size *= 2)
778 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
779 if (getcwd( cwd, size )) break;
780 HeapFree( GetProcessHeap(), 0, cwd );
781 if (errno == ERANGE) continue;
789 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
790 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
792 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
793 RtlInitUnicodeString( &dir_str, dirW );
794 RtlSetCurrentDirectory_U( &dir_str );
795 RtlFreeUnicodeString( &dir_str );
799 if (!cur_dir->DosPath.Length) /* still not initialized */
801 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
802 "starting in the Windows directory.\n", cwd ? cwd : "" );
803 RtlInitUnicodeString( &dir_str, DIR_Windows );
804 RtlSetCurrentDirectory_U( &dir_str );
806 if (cwd) HeapFree( GetProcessHeap(), 0, cwd );
809 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
810 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
814 /***********************************************************************
817 * Initialize the windows and system directories from the environment.
819 static void init_windows_dirs(void)
821 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
823 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
824 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
825 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
826 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m',0};
831 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
833 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
834 GetEnvironmentVariableW( windirW, buffer, len );
835 DIR_Windows = buffer;
837 else DIR_Windows = default_windirW;
839 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
841 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
842 GetEnvironmentVariableW( winsysdirW, buffer, len );
847 len = strlenW( DIR_Windows );
848 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
849 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
850 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
854 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
855 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
856 debugstr_w(DIR_Windows) );
857 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
858 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
859 debugstr_w(DIR_System) );
861 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
862 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
864 /* set the directories in ntdll too */
865 __wine_init_windows_dir( DIR_Windows, DIR_System );
869 /***********************************************************************
872 * Main process initialisation code
874 static BOOL process_init(void)
876 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
878 size_t info_size = 0;
879 RTL_USER_PROCESS_PARAMETERS *params;
880 PEB *peb = NtCurrentTeb()->Peb;
881 HANDLE hstdin, hstdout, hstderr;
882 extern void __wine_dbg_kernel32_init(void);
886 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
890 setlocale(LC_CTYPE,"");
892 /* Retrieve startup info from the server */
893 SERVER_START_REQ( init_process )
896 req->ldt_copy = &wine_ldt_copy;
897 if ((ret = !wine_server_call_err( req )))
899 main_exe_file = reply->exe_file;
900 main_create_flags = reply->create_flags;
901 info_size = reply->info_size;
902 server_startticks = reply->server_start;
903 hstdin = reply->hstdin;
904 hstdout = reply->hstdout;
905 hstderr = reply->hstderr;
909 if (!ret) return FALSE;
913 params = peb->ProcessParameters;
915 /* This is wine specific: we have no parent (we're started from unix)
916 * so, create a simple console with bare handles to unix stdio
917 * input & output streams (aka simple console)
919 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, ¶ms->hStdInput );
920 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdOutput );
921 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms->hStdError );
923 params->CurrentDirectory.DosPath.Length = 0;
924 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
925 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
929 if (!(params = init_user_process_params( info_size ))) return FALSE;
930 peb->ProcessParameters = params;
932 /* convert value from server:
933 * + 0 => INVALID_HANDLE_VALUE
934 * + console handle need to be mapped
937 hstdin = INVALID_HANDLE_VALUE;
938 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
939 hstdin = console_handle_map(hstdin);
942 hstdout = INVALID_HANDLE_VALUE;
943 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
944 hstdout = console_handle_map(hstdout);
947 hstderr = INVALID_HANDLE_VALUE;
948 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
949 hstderr = console_handle_map(hstderr);
951 params->hStdInput = hstdin;
952 params->hStdOutput = hstdout;
953 params->hStdError = hstderr;
956 kernel32_handle = GetModuleHandleW(kernel32W);
962 /* Copy the parent environment */
963 if (!build_initial_environment( __wine_main_environ )) return FALSE;
965 /* Create device symlinks */
966 VOLUME_CreateDevices();
968 /* registry initialisation */
969 SHELL_LoadRegistry();
971 /* global boot finished, the rest is process-local */
972 SERVER_START_REQ( boot_done )
974 req->debug_level = TRACE_ON(server);
975 wine_server_call( req );
979 set_registry_environment();
983 init_current_directory( ¶ms->CurrentDirectory );
989 /***********************************************************************
992 * Startup routine of a new process. Runs on the new process stack.
994 static void start_process( void *arg )
998 PEB *peb = NtCurrentTeb()->Peb;
999 IMAGE_NT_HEADERS *nt;
1000 LPTHREAD_START_ROUTINE entry;
1002 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
1004 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1005 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1006 nt->OptionalHeader.AddressOfEntryPoint);
1008 if (TRACE_ON(relay))
1009 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1010 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1012 SetLastError( 0 ); /* clear error code */
1013 if (peb->BeingDebugged) DbgBreakPoint();
1014 ExitProcess( entry( peb ) );
1016 __EXCEPT(UnhandledExceptionFilter)
1018 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1024 /***********************************************************************
1025 * __wine_kernel_init
1027 * Wine initialisation: load and start the main exe file.
1029 void __wine_kernel_init(void)
1031 WCHAR *main_exe_name, *p;
1033 DWORD stack_size = 0;
1035 PEB *peb = NtCurrentTeb()->Peb;
1037 /* Initialize everything */
1038 if (!process_init()) exit(1);
1040 __wine_main_argv++; /* remove argv[0] (wine itself) */
1043 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1045 WCHAR buffer[MAX_PATH];
1046 WCHAR exe_nameW[MAX_PATH];
1048 if (!__wine_main_argv[0]) usage();
1049 if (__wine_main_argc == 1)
1051 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1052 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1055 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1056 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1058 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1061 if (main_exe_file == INVALID_HANDLE_VALUE)
1063 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1066 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1067 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1070 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1071 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1073 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1074 MODULE_get_dll_load_path(NULL) );
1075 VERSION_Init( main_exe_name );
1077 if (!main_exe_file) /* no file handle -> Winelib app */
1079 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1080 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1082 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1083 debugstr_w(main_exe_name), error );
1087 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1090 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1091 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1093 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1096 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1098 case BINARY_UNKNOWN:
1099 /* check for .com extension */
1100 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1102 MESSAGE( "wine: cannot determine executable type for %s\n",
1103 debugstr_w(main_exe_name) );
1109 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1110 CloseHandle( main_exe_file );
1114 __wine_main_argv[0] = "winevdm.exe";
1115 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1117 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1118 debugstr_w(main_exe_name), error );
1121 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
1123 case BINARY_UNIX_EXE:
1124 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1126 case BINARY_UNIX_LIB:
1130 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1131 CloseHandle( main_exe_file );
1133 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1134 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1136 static const WCHAR soW[] = {'.','s','o',0};
1137 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1140 /* update the unicode string */
1141 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1143 HeapFree( GetProcessHeap(), 0, unix_name );
1146 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1152 /* build command line */
1153 set_library_wargv( __wine_main_argv );
1154 if (!build_command_line( __wine_main_wargv )) goto error;
1156 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1158 /* allocate main thread stack */
1159 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1161 /* switch to the new stack */
1162 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1165 ExitProcess( GetLastError() );
1169 /***********************************************************************
1172 * Build an argv array from a command-line.
1173 * 'reserved' is the number of args to reserve before the first one.
1175 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1179 char *arg,*s,*d,*cmdline;
1180 int in_quotes,bcount,len;
1182 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1183 if (!(cmdline = malloc(len))) return NULL;
1184 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1191 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1194 /* skip the remaining spaces */
1195 while (*s==' ' || *s=='\t') {
1202 } else if (*s=='\\') {
1203 /* '\', count them */
1205 } else if ((*s=='"') && ((bcount & 1)==0)) {
1207 in_quotes=!in_quotes;
1210 /* a regular character */
1215 argv=malloc(argc*sizeof(*argv));
1224 if ((*s==' ' || *s=='\t') && !in_quotes) {
1225 /* Close the argument and copy it */
1229 /* skip the remaining spaces */
1232 } while (*s==' ' || *s=='\t');
1234 /* Start with a new argument */
1237 } else if (*s=='\\') {
1241 } else if (*s=='"') {
1243 if ((bcount & 1)==0) {
1244 /* Preceeded by an even number of '\', this is half that
1245 * number of '\', plus a '"' which we discard.
1249 in_quotes=!in_quotes;
1251 /* Preceeded by an odd number of '\', this is half that
1252 * number of '\' followed by a '"'
1260 /* a regular character */
1275 /***********************************************************************
1278 * Allocate an environment string; helper for build_envp
1280 static char *alloc_env_string( const char *name, const char *value )
1282 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1283 strcpy( ret, name );
1284 strcat( ret, value );
1288 /***********************************************************************
1291 * Build the environment of a new child process.
1293 static char **build_envp( const WCHAR *envW )
1298 int count = 0, length;
1300 for (end = envW; *end; count++) end += strlenW(end) + 1;
1302 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1303 if (!(env = malloc( length ))) return NULL;
1304 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1308 if ((envp = malloc( count * sizeof(*envp) )))
1310 char **envptr = envp;
1312 /* some variables must not be modified, so we get them directly from the unix env */
1313 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1314 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1315 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1316 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1317 /* now put the Windows environment strings */
1318 for (p = env; *p; p += strlen(p) + 1)
1320 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1321 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1322 if (is_special_env_var( p )) /* prefix it with "WINE" */
1323 *envptr++ = alloc_env_string( "WINE", p );
1333 /***********************************************************************
1336 * Fork and exec a new Unix binary, checking for errors.
1338 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1339 const WCHAR *env, const char *newdir )
1344 if (!env) env = GetEnvironmentStringsW();
1348 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1351 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1352 if (!(pid = fork())) /* child */
1354 char **argv = build_argv( cmdline, 0 );
1355 char **envp = build_envp( env );
1358 /* Reset signals that we previously set to SIG_IGN */
1359 signal( SIGPIPE, SIG_DFL );
1360 signal( SIGCHLD, SIG_DFL );
1362 if (newdir) chdir(newdir);
1364 if (argv && envp) execve( filename, argv, envp );
1366 write( fd[1], &err, sizeof(err) );
1370 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1375 if (pid == -1) FILE_SetDosError();
1381 /***********************************************************************
1382 * create_user_params
1384 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1385 LPCWSTR cur_dir, LPWSTR env,
1386 const STARTUPINFOW *startup )
1388 RTL_USER_PROCESS_PARAMETERS *params;
1389 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title;
1391 WCHAR buffer[MAX_PATH];
1393 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1394 lstrcpynW( buffer, filename, MAX_PATH );
1395 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1396 lstrcpynW( buffer, filename, MAX_PATH );
1397 RtlInitUnicodeString( &image_str, buffer );
1399 RtlInitUnicodeString( &cmdline_str, cmdline );
1400 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1401 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1402 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1404 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1405 cur_dir ? &curdir_str : NULL,
1407 startup->lpTitle ? &title : NULL,
1408 startup->lpDesktop ? &desktop : NULL,
1410 if (status != STATUS_SUCCESS)
1412 SetLastError( RtlNtStatusToDosError(status) );
1416 params->hStdInput = startup->hStdInput;
1417 params->hStdOutput = startup->hStdOutput;
1418 params->hStdError = startup->hStdError;
1419 params->dwX = startup->dwX;
1420 params->dwY = startup->dwY;
1421 params->dwXSize = startup->dwXSize;
1422 params->dwYSize = startup->dwYSize;
1423 params->dwXCountChars = startup->dwXCountChars;
1424 params->dwYCountChars = startup->dwYCountChars;
1425 params->dwFillAttribute = startup->dwFillAttribute;
1426 params->dwFlags = startup->dwFlags;
1427 params->wShowWindow = startup->wShowWindow;
1432 /***********************************************************************
1435 * Create a new process. If hFile is a valid handle we have an exe
1436 * file, otherwise it is a Winelib app.
1438 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1439 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1440 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1441 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1442 void *res_start, void *res_end )
1444 BOOL ret, success = FALSE;
1445 HANDLE process_info;
1447 RTL_USER_PROCESS_PARAMETERS *params;
1453 char preloader_reserve[64];
1455 if (!env) RtlAcquirePebLock();
1457 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, startup )))
1459 if (!env) RtlReleasePebLock();
1462 env_end = params->Environment;
1463 while (*env_end) env_end += strlenW(env_end) + 1;
1466 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1467 (unsigned long)res_start, (unsigned long)res_end, 0 );
1469 /* create the synchronization pipes */
1471 if (pipe( startfd ) == -1)
1473 if (!env) RtlReleasePebLock();
1474 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1475 RtlDestroyProcessParameters( params );
1478 if (pipe( execfd ) == -1)
1480 if (!env) RtlReleasePebLock();
1481 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1482 close( startfd[0] );
1483 close( startfd[1] );
1484 RtlDestroyProcessParameters( params );
1487 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1489 /* create the child process */
1491 if (!(pid = fork())) /* child */
1493 char **argv = build_argv( cmd_line, 1 );
1495 close( startfd[1] );
1498 /* wait for parent to tell us to start */
1499 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1501 close( startfd[0] );
1502 /* Reset signals that we previously set to SIG_IGN */
1503 signal( SIGPIPE, SIG_DFL );
1504 signal( SIGCHLD, SIG_DFL );
1506 putenv( preloader_reserve );
1507 if (unixdir) chdir(unixdir);
1511 /* first, try for a WINELOADER environment variable */
1512 const char *loader = getenv("WINELOADER");
1513 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1514 /* now use the standard search strategy */
1515 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1518 write( execfd[1], &err, sizeof(err) );
1522 /* this is the parent */
1524 close( startfd[0] );
1528 if (!env) RtlReleasePebLock();
1529 close( startfd[1] );
1532 RtlDestroyProcessParameters( params );
1536 /* create the process on the server side */
1538 SERVER_START_REQ( new_process )
1540 req->inherit_all = inherit;
1541 req->create_flags = flags;
1542 req->unix_pid = pid;
1543 req->exe_file = hFile;
1544 if (startup->dwFlags & STARTF_USESTDHANDLES)
1546 req->hstdin = startup->hStdInput;
1547 req->hstdout = startup->hStdOutput;
1548 req->hstderr = startup->hStdError;
1552 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1553 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1554 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1557 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1559 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1560 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1561 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1562 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1566 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1567 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1568 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1571 wine_server_add_data( req, params, params->Size );
1572 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1573 ret = !wine_server_call_err( req );
1574 process_info = reply->info;
1578 if (!env) RtlReleasePebLock();
1579 RtlDestroyProcessParameters( params );
1582 close( startfd[1] );
1587 /* tell child to start and wait for it to exec */
1589 write( startfd[1], &dummy, 1 );
1590 close( startfd[1] );
1592 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1597 CloseHandle( process_info );
1602 /* wait for the new process info to be ready */
1604 WaitForSingleObject( process_info, INFINITE );
1605 SERVER_START_REQ( get_new_process_info )
1607 req->info = process_info;
1608 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1609 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1610 if ((ret = !wine_server_call_err( req )))
1612 info->dwProcessId = (DWORD)reply->pid;
1613 info->dwThreadId = (DWORD)reply->tid;
1614 info->hProcess = reply->phandle;
1615 info->hThread = reply->thandle;
1616 success = reply->success;
1621 if (ret && !success) /* new process failed to start */
1624 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1625 CloseHandle( info->hThread );
1626 CloseHandle( info->hProcess );
1629 CloseHandle( process_info );
1634 /***********************************************************************
1635 * create_vdm_process
1637 * Create a new VDM process for a 16-bit or DOS application.
1639 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1640 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1641 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1642 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1644 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1647 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1648 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1652 SetLastError( ERROR_OUTOFMEMORY );
1655 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1656 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1657 flags, startup, info, unixdir, NULL, NULL );
1658 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1663 /***********************************************************************
1664 * create_cmd_process
1666 * Create a new cmd shell process for a .BAT file.
1668 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1669 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1670 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1671 LPPROCESS_INFORMATION info )
1674 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1675 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1676 WCHAR comspec[MAX_PATH];
1680 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1682 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1683 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1686 strcpyW( newcmdline, comspec );
1687 strcatW( newcmdline, slashcW );
1688 strcatW( newcmdline, cmd_line );
1689 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1690 flags, env, cur_dir, startup, info );
1691 HeapFree( GetProcessHeap(), 0, newcmdline );
1696 /*************************************************************************
1699 * Helper for CreateProcess: retrieve the file name to load from the
1700 * app name and command line. Store the file name in buffer, and
1701 * return a possibly modified command line.
1702 * Also returns a handle to the opened file if it's a Windows binary.
1704 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1705 int buflen, HANDLE *handle )
1707 static const WCHAR quotesW[] = {'"','%','s','"',0};
1709 WCHAR *name, *pos, *ret = NULL;
1712 /* if we have an app name, everything is easy */
1716 /* use the unmodified app name as file name */
1717 lstrcpynW( buffer, appname, buflen );
1718 *handle = open_exe_file( buffer );
1719 if (!(ret = cmdline) || !cmdline[0])
1721 /* no command-line, create one */
1722 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1723 sprintfW( ret, quotesW, appname );
1730 SetLastError( ERROR_INVALID_PARAMETER );
1734 /* first check for a quoted file name */
1736 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1738 int len = p - cmdline - 1;
1739 /* extract the quoted portion as file name */
1740 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1741 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1744 if (find_exe_file( name, buffer, buflen, handle ))
1745 ret = cmdline; /* no change necessary */
1749 /* now try the command-line word by word */
1751 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1758 do *pos++ = *p++; while (*p && *p != ' ');
1760 if (find_exe_file( name, buffer, buflen, handle ))
1767 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1769 /* now build a new command-line with quotes */
1771 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1773 sprintfW( ret, quotesW, name );
1777 HeapFree( GetProcessHeap(), 0, name );
1782 /**********************************************************************
1783 * CreateProcessA (KERNEL32.@)
1785 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1786 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1787 DWORD flags, LPVOID env, LPCSTR cur_dir,
1788 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1791 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1792 UNICODE_STRING desktopW, titleW;
1795 desktopW.Buffer = NULL;
1796 titleW.Buffer = NULL;
1797 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1798 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1799 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1801 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1802 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1804 memcpy( &infoW, startup_info, sizeof(infoW) );
1805 infoW.lpDesktop = desktopW.Buffer;
1806 infoW.lpTitle = titleW.Buffer;
1808 if (startup_info->lpReserved)
1809 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1810 debugstr_a(startup_info->lpReserved));
1812 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1813 inherit, flags, env, cur_dirW, &infoW, info );
1815 if (app_nameW) HeapFree( GetProcessHeap(), 0, app_nameW );
1816 if (cmd_lineW) HeapFree( GetProcessHeap(), 0, cmd_lineW );
1817 if (cur_dirW) HeapFree( GetProcessHeap(), 0, cur_dirW );
1818 RtlFreeUnicodeString( &desktopW );
1819 RtlFreeUnicodeString( &titleW );
1824 /**********************************************************************
1825 * CreateProcessW (KERNEL32.@)
1827 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1828 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1829 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1830 LPPROCESS_INFORMATION info )
1834 char *unixdir = NULL;
1835 WCHAR name[MAX_PATH];
1836 WCHAR *tidy_cmdline, *p, *envW = env;
1837 void *res_start, *res_end;
1839 /* Process the AppName and/or CmdLine to get module name and path */
1841 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1843 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1845 if (hFile == INVALID_HANDLE_VALUE) goto done;
1847 /* Warn if unsupported features are used */
1849 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1850 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1851 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1852 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1853 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1857 unixdir = wine_get_unix_file_name( cur_dir );
1861 WCHAR buf[MAX_PATH];
1862 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1865 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1870 while (*p) p += strlen(p) + 1;
1871 p++; /* final null */
1872 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1873 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1874 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1875 flags |= CREATE_UNICODE_ENVIRONMENT;
1878 info->hThread = info->hProcess = 0;
1879 info->dwProcessId = info->dwThreadId = 0;
1881 /* Determine executable type */
1883 if (!hFile) /* builtin exe */
1885 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1886 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1887 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1891 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1894 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1895 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1896 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1900 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1901 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1902 inherit, flags, startup_info, info, unixdir );
1905 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1906 SetLastError( ERROR_BAD_EXE_FORMAT );
1909 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1910 SetLastError( ERROR_BAD_EXE_FORMAT );
1912 case BINARY_UNIX_LIB:
1913 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1914 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1915 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1917 case BINARY_UNKNOWN:
1918 /* check for .com or .bat extension */
1919 if ((p = strrchrW( name, '.' )))
1921 if (!strcmpiW( p, comW ))
1923 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1924 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1925 inherit, flags, startup_info, info, unixdir );
1928 if (!strcmpiW( p, batW ))
1930 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1931 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1932 inherit, flags, startup_info, info );
1937 case BINARY_UNIX_EXE:
1939 /* unknown file, try as unix executable */
1942 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1944 if ((unix_name = wine_get_unix_file_name( name )))
1946 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1947 HeapFree( GetProcessHeap(), 0, unix_name );
1952 CloseHandle( hFile );
1955 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1956 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1957 if (unixdir) HeapFree( GetProcessHeap(), 0, unixdir );
1962 /***********************************************************************
1965 * Wrapper to call WaitForInputIdle USER function
1967 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1969 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1971 HMODULE mod = GetModuleHandleA( "user32.dll" );
1974 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1975 if (ptr) return ptr( process, timeout );
1981 /***********************************************************************
1982 * WinExec (KERNEL32.@)
1984 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1986 PROCESS_INFORMATION info;
1987 STARTUPINFOA startup;
1991 memset( &startup, 0, sizeof(startup) );
1992 startup.cb = sizeof(startup);
1993 startup.dwFlags = STARTF_USESHOWWINDOW;
1994 startup.wShowWindow = nCmdShow;
1996 /* cmdline needs to be writeable for CreateProcess */
1997 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1998 strcpy( cmdline, lpCmdLine );
2000 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2001 0, NULL, NULL, &startup, &info ))
2003 /* Give 30 seconds to the app to come up */
2004 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2005 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2007 /* Close off the handles */
2008 CloseHandle( info.hThread );
2009 CloseHandle( info.hProcess );
2011 else if ((ret = GetLastError()) >= 32)
2013 FIXME("Strange error set by CreateProcess: %d\n", ret );
2016 HeapFree( GetProcessHeap(), 0, cmdline );
2021 /**********************************************************************
2022 * LoadModule (KERNEL32.@)
2024 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2026 LOADPARMS32 *params = paramBlock;
2027 PROCESS_INFORMATION info;
2028 STARTUPINFOA startup;
2029 HINSTANCE hInstance;
2031 char filename[MAX_PATH];
2034 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2036 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2037 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2038 return (HINSTANCE)GetLastError();
2040 len = (BYTE)params->lpCmdLine[0];
2041 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2042 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2044 strcpy( cmdline, filename );
2045 p = cmdline + strlen(cmdline);
2047 memcpy( p, params->lpCmdLine + 1, len );
2050 memset( &startup, 0, sizeof(startup) );
2051 startup.cb = sizeof(startup);
2052 if (params->lpCmdShow)
2054 startup.dwFlags = STARTF_USESHOWWINDOW;
2055 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2058 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2059 params->lpEnvAddress, NULL, &startup, &info ))
2061 /* Give 30 seconds to the app to come up */
2062 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2063 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2064 hInstance = (HINSTANCE)33;
2065 /* Close off the handles */
2066 CloseHandle( info.hThread );
2067 CloseHandle( info.hProcess );
2069 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2071 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2072 hInstance = (HINSTANCE)11;
2075 HeapFree( GetProcessHeap(), 0, cmdline );
2080 /******************************************************************************
2081 * TerminateProcess (KERNEL32.@)
2083 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2085 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2086 if (status) SetLastError( RtlNtStatusToDosError(status) );
2091 /***********************************************************************
2092 * ExitProcess (KERNEL32.@)
2094 void WINAPI ExitProcess( DWORD status )
2096 LdrShutdownProcess();
2097 SERVER_START_REQ( terminate_process )
2099 /* send the exit code to the server */
2100 req->handle = GetCurrentProcess();
2101 req->exit_code = status;
2102 wine_server_call( req );
2109 /***********************************************************************
2110 * GetExitCodeProcess [KERNEL32.@]
2112 * Gets termination status of specified process
2118 BOOL WINAPI GetExitCodeProcess(
2119 HANDLE hProcess, /* [in] handle to the process */
2120 LPDWORD lpExitCode) /* [out] address to receive termination status */
2123 PROCESS_BASIC_INFORMATION pbi;
2125 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2127 if (status == STATUS_SUCCESS)
2129 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2132 SetLastError( RtlNtStatusToDosError(status) );
2137 /***********************************************************************
2138 * SetErrorMode (KERNEL32.@)
2140 UINT WINAPI SetErrorMode( UINT mode )
2142 UINT old = process_error_mode;
2143 process_error_mode = mode;
2148 /**********************************************************************
2149 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2151 * Allocates a thread local storage index
2154 * Success: TLS Index
2155 * Failure: 0xFFFFFFFF
2157 DWORD WINAPI TlsAlloc( void )
2161 RtlAcquirePebLock();
2162 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
2163 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2164 else SetLastError( ERROR_NO_MORE_ITEMS );
2165 RtlReleasePebLock();
2170 /**********************************************************************
2171 * TlsFree [KERNEL32.@] Releases a TLS index.
2173 * Releases a thread local storage index, making it available for reuse
2179 BOOL WINAPI TlsFree(
2180 DWORD index) /* [in] TLS Index to free */
2184 RtlAcquirePebLock();
2185 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2188 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2189 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2191 else SetLastError( ERROR_INVALID_PARAMETER );
2192 RtlReleasePebLock();
2197 /**********************************************************************
2198 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2201 * Success: Value stored in calling thread's TLS slot for index
2202 * Failure: 0 and GetLastError returns NO_ERROR
2204 LPVOID WINAPI TlsGetValue(
2205 DWORD index) /* [in] TLS index to retrieve value for */
2207 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2209 SetLastError( ERROR_INVALID_PARAMETER );
2212 SetLastError( ERROR_SUCCESS );
2213 return NtCurrentTeb()->TlsSlots[index];
2217 /**********************************************************************
2218 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2224 BOOL WINAPI TlsSetValue(
2225 DWORD index, /* [in] TLS index to set value for */
2226 LPVOID value) /* [in] Value to be stored */
2228 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2230 SetLastError( ERROR_INVALID_PARAMETER );
2233 NtCurrentTeb()->TlsSlots[index] = value;
2238 /***********************************************************************
2239 * GetProcessFlags (KERNEL32.@)
2241 DWORD WINAPI GetProcessFlags( DWORD processid )
2243 IMAGE_NT_HEADERS *nt;
2246 if (processid && processid != GetCurrentProcessId()) return 0;
2248 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2250 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2251 flags |= PDB32_CONSOLE_PROC;
2253 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2254 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2259 /***********************************************************************
2260 * GetProcessDword (KERNEL.485)
2261 * GetProcessDword (KERNEL32.18)
2262 * 'Of course you cannot directly access Windows internal structures'
2264 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2269 TRACE("(%ld, %d)\n", dwProcessID, offset );
2271 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2273 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2279 case GPD_APP_COMPAT_FLAGS:
2280 return GetAppCompatFlags16(0);
2281 case GPD_LOAD_DONE_EVENT:
2283 case GPD_HINSTANCE16:
2284 return GetTaskDS16();
2285 case GPD_WINDOWS_VERSION:
2286 return GetExeVersion16();
2288 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2290 return (DWORD)NtCurrentTeb()->Peb;
2291 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2292 GetStartupInfoW(&siw);
2293 return (DWORD)siw.hStdOutput;
2294 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2295 GetStartupInfoW(&siw);
2296 return (DWORD)siw.hStdInput;
2297 case GPD_STARTF_SHOWWINDOW:
2298 GetStartupInfoW(&siw);
2299 return siw.wShowWindow;
2300 case GPD_STARTF_SIZE:
2301 GetStartupInfoW(&siw);
2303 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2305 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2306 return MAKELONG( x, y );
2307 case GPD_STARTF_POSITION:
2308 GetStartupInfoW(&siw);
2310 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2312 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2313 return MAKELONG( x, y );
2314 case GPD_STARTF_FLAGS:
2315 GetStartupInfoW(&siw);
2320 return GetProcessFlags(0);
2322 return process_dword;
2324 ERR("Unknown offset %d\n", offset );
2329 /***********************************************************************
2330 * SetProcessDword (KERNEL.484)
2331 * 'Of course you cannot directly access Windows internal structures'
2333 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2335 TRACE("(%ld, %d)\n", dwProcessID, offset );
2337 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2339 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2345 case GPD_APP_COMPAT_FLAGS:
2346 case GPD_LOAD_DONE_EVENT:
2347 case GPD_HINSTANCE16:
2348 case GPD_WINDOWS_VERSION:
2351 case GPD_STARTF_SHELLDATA:
2352 case GPD_STARTF_HOTKEY:
2353 case GPD_STARTF_SHOWWINDOW:
2354 case GPD_STARTF_SIZE:
2355 case GPD_STARTF_POSITION:
2356 case GPD_STARTF_FLAGS:
2359 ERR("Not allowed to modify offset %d\n", offset );
2362 process_dword = value;
2365 ERR("Unknown offset %d\n", offset );
2371 /***********************************************************************
2372 * ExitProcess (KERNEL.466)
2374 void WINAPI ExitProcess16( WORD status )
2377 ReleaseThunkLock( &count );
2378 ExitProcess( status );
2382 /*********************************************************************
2383 * OpenProcess (KERNEL32.@)
2385 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2388 SERVER_START_REQ( open_process )
2391 req->access = access;
2392 req->inherit = inherit;
2393 if (!wine_server_call_err( req )) ret = reply->handle;
2400 /*********************************************************************
2401 * MapProcessHandle (KERNEL.483)
2402 * GetProcessId (KERNEL32.@)
2404 DWORD WINAPI GetProcessId( HANDLE hProcess )
2407 PROCESS_BASIC_INFORMATION pbi;
2409 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2411 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2412 SetLastError( RtlNtStatusToDosError(status) );
2417 /*********************************************************************
2418 * CloseW32Handle (KERNEL.474)
2419 * CloseHandle (KERNEL32.@)
2421 BOOL WINAPI CloseHandle( HANDLE handle )
2425 /* stdio handles need special treatment */
2426 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2427 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2428 (handle == (HANDLE)STD_ERROR_HANDLE))
2429 handle = GetStdHandle( (DWORD)handle );
2431 if (is_console_handle(handle))
2432 return CloseConsoleHandle(handle);
2434 status = NtClose( handle );
2435 if (status) SetLastError( RtlNtStatusToDosError(status) );
2440 /*********************************************************************
2441 * GetHandleInformation (KERNEL32.@)
2443 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2446 SERVER_START_REQ( set_handle_info )
2448 req->handle = handle;
2452 ret = !wine_server_call_err( req );
2453 if (ret && flags) *flags = reply->old_flags;
2460 /*********************************************************************
2461 * SetHandleInformation (KERNEL32.@)
2463 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2466 SERVER_START_REQ( set_handle_info )
2468 req->handle = handle;
2472 ret = !wine_server_call_err( req );
2479 /*********************************************************************
2480 * DuplicateHandle (KERNEL32.@)
2482 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2483 HANDLE dest_process, HANDLE *dest,
2484 DWORD access, BOOL inherit, DWORD options )
2488 if (is_console_handle(source))
2490 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2491 if (source_process != dest_process ||
2492 source_process != GetCurrentProcess())
2494 SetLastError(ERROR_INVALID_PARAMETER);
2497 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2498 return (*dest != INVALID_HANDLE_VALUE);
2500 status = NtDuplicateObject( source_process, source, dest_process, dest,
2501 access, inherit ? OBJ_INHERIT : 0, options );
2502 if (status) SetLastError( RtlNtStatusToDosError(status) );
2507 /***********************************************************************
2508 * ConvertToGlobalHandle (KERNEL.476)
2509 * ConvertToGlobalHandle (KERNEL32.@)
2511 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2513 HANDLE ret = INVALID_HANDLE_VALUE;
2514 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2515 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2520 /***********************************************************************
2521 * SetHandleContext (KERNEL32.@)
2523 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2525 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2526 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2527 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2532 /***********************************************************************
2533 * GetHandleContext (KERNEL32.@)
2535 DWORD WINAPI GetHandleContext(HANDLE hnd)
2537 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2538 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2539 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2544 /***********************************************************************
2545 * CreateSocketHandle (KERNEL32.@)
2547 HANDLE WINAPI CreateSocketHandle(void)
2549 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2550 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2551 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2552 return INVALID_HANDLE_VALUE;
2556 /***********************************************************************
2557 * SetPriorityClass (KERNEL32.@)
2559 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2562 SERVER_START_REQ( set_process_info )
2564 req->handle = hprocess;
2565 req->priority = priorityclass;
2566 req->mask = SET_PROCESS_INFO_PRIORITY;
2567 ret = !wine_server_call_err( req );
2574 /***********************************************************************
2575 * GetPriorityClass (KERNEL32.@)
2577 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2580 PROCESS_BASIC_INFORMATION pbi;
2582 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2584 if (status == STATUS_SUCCESS) return pbi.BasePriority;
2585 SetLastError( RtlNtStatusToDosError(status) );
2590 /***********************************************************************
2591 * SetProcessAffinityMask (KERNEL32.@)
2593 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2596 SERVER_START_REQ( set_process_info )
2598 req->handle = hProcess;
2599 req->affinity = affmask;
2600 req->mask = SET_PROCESS_INFO_AFFINITY;
2601 ret = !wine_server_call_err( req );
2608 /**********************************************************************
2609 * GetProcessAffinityMask (KERNEL32.@)
2611 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2612 LPDWORD lpProcessAffinityMask,
2613 LPDWORD lpSystemAffinityMask )
2616 SERVER_START_REQ( get_process_info )
2618 req->handle = hProcess;
2619 if (!wine_server_call_err( req ))
2621 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2622 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2631 /***********************************************************************
2632 * GetProcessVersion (KERNEL32.@)
2634 DWORD WINAPI GetProcessVersion( DWORD processid )
2636 IMAGE_NT_HEADERS *nt;
2638 if (processid && processid != GetCurrentProcessId())
2640 FIXME("should use ReadProcessMemory\n");
2643 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2644 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2645 nt->OptionalHeader.MinorSubsystemVersion);
2650 /***********************************************************************
2651 * SetProcessWorkingSetSize [KERNEL32.@]
2652 * Sets the min/max working set sizes for a specified process.
2655 * hProcess [I] Handle to the process of interest
2656 * minset [I] Specifies minimum working set size
2657 * maxset [I] Specifies maximum working set size
2661 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2664 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2665 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2666 /* Trim the working set to zero */
2667 /* Swap the process out of physical RAM */
2672 /***********************************************************************
2673 * GetProcessWorkingSetSize (KERNEL32.@)
2675 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2678 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2679 /* 32 MB working set size */
2680 if (minset) *minset = 32*1024*1024;
2681 if (maxset) *maxset = 32*1024*1024;
2686 /***********************************************************************
2687 * SetProcessShutdownParameters (KERNEL32.@)
2689 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2691 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2692 shutdown_flags = flags;
2693 shutdown_priority = level;
2698 /***********************************************************************
2699 * GetProcessShutdownParameters (KERNEL32.@)
2702 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2704 *lpdwLevel = shutdown_priority;
2705 *lpdwFlags = shutdown_flags;
2710 /***********************************************************************
2711 * GetProcessPriorityBoost (KERNEL32.@)
2713 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2715 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2717 /* Report that no boost is present.. */
2718 *pDisablePriorityBoost = FALSE;
2723 /***********************************************************************
2724 * SetProcessPriorityBoost (KERNEL32.@)
2726 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2728 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2729 /* Say we can do it. I doubt the program will notice that we don't. */
2734 /***********************************************************************
2735 * ReadProcessMemory (KERNEL32.@)
2737 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2738 SIZE_T *bytes_read )
2740 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2741 if (status) SetLastError( RtlNtStatusToDosError(status) );
2746 /***********************************************************************
2747 * WriteProcessMemory (KERNEL32.@)
2749 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2750 SIZE_T *bytes_written )
2752 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2753 if (status) SetLastError( RtlNtStatusToDosError(status) );
2758 /****************************************************************************
2759 * FlushInstructionCache (KERNEL32.@)
2761 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2764 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2765 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2766 if (status) SetLastError( RtlNtStatusToDosError(status) );
2771 /******************************************************************
2772 * GetProcessIoCounters (KERNEL32.@)
2774 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2778 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2779 ioc, sizeof(*ioc), NULL);
2780 if (status) SetLastError( RtlNtStatusToDosError(status) );
2784 /***********************************************************************
2785 * ProcessIdToSessionId (KERNEL32.@)
2786 * This function is available on Terminal Server 4SP4 and Windows 2000
2788 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2790 /* According to MSDN, if the calling process is not in a terminal
2791 * services environment, then the sessionid returned is zero.
2798 /***********************************************************************
2799 * RegisterServiceProcess (KERNEL.491)
2800 * RegisterServiceProcess (KERNEL32.@)
2802 * A service process calls this function to ensure that it continues to run
2803 * even after a user logged off.
2805 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2807 /* I don't think that Wine needs to do anything in that function */
2808 return 1; /* success */
2812 /***********************************************************************
2813 * GetSystemMSecCount (SYSTEM.6)
2814 * GetTickCount (KERNEL32.@)
2816 * Returns the number of milliseconds, modulo 2^32, since the start
2817 * of the wineserver.
2819 DWORD WINAPI GetTickCount(void)
2822 gettimeofday( &t, NULL );
2823 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2827 /***********************************************************************
2828 * GetCurrentProcess (KERNEL32.@)
2830 #undef GetCurrentProcess
2831 HANDLE WINAPI GetCurrentProcess(void)
2833 return (HANDLE)0xffffffff;