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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
40 #ifdef HAVE_SYS_PRCTL_H
41 # include <sys/prctl.h>
43 #include <sys/types.h>
46 #define WIN32_NO_STATUS
47 #include "wine/winbase16.h"
48 #include "wine/winuser16.h"
51 #include "kernel_private.h"
52 #include "wine/exception.h"
53 #include "wine/server.h"
54 #include "wine/unicode.h"
55 #include "wine/debug.h"
57 #ifdef HAVE_VALGRIND_MEMCHECK_H
58 #include <valgrind/memcheck.h>
61 WINE_DEFAULT_DEBUG_CHANNEL(process);
62 WINE_DECLARE_DEBUG_CHANNEL(file);
72 static UINT process_error_mode;
74 static DWORD shutdown_flags = 0;
75 static DWORD shutdown_priority = 0x280;
76 static DWORD process_dword;
78 HMODULE kernel32_handle = 0;
80 const WCHAR *DIR_Windows = NULL;
81 const WCHAR *DIR_System = NULL;
84 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
85 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
86 #define PDB32_DOS_PROC 0x0010 /* Dos process */
87 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
88 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
89 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
91 static const WCHAR comW[] = {'.','c','o','m',0};
92 static const WCHAR batW[] = {'.','b','a','t',0};
93 static const WCHAR pifW[] = {'.','p','i','f',0};
94 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
96 static void exec_process( LPCWSTR name );
98 extern void SHELL_LoadRegistry(void);
101 /***********************************************************************
104 inline static int contains_path( LPCWSTR name )
106 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
110 /***********************************************************************
113 * Check if an environment variable needs to be handled specially when
114 * passed through the Unix environment (i.e. prefixed with "WINE").
116 inline static int is_special_env_var( const char *var )
118 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
119 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
120 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
121 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
125 /***************************************************************************
128 * Get the path of a builtin module when the native file does not exist.
130 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
133 UINT len = strlenW( DIR_System );
135 if (contains_path( libname ))
137 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
138 filename, &file_part ) > size * sizeof(WCHAR))
139 return FALSE; /* too long */
141 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
143 while (filename[len] == '\\') len++;
144 if (filename + len != file_part) return FALSE;
148 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
149 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
150 file_part = filename + len;
151 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
152 strcpyW( file_part, libname );
154 if (ext && !strchrW( file_part, '.' ))
156 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
157 return FALSE; /* too long */
158 strcatW( file_part, ext );
164 /***********************************************************************
165 * open_builtin_exe_file
167 * Open an exe file for a builtin exe.
169 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
170 int test_only, int *file_exists )
172 char exename[MAX_PATH];
177 if ((p = strrchrW( name, '/' ))) name = p + 1;
178 if ((p = strrchrW( name, '\\' ))) name = p + 1;
180 /* we don't want to depend on the current codepage here */
181 len = strlenW( name ) + 1;
182 if (len >= sizeof(exename)) return NULL;
183 for (i = 0; i < len; i++)
185 if (name[i] > 127) return NULL;
186 exename[i] = (char)name[i];
187 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
189 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
193 /***********************************************************************
196 * Open a specific exe file, taking load order into account.
197 * Returns the file handle or 0 for a builtin exe.
199 static HANDLE open_exe_file( const WCHAR *name )
203 TRACE("looking for %s\n", debugstr_w(name) );
205 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
206 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
208 WCHAR buffer[MAX_PATH];
209 /* file doesn't exist, check for builtin */
210 if (!contains_path( name )) goto error;
211 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
217 SetLastError( ERROR_FILE_NOT_FOUND );
218 return INVALID_HANDLE_VALUE;
222 /***********************************************************************
225 * Open an exe file, and return the full name and file handle.
226 * Returns FALSE if file could not be found.
227 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
228 * If file is a builtin exe, returns TRUE and sets handle to 0.
230 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
232 static const WCHAR exeW[] = {'.','e','x','e',0};
235 TRACE("looking for %s\n", debugstr_w(name) );
237 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
238 !get_builtin_path( name, exeW, buffer, buflen ))
240 /* no builtin found, try native without extension in case it is a Unix app */
242 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
244 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
245 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
246 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
252 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
253 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
254 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
257 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
258 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
269 /***********************************************************************
270 * build_initial_environment
272 * Build the Win32 environment from the Unix environment
274 static BOOL build_initial_environment( char **environ )
281 /* Compute the total size of the Unix environment */
282 for (e = environ; *e; e++)
284 if (is_special_env_var( *e )) continue;
285 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
287 size *= sizeof(WCHAR);
289 /* Now allocate the environment */
291 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
292 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
295 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
296 endptr = p + size / sizeof(WCHAR);
298 /* And fill it with the Unix environment */
299 for (e = environ; *e; e++)
303 /* skip Unix special variables and use the Wine variants instead */
304 if (!strncmp( str, "WINE", 4 ))
306 if (is_special_env_var( str + 4 )) str += 4;
307 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
309 else if (is_special_env_var( str )) continue; /* skip it */
311 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
319 /***********************************************************************
320 * set_registry_variables
322 * Set environment variables by enumerating the values of a key;
323 * helper for set_registry_environment().
324 * Note that Windows happily truncates the value if it's too big.
326 static void set_registry_variables( HANDLE hkey, ULONG type )
328 UNICODE_STRING env_name, env_value;
332 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
333 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
335 for (index = 0; ; index++)
337 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
338 buffer, sizeof(buffer), &size );
339 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
341 if (info->Type != type)
343 env_name.Buffer = info->Name;
344 env_name.Length = env_name.MaximumLength = info->NameLength;
345 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
346 env_value.Length = env_value.MaximumLength = info->DataLength;
347 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
348 env_value.Length--; /* don't count terminating null if any */
349 if (info->Type == REG_EXPAND_SZ)
351 WCHAR buf_expanded[1024];
352 UNICODE_STRING env_expanded;
353 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
354 env_expanded.Buffer=buf_expanded;
355 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
356 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
357 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
361 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
367 /***********************************************************************
368 * set_registry_environment
370 * Set the environment variables specified in the registry.
372 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
373 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
374 * on the order in which the variables are processed. But on Windows it
375 * does not really matter since they only use %SystemDrive% and
376 * %SystemRoot% which are predefined. But Wine defines these in the
377 * registry, so we need two passes.
379 static void set_registry_environment(void)
381 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
382 'S','y','s','t','e','m','\\',
383 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
384 'C','o','n','t','r','o','l','\\',
385 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
386 'E','n','v','i','r','o','n','m','e','n','t',0};
387 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
389 OBJECT_ATTRIBUTES attr;
390 UNICODE_STRING nameW;
393 attr.Length = sizeof(attr);
394 attr.RootDirectory = 0;
395 attr.ObjectName = &nameW;
397 attr.SecurityDescriptor = NULL;
398 attr.SecurityQualityOfService = NULL;
400 /* first the system environment variables */
401 RtlInitUnicodeString( &nameW, env_keyW );
402 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
404 set_registry_variables( hkey, REG_SZ );
405 set_registry_variables( hkey, REG_EXPAND_SZ );
409 /* then the ones for the current user */
410 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return;
411 RtlInitUnicodeString( &nameW, envW );
412 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
414 set_registry_variables( hkey, REG_SZ );
415 set_registry_variables( hkey, REG_EXPAND_SZ );
418 NtClose( attr.RootDirectory );
422 /***********************************************************************
425 * Set the Wine library Unicode argv global variables.
427 static void set_library_wargv( char **argv )
435 for (argc = 0; argv[argc]; argc++)
436 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
438 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
439 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
440 p = (WCHAR *)(wargv + argc + 1);
441 for (argc = 0; argv[argc]; argc++)
443 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
450 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
452 for (argc = 0; wargv[argc]; argc++)
453 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
455 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
456 q = (char *)(argv + argc + 1);
457 for (argc = 0; wargv[argc]; argc++)
459 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
466 __wine_main_argc = argc;
467 __wine_main_argv = argv;
468 __wine_main_wargv = wargv;
472 /***********************************************************************
475 * Build the command line of a process from the argv array.
477 * Note that it does NOT necessarily include the file name.
478 * Sometimes we don't even have any command line options at all.
480 * We must quote and escape characters so that the argv array can be rebuilt
481 * from the command line:
482 * - spaces and tabs must be quoted
484 * - quotes must be escaped
486 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
487 * resulting in an odd number of '\' followed by a '"'
490 * - '\'s that are not followed by a '"' can be left as is
494 static BOOL build_command_line( WCHAR **argv )
499 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
501 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
504 for (arg = argv; *arg; arg++)
506 int has_space,bcount;
512 if( !*a ) has_space=1;
517 if (*a==' ' || *a=='\t') {
519 } else if (*a=='"') {
520 /* doubling of '\' preceding a '"',
521 * plus escaping of said '"'
529 len+=(a-*arg)+1 /* for the separating space */;
531 len+=2; /* for the quotes */
534 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
537 p = rupp->CommandLine.Buffer;
538 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
539 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
540 for (arg = argv; *arg; arg++)
542 int has_space,has_quote;
545 /* Check for quotes and spaces in this argument */
546 has_space=has_quote=0;
548 if( !*a ) has_space=1;
550 if (*a==' ' || *a=='\t') {
554 } else if (*a=='"') {
562 /* Now transfer it to the command line */
579 /* Double all the '\\' preceding this '"', plus one */
580 for (i=0;i<=bcount;i++)
592 while ((*p=*x++)) p++;
598 if (p > rupp->CommandLine.Buffer)
599 p--; /* remove last space */
606 /***********************************************************************
607 * init_current_directory
609 * Initialize the current directory from the Unix cwd or the parent info.
611 static void init_current_directory( CURDIR *cur_dir )
613 UNICODE_STRING dir_str;
617 /* if we received a cur dir from the parent, try this first */
619 if (cur_dir->DosPath.Length)
621 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
624 /* now try to get it from the Unix cwd */
626 for (size = 256; ; size *= 2)
628 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
629 if (getcwd( cwd, size )) break;
630 HeapFree( GetProcessHeap(), 0, cwd );
631 if (errno == ERANGE) continue;
639 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
640 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
642 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
643 RtlInitUnicodeString( &dir_str, dirW );
644 RtlSetCurrentDirectory_U( &dir_str );
645 RtlFreeUnicodeString( &dir_str );
649 if (!cur_dir->DosPath.Length) /* still not initialized */
651 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
652 "starting in the Windows directory.\n", cwd ? cwd : "" );
653 RtlInitUnicodeString( &dir_str, DIR_Windows );
654 RtlSetCurrentDirectory_U( &dir_str );
656 HeapFree( GetProcessHeap(), 0, cwd );
659 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
660 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
664 /***********************************************************************
667 * Initialize the windows and system directories from the environment.
669 static void init_windows_dirs(void)
671 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
673 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
674 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
675 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
676 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
681 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
683 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
684 GetEnvironmentVariableW( windirW, buffer, len );
685 DIR_Windows = buffer;
687 else DIR_Windows = default_windirW;
689 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
691 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
692 GetEnvironmentVariableW( winsysdirW, buffer, len );
697 len = strlenW( DIR_Windows );
698 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
699 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
700 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
704 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
705 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
706 debugstr_w(DIR_Windows) );
707 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
708 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
709 debugstr_w(DIR_System) );
711 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
712 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
714 /* set the directories in ntdll too */
715 __wine_init_windows_dir( DIR_Windows, DIR_System );
719 /***********************************************************************
722 * Main process initialisation code
724 static BOOL process_init(void)
726 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
727 PEB *peb = NtCurrentTeb()->Peb;
728 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
734 setlocale(LC_CTYPE,"");
736 kernel32_handle = GetModuleHandleW(kernel32W);
740 if (!params->Environment)
742 /* Copy the parent environment */
743 if (!build_initial_environment( __wine_main_environ )) return FALSE;
745 /* convert old configuration to new format */
746 convert_old_config();
748 set_registry_environment();
752 init_current_directory( ¶ms->CurrentDirectory );
758 /***********************************************************************
761 * Allocate the stack of new process.
763 static void *init_stack(void)
766 SIZE_T stack_size, page_size = getpagesize();
767 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
769 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
770 stack_size += page_size; /* for the guard page */
771 stack_size = (stack_size + 0xffff) & ~0xffff; /* round to 64K boundary */
772 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
774 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
776 ERR( "failed to allocate main process stack\n" );
780 /* note: limit is lower than base since the stack grows down */
781 NtCurrentTeb()->DeallocationStack = base;
782 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
783 NtCurrentTeb()->Tib.StackLimit = (char *)base + page_size;
785 #ifdef VALGRIND_STACK_REGISTER
786 /* no need to de-register the stack as it's the one of the main thread */
787 VALGRIND_STACK_REGISTER(NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase);
790 /* setup guard page */
791 VirtualProtect( base, page_size, PAGE_NOACCESS, NULL );
792 return NtCurrentTeb()->Tib.StackBase;
796 /***********************************************************************
799 * Startup routine of a new process. Runs on the new process stack.
801 static void start_process( void *arg )
805 LdrInitializeThunk( 0, 0, 0, 0 );
807 __EXCEPT(UnhandledExceptionFilter)
809 TerminateThread( GetCurrentThread(), GetExceptionCode() );
815 /***********************************************************************
818 * Change the process name in the ps output.
820 static void set_process_name( int argc, char *argv[] )
824 char *p, *prctl_name = argv[1];
825 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
828 # define PR_SET_NAME 15
831 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
832 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
834 if (prctl( PR_SET_NAME, prctl_name ) != -1)
836 offset = argv[1] - argv[0];
837 memmove( argv[1] - offset, argv[1], end - argv[1] );
838 memset( end - offset, 0, offset );
839 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
843 #endif /* HAVE_PRCTL */
846 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
851 /***********************************************************************
854 * Wine initialisation: load and start the main exe file.
856 void __wine_kernel_init(void)
858 static const WCHAR dotW[] = {'.',0};
859 static const WCHAR exeW[] = {'.','e','x','e',0};
861 WCHAR *p, main_exe_name[MAX_PATH+1];
862 PEB *peb = NtCurrentTeb()->Peb;
864 /* Initialize everything */
865 if (!process_init()) exit(1);
866 set_process_name( __wine_main_argc, __wine_main_argv );
867 set_library_wargv( __wine_main_argv );
869 if (peb->ProcessParameters->ImagePathName.Buffer)
871 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
875 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
876 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
878 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
879 ExitProcess( GetLastError() );
881 if (!build_command_line( __wine_main_wargv )) goto error;
884 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
885 p = strrchrW( main_exe_name, '.' );
886 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
888 TRACE( "starting process name=%s argv[0]=%s\n",
889 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
891 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
892 MODULE_get_dll_load_path(main_exe_name) );
894 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
897 DWORD error = GetLastError();
899 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
900 if (error == ERROR_BAD_EXE_FORMAT || error == ERROR_INVALID_ADDRESS)
902 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
903 /* if we get back here, it failed */
906 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
907 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
908 ExitProcess( error );
911 /* switch to the new stack */
912 wine_switch_to_stack( start_process, NULL, init_stack() );
915 ExitProcess( GetLastError() );
919 /***********************************************************************
922 * Build an argv array from a command-line.
923 * 'reserved' is the number of args to reserve before the first one.
925 static char **build_argv( const WCHAR *cmdlineW, int reserved )
929 char *arg,*s,*d,*cmdline;
930 int in_quotes,bcount,len;
932 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
933 if (!(cmdline = malloc(len))) return NULL;
934 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
941 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
944 /* skip the remaining spaces */
945 while (*s==' ' || *s=='\t') {
952 } else if (*s=='\\') {
953 /* '\', count them */
955 } else if ((*s=='"') && ((bcount & 1)==0)) {
957 in_quotes=!in_quotes;
960 /* a regular character */
965 argv=malloc(argc*sizeof(*argv));
974 if ((*s==' ' || *s=='\t') && !in_quotes) {
975 /* Close the argument and copy it */
979 /* skip the remaining spaces */
982 } while (*s==' ' || *s=='\t');
984 /* Start with a new argument */
987 } else if (*s=='\\') {
991 } else if (*s=='"') {
993 if ((bcount & 1)==0) {
994 /* Preceded by an even number of '\', this is half that
995 * number of '\', plus a '"' which we discard.
999 in_quotes=!in_quotes;
1001 /* Preceded by an odd number of '\', this is half that
1002 * number of '\' followed by a '"'
1010 /* a regular character */
1025 /***********************************************************************
1028 * Allocate an environment string; helper for build_envp
1030 static char *alloc_env_string( const char *name, const char *value )
1032 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1033 strcpy( ret, name );
1034 strcat( ret, value );
1038 /***********************************************************************
1041 * Build the environment of a new child process.
1043 static char **build_envp( const WCHAR *envW )
1048 int count = 0, length;
1050 for (end = envW; *end; count++) end += strlenW(end) + 1;
1052 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1053 if (!(env = malloc( length ))) return NULL;
1054 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1058 if ((envp = malloc( count * sizeof(*envp) )))
1060 char **envptr = envp;
1062 /* some variables must not be modified, so we get them directly from the unix env */
1063 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1064 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1065 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1066 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1067 /* now put the Windows environment strings */
1068 for (p = env; *p; p += strlen(p) + 1)
1070 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1071 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1072 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1073 if (is_special_env_var( p )) /* prefix it with "WINE" */
1074 *envptr++ = alloc_env_string( "WINE", p );
1084 /***********************************************************************
1087 * Fork and exec a new Unix binary, checking for errors.
1089 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1090 const WCHAR *env, const char *newdir, DWORD flags )
1095 if (!env) env = GetEnvironmentStringsW();
1099 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1102 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1103 if (!(pid = fork())) /* child */
1105 char **argv = build_argv( cmdline, 0 );
1106 char **envp = build_envp( env );
1109 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)) setsid();
1111 /* Reset signals that we previously set to SIG_IGN */
1112 signal( SIGPIPE, SIG_DFL );
1113 signal( SIGCHLD, SIG_DFL );
1115 if (newdir) chdir(newdir);
1117 if (argv && envp) execve( filename, argv, envp );
1119 write( fd[1], &err, sizeof(err) );
1123 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1128 if (pid == -1) FILE_SetDosError();
1134 /***********************************************************************
1135 * create_user_params
1137 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1138 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1139 const STARTUPINFOW *startup )
1141 RTL_USER_PROCESS_PARAMETERS *params;
1142 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1144 WCHAR buffer[MAX_PATH];
1146 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1147 lstrcpynW( buffer, filename, MAX_PATH );
1148 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1149 lstrcpynW( buffer, filename, MAX_PATH );
1150 RtlInitUnicodeString( &image_str, buffer );
1152 RtlInitUnicodeString( &cmdline_str, cmdline );
1153 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1154 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1155 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1156 if (startup->lpReserved2 && startup->cbReserved2)
1159 runtime.MaximumLength = startup->cbReserved2;
1160 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1163 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1164 cur_dir ? &curdir_str : NULL,
1166 startup->lpTitle ? &title : NULL,
1167 startup->lpDesktop ? &desktop : NULL,
1169 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1170 if (status != STATUS_SUCCESS)
1172 SetLastError( RtlNtStatusToDosError(status) );
1176 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1177 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1179 if (startup->dwFlags & STARTF_USESTDHANDLES)
1181 params->hStdInput = startup->hStdInput;
1182 params->hStdOutput = startup->hStdOutput;
1183 params->hStdError = startup->hStdError;
1187 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1188 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1189 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1191 params->dwX = startup->dwX;
1192 params->dwY = startup->dwY;
1193 params->dwXSize = startup->dwXSize;
1194 params->dwYSize = startup->dwYSize;
1195 params->dwXCountChars = startup->dwXCountChars;
1196 params->dwYCountChars = startup->dwYCountChars;
1197 params->dwFillAttribute = startup->dwFillAttribute;
1198 params->dwFlags = startup->dwFlags;
1199 params->wShowWindow = startup->wShowWindow;
1204 /***********************************************************************
1207 * Create a new process. If hFile is a valid handle we have an exe
1208 * file, otherwise it is a Winelib app.
1210 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1211 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1212 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1213 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1214 void *res_start, void *res_end, int exec_only )
1216 BOOL ret, success = FALSE;
1217 HANDLE process_info;
1219 char *winedebug = NULL;
1220 RTL_USER_PROCESS_PARAMETERS *params;
1225 if (!env) RtlAcquirePebLock();
1227 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1229 if (!env) RtlReleasePebLock();
1232 env_end = params->Environment;
1235 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1236 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1238 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1239 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1240 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1242 env_end += strlenW(env_end) + 1;
1246 /* create the socket for the new process */
1248 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1250 if (!env) RtlReleasePebLock();
1251 HeapFree( GetProcessHeap(), 0, winedebug );
1252 RtlDestroyProcessParameters( params );
1253 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1256 wine_server_send_fd( socketfd[1] );
1257 close( socketfd[1] );
1259 /* create the process on the server side */
1261 SERVER_START_REQ( new_process )
1263 req->inherit_all = inherit;
1264 req->create_flags = flags;
1265 req->socket_fd = socketfd[1];
1266 req->exe_file = hFile;
1267 req->process_access = PROCESS_ALL_ACCESS;
1268 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1269 req->thread_access = THREAD_ALL_ACCESS;
1270 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1271 req->hstdin = params->hStdInput;
1272 req->hstdout = params->hStdOutput;
1273 req->hstderr = params->hStdError;
1275 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1277 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1278 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1279 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1280 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1284 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1285 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1286 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1289 wine_server_add_data( req, params, params->Size );
1290 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1291 if ((ret = !wine_server_call_err( req )))
1293 info->dwProcessId = (DWORD)reply->pid;
1294 info->dwThreadId = (DWORD)reply->tid;
1295 info->hProcess = reply->phandle;
1296 info->hThread = reply->thandle;
1298 process_info = reply->info;
1302 if (!env) RtlReleasePebLock();
1303 RtlDestroyProcessParameters( params );
1306 close( socketfd[0] );
1307 HeapFree( GetProcessHeap(), 0, winedebug );
1311 /* create the child process */
1313 if (exec_only || !(pid = fork())) /* child */
1315 char preloader_reserve[64], socket_env[64];
1316 char **argv = build_argv( cmd_line, 1 );
1318 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)) setsid();
1320 /* Reset signals that we previously set to SIG_IGN */
1321 signal( SIGPIPE, SIG_DFL );
1322 signal( SIGCHLD, SIG_DFL );
1324 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1325 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1326 (unsigned long)res_start, (unsigned long)res_end );
1328 putenv( preloader_reserve );
1329 putenv( socket_env );
1330 if (winedebug) putenv( winedebug );
1331 if (unixdir) chdir(unixdir);
1333 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1337 /* this is the parent */
1339 close( socketfd[0] );
1340 HeapFree( GetProcessHeap(), 0, winedebug );
1347 /* wait for the new process info to be ready */
1349 WaitForSingleObject( process_info, INFINITE );
1350 SERVER_START_REQ( get_new_process_info )
1352 req->info = process_info;
1353 wine_server_call( req );
1354 success = reply->success;
1355 err = reply->exit_code;
1361 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1364 CloseHandle( process_info );
1368 CloseHandle( process_info );
1369 CloseHandle( info->hProcess );
1370 CloseHandle( info->hThread );
1371 info->hProcess = info->hThread = 0;
1372 info->dwProcessId = info->dwThreadId = 0;
1377 /***********************************************************************
1378 * create_vdm_process
1380 * Create a new VDM process for a 16-bit or DOS application.
1382 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1383 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1384 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1385 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1387 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1390 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1391 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1395 SetLastError( ERROR_OUTOFMEMORY );
1398 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1399 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1400 flags, startup, info, unixdir, NULL, NULL, exec_only );
1401 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1406 /***********************************************************************
1407 * create_cmd_process
1409 * Create a new cmd shell process for a .BAT file.
1411 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1412 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1413 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1414 LPPROCESS_INFORMATION info )
1417 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1418 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1419 WCHAR comspec[MAX_PATH];
1423 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1425 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1426 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1429 strcpyW( newcmdline, comspec );
1430 strcatW( newcmdline, slashcW );
1431 strcatW( newcmdline, cmd_line );
1432 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1433 flags, env, cur_dir, startup, info );
1434 HeapFree( GetProcessHeap(), 0, newcmdline );
1439 /*************************************************************************
1442 * Helper for CreateProcess: retrieve the file name to load from the
1443 * app name and command line. Store the file name in buffer, and
1444 * return a possibly modified command line.
1445 * Also returns a handle to the opened file if it's a Windows binary.
1447 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1448 int buflen, HANDLE *handle )
1450 static const WCHAR quotesW[] = {'"','%','s','"',0};
1452 WCHAR *name, *pos, *ret = NULL;
1456 /* if we have an app name, everything is easy */
1460 /* use the unmodified app name as file name */
1461 lstrcpynW( buffer, appname, buflen );
1462 *handle = open_exe_file( buffer );
1463 if (!(ret = cmdline) || !cmdline[0])
1465 /* no command-line, create one */
1466 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1467 sprintfW( ret, quotesW, appname );
1474 SetLastError( ERROR_INVALID_PARAMETER );
1478 /* first check for a quoted file name */
1480 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1482 int len = p - cmdline - 1;
1483 /* extract the quoted portion as file name */
1484 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1485 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1488 if (find_exe_file( name, buffer, buflen, handle ))
1489 ret = cmdline; /* no change necessary */
1493 /* now try the command-line word by word */
1495 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1503 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1505 if (find_exe_file( name, buffer, buflen, handle ))
1510 if (*p) got_space = TRUE;
1513 if (ret && got_space) /* now build a new command-line with quotes */
1515 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1517 sprintfW( ret, quotesW, name );
1522 HeapFree( GetProcessHeap(), 0, name );
1527 /**********************************************************************
1528 * CreateProcessA (KERNEL32.@)
1530 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1531 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1532 DWORD flags, LPVOID env, LPCSTR cur_dir,
1533 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1536 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1537 UNICODE_STRING desktopW, titleW;
1540 desktopW.Buffer = NULL;
1541 titleW.Buffer = NULL;
1542 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1543 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1544 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1546 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1547 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1549 memcpy( &infoW, startup_info, sizeof(infoW) );
1550 infoW.lpDesktop = desktopW.Buffer;
1551 infoW.lpTitle = titleW.Buffer;
1553 if (startup_info->lpReserved)
1554 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1555 debugstr_a(startup_info->lpReserved));
1557 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1558 inherit, flags, env, cur_dirW, &infoW, info );
1560 HeapFree( GetProcessHeap(), 0, app_nameW );
1561 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1562 HeapFree( GetProcessHeap(), 0, cur_dirW );
1563 RtlFreeUnicodeString( &desktopW );
1564 RtlFreeUnicodeString( &titleW );
1569 /**********************************************************************
1570 * CreateProcessW (KERNEL32.@)
1572 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1573 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1574 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1575 LPPROCESS_INFORMATION info )
1579 char *unixdir = NULL;
1580 WCHAR name[MAX_PATH];
1581 WCHAR *tidy_cmdline, *p, *envW = env;
1582 void *res_start, *res_end;
1584 /* Process the AppName and/or CmdLine to get module name and path */
1586 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1588 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1590 if (hFile == INVALID_HANDLE_VALUE) goto done;
1592 /* Warn if unsupported features are used */
1594 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1595 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1596 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1597 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1598 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1602 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1604 SetLastError(ERROR_DIRECTORY);
1610 WCHAR buf[MAX_PATH];
1611 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1614 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1619 while (*p) p += strlen(p) + 1;
1620 p++; /* final null */
1621 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1622 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1623 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1624 flags |= CREATE_UNICODE_ENVIRONMENT;
1627 info->hThread = info->hProcess = 0;
1628 info->dwProcessId = info->dwThreadId = 0;
1630 /* Determine executable type */
1632 if (!hFile) /* builtin exe */
1634 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1635 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1636 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1640 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1643 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1644 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1645 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1650 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1651 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1652 inherit, flags, startup_info, info, unixdir, FALSE );
1655 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1656 SetLastError( ERROR_BAD_EXE_FORMAT );
1658 case BINARY_UNIX_LIB:
1659 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1660 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1661 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1663 case BINARY_UNKNOWN:
1664 /* check for .com or .bat extension */
1665 if ((p = strrchrW( name, '.' )))
1667 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1669 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1670 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1671 inherit, flags, startup_info, info, unixdir, FALSE );
1674 if (!strcmpiW( p, batW ))
1676 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1677 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1678 inherit, flags, startup_info, info );
1683 case BINARY_UNIX_EXE:
1685 /* unknown file, try as unix executable */
1688 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1690 if ((unix_name = wine_get_unix_file_name( name )))
1692 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags ) != -1);
1693 HeapFree( GetProcessHeap(), 0, unix_name );
1698 CloseHandle( hFile );
1701 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1702 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1703 HeapFree( GetProcessHeap(), 0, unixdir );
1708 /**********************************************************************
1711 static void exec_process( LPCWSTR name )
1715 void *res_start, *res_end;
1716 STARTUPINFOW startup_info;
1717 PROCESS_INFORMATION info;
1719 hFile = open_exe_file( name );
1720 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
1722 memset( &startup_info, 0, sizeof(startup_info) );
1723 startup_info.cb = sizeof(startup_info);
1725 /* Determine executable type */
1727 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1730 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1731 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1732 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
1734 case BINARY_UNIX_LIB:
1735 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1736 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1737 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
1739 case BINARY_UNKNOWN:
1740 /* check for .com or .pif extension */
1741 if (!(p = strrchrW( name, '.' ))) break;
1742 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
1747 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1748 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1749 FALSE, 0, &startup_info, &info, NULL, TRUE );
1754 CloseHandle( hFile );
1758 /***********************************************************************
1761 * Wrapper to call WaitForInputIdle USER function
1763 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1765 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1767 HMODULE mod = GetModuleHandleA( "user32.dll" );
1770 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1771 if (ptr) return ptr( process, timeout );
1777 /***********************************************************************
1778 * WinExec (KERNEL32.@)
1780 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1782 PROCESS_INFORMATION info;
1783 STARTUPINFOA startup;
1787 memset( &startup, 0, sizeof(startup) );
1788 startup.cb = sizeof(startup);
1789 startup.dwFlags = STARTF_USESHOWWINDOW;
1790 startup.wShowWindow = nCmdShow;
1792 /* cmdline needs to be writeable for CreateProcess */
1793 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1794 strcpy( cmdline, lpCmdLine );
1796 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1797 0, NULL, NULL, &startup, &info ))
1799 /* Give 30 seconds to the app to come up */
1800 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1801 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1803 /* Close off the handles */
1804 CloseHandle( info.hThread );
1805 CloseHandle( info.hProcess );
1807 else if ((ret = GetLastError()) >= 32)
1809 FIXME("Strange error set by CreateProcess: %d\n", ret );
1812 HeapFree( GetProcessHeap(), 0, cmdline );
1817 /**********************************************************************
1818 * LoadModule (KERNEL32.@)
1820 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1822 LOADPARMS32 *params = paramBlock;
1823 PROCESS_INFORMATION info;
1824 STARTUPINFOA startup;
1825 HINSTANCE hInstance;
1827 char filename[MAX_PATH];
1830 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1832 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1833 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1834 return (HINSTANCE)GetLastError();
1836 len = (BYTE)params->lpCmdLine[0];
1837 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1838 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1840 strcpy( cmdline, filename );
1841 p = cmdline + strlen(cmdline);
1843 memcpy( p, params->lpCmdLine + 1, len );
1846 memset( &startup, 0, sizeof(startup) );
1847 startup.cb = sizeof(startup);
1848 if (params->lpCmdShow)
1850 startup.dwFlags = STARTF_USESHOWWINDOW;
1851 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1854 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1855 params->lpEnvAddress, NULL, &startup, &info ))
1857 /* Give 30 seconds to the app to come up */
1858 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1859 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1860 hInstance = (HINSTANCE)33;
1861 /* Close off the handles */
1862 CloseHandle( info.hThread );
1863 CloseHandle( info.hProcess );
1865 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1867 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1868 hInstance = (HINSTANCE)11;
1871 HeapFree( GetProcessHeap(), 0, cmdline );
1876 /******************************************************************************
1877 * TerminateProcess (KERNEL32.@)
1879 * Terminates a process.
1882 * handle [I] Process to terminate.
1883 * exit_code [I] Exit code.
1887 * Failure: FALSE, check GetLastError().
1889 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1891 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1892 if (status) SetLastError( RtlNtStatusToDosError(status) );
1897 /***********************************************************************
1898 * ExitProcess (KERNEL32.@)
1900 * Exits the current process.
1903 * status [I] Status code to exit with.
1908 void WINAPI ExitProcess( DWORD status )
1910 LdrShutdownProcess();
1911 NtTerminateProcess(GetCurrentProcess(), status);
1916 /***********************************************************************
1917 * GetExitCodeProcess [KERNEL32.@]
1919 * Gets termination status of specified process.
1922 * hProcess [in] Handle to the process.
1923 * lpExitCode [out] Address to receive termination status.
1929 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
1932 PROCESS_BASIC_INFORMATION pbi;
1934 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
1936 if (status == STATUS_SUCCESS)
1938 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
1941 SetLastError( RtlNtStatusToDosError(status) );
1946 /***********************************************************************
1947 * SetErrorMode (KERNEL32.@)
1949 UINT WINAPI SetErrorMode( UINT mode )
1951 UINT old = process_error_mode;
1952 process_error_mode = mode;
1957 /**********************************************************************
1958 * TlsAlloc [KERNEL32.@]
1960 * Allocates a thread local storage index.
1963 * Success: TLS index.
1964 * Failure: 0xFFFFFFFF
1966 DWORD WINAPI TlsAlloc( void )
1969 PEB * const peb = NtCurrentTeb()->Peb;
1971 RtlAcquirePebLock();
1972 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
1973 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
1976 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
1979 if (!NtCurrentTeb()->TlsExpansionSlots &&
1980 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
1981 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
1983 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
1985 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1989 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
1990 index += TLS_MINIMUM_AVAILABLE;
1993 else SetLastError( ERROR_NO_MORE_ITEMS );
1995 RtlReleasePebLock();
2000 /**********************************************************************
2001 * TlsFree [KERNEL32.@]
2003 * Releases a thread local storage index, making it available for reuse.
2006 * index [in] TLS index to free.
2012 BOOL WINAPI TlsFree( DWORD index )
2016 RtlAcquirePebLock();
2017 if (index >= TLS_MINIMUM_AVAILABLE)
2019 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2020 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2024 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2025 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2027 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2028 else SetLastError( ERROR_INVALID_PARAMETER );
2029 RtlReleasePebLock();
2034 /**********************************************************************
2035 * TlsGetValue [KERNEL32.@]
2037 * Gets value in a thread's TLS slot.
2040 * index [in] TLS index to retrieve value for.
2043 * Success: Value stored in calling thread's TLS slot for index.
2044 * Failure: 0 and GetLastError() returns NO_ERROR.
2046 LPVOID WINAPI TlsGetValue( DWORD index )
2050 if (index < TLS_MINIMUM_AVAILABLE)
2052 ret = NtCurrentTeb()->TlsSlots[index];
2056 index -= TLS_MINIMUM_AVAILABLE;
2057 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2059 SetLastError( ERROR_INVALID_PARAMETER );
2062 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2063 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2065 SetLastError( ERROR_SUCCESS );
2070 /**********************************************************************
2071 * TlsSetValue [KERNEL32.@]
2073 * Stores a value in the thread's TLS slot.
2076 * index [in] TLS index to set value for.
2077 * value [in] Value to be stored.
2083 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2085 if (index < TLS_MINIMUM_AVAILABLE)
2087 NtCurrentTeb()->TlsSlots[index] = value;
2091 index -= TLS_MINIMUM_AVAILABLE;
2092 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2094 SetLastError( ERROR_INVALID_PARAMETER );
2097 if (!NtCurrentTeb()->TlsExpansionSlots &&
2098 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2099 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2101 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2104 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2110 /***********************************************************************
2111 * GetProcessFlags (KERNEL32.@)
2113 DWORD WINAPI GetProcessFlags( DWORD processid )
2115 IMAGE_NT_HEADERS *nt;
2118 if (processid && processid != GetCurrentProcessId()) return 0;
2120 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2122 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2123 flags |= PDB32_CONSOLE_PROC;
2125 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2126 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2131 /***********************************************************************
2132 * GetProcessDword (KERNEL.485)
2133 * GetProcessDword (KERNEL32.18)
2134 * 'Of course you cannot directly access Windows internal structures'
2136 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2141 TRACE("(%ld, %d)\n", dwProcessID, offset );
2143 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2145 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2151 case GPD_APP_COMPAT_FLAGS:
2152 return GetAppCompatFlags16(0);
2153 case GPD_LOAD_DONE_EVENT:
2155 case GPD_HINSTANCE16:
2156 return GetTaskDS16();
2157 case GPD_WINDOWS_VERSION:
2158 return GetExeVersion16();
2160 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2162 return (DWORD)NtCurrentTeb()->Peb;
2163 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2164 GetStartupInfoW(&siw);
2165 return (DWORD)siw.hStdOutput;
2166 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2167 GetStartupInfoW(&siw);
2168 return (DWORD)siw.hStdInput;
2169 case GPD_STARTF_SHOWWINDOW:
2170 GetStartupInfoW(&siw);
2171 return siw.wShowWindow;
2172 case GPD_STARTF_SIZE:
2173 GetStartupInfoW(&siw);
2175 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2177 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2178 return MAKELONG( x, y );
2179 case GPD_STARTF_POSITION:
2180 GetStartupInfoW(&siw);
2182 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2184 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2185 return MAKELONG( x, y );
2186 case GPD_STARTF_FLAGS:
2187 GetStartupInfoW(&siw);
2192 return GetProcessFlags(0);
2194 return process_dword;
2196 ERR("Unknown offset %d\n", offset );
2201 /***********************************************************************
2202 * SetProcessDword (KERNEL.484)
2203 * 'Of course you cannot directly access Windows internal structures'
2205 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2207 TRACE("(%ld, %d)\n", dwProcessID, offset );
2209 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2211 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2217 case GPD_APP_COMPAT_FLAGS:
2218 case GPD_LOAD_DONE_EVENT:
2219 case GPD_HINSTANCE16:
2220 case GPD_WINDOWS_VERSION:
2223 case GPD_STARTF_SHELLDATA:
2224 case GPD_STARTF_HOTKEY:
2225 case GPD_STARTF_SHOWWINDOW:
2226 case GPD_STARTF_SIZE:
2227 case GPD_STARTF_POSITION:
2228 case GPD_STARTF_FLAGS:
2231 ERR("Not allowed to modify offset %d\n", offset );
2234 process_dword = value;
2237 ERR("Unknown offset %d\n", offset );
2243 /***********************************************************************
2244 * ExitProcess (KERNEL.466)
2246 void WINAPI ExitProcess16( WORD status )
2249 ReleaseThunkLock( &count );
2250 ExitProcess( status );
2254 /*********************************************************************
2255 * OpenProcess (KERNEL32.@)
2257 * Opens a handle to a process.
2260 * access [I] Desired access rights assigned to the returned handle.
2261 * inherit [I] Determines whether or not child processes will inherit the handle.
2262 * id [I] Process identifier of the process to get a handle to.
2265 * Success: Valid handle to the specified process.
2266 * Failure: NULL, check GetLastError().
2268 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2272 OBJECT_ATTRIBUTES attr;
2275 cid.UniqueProcess = (HANDLE)id;
2276 cid.UniqueThread = 0; /* FIXME ? */
2278 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2279 attr.RootDirectory = NULL;
2280 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2281 attr.SecurityDescriptor = NULL;
2282 attr.SecurityQualityOfService = NULL;
2283 attr.ObjectName = NULL;
2285 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2287 status = NtOpenProcess(&handle, access, &attr, &cid);
2288 if (status != STATUS_SUCCESS)
2290 SetLastError( RtlNtStatusToDosError(status) );
2297 /*********************************************************************
2298 * MapProcessHandle (KERNEL.483)
2299 * GetProcessId (KERNEL32.@)
2301 * Gets the a unique identifier of a process.
2304 * hProcess [I] Handle to the process.
2308 * Failure: FALSE, check GetLastError().
2312 * The identifier is unique only on the machine and only until the process
2313 * exits (including system shutdown).
2315 DWORD WINAPI GetProcessId( HANDLE hProcess )
2318 PROCESS_BASIC_INFORMATION pbi;
2320 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2322 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2323 SetLastError( RtlNtStatusToDosError(status) );
2328 /*********************************************************************
2329 * CloseW32Handle (KERNEL.474)
2330 * CloseHandle (KERNEL32.@)
2335 * handle [I] Handle to close.
2339 * Failure: FALSE, check GetLastError().
2341 BOOL WINAPI CloseHandle( HANDLE handle )
2345 /* stdio handles need special treatment */
2346 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2347 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2348 (handle == (HANDLE)STD_ERROR_HANDLE))
2349 handle = GetStdHandle( (DWORD)handle );
2351 if (is_console_handle(handle))
2352 return CloseConsoleHandle(handle);
2354 status = NtClose( handle );
2355 if (status) SetLastError( RtlNtStatusToDosError(status) );
2360 /*********************************************************************
2361 * GetHandleInformation (KERNEL32.@)
2363 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2365 OBJECT_DATA_INFORMATION info;
2366 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2368 if (status) SetLastError( RtlNtStatusToDosError(status) );
2372 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2373 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2379 /*********************************************************************
2380 * SetHandleInformation (KERNEL32.@)
2382 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2384 OBJECT_DATA_INFORMATION info;
2387 /* if not setting both fields, retrieve current value first */
2388 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2389 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2391 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2393 SetLastError( RtlNtStatusToDosError(status) );
2397 if (mask & HANDLE_FLAG_INHERIT)
2398 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2399 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2400 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2402 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2403 if (status) SetLastError( RtlNtStatusToDosError(status) );
2408 /*********************************************************************
2409 * DuplicateHandle (KERNEL32.@)
2411 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2412 HANDLE dest_process, HANDLE *dest,
2413 DWORD access, BOOL inherit, DWORD options )
2417 if (is_console_handle(source))
2419 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2420 if (source_process != dest_process ||
2421 source_process != GetCurrentProcess())
2423 SetLastError(ERROR_INVALID_PARAMETER);
2426 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2427 return (*dest != INVALID_HANDLE_VALUE);
2429 status = NtDuplicateObject( source_process, source, dest_process, dest,
2430 access, inherit ? OBJ_INHERIT : 0, options );
2431 if (status) SetLastError( RtlNtStatusToDosError(status) );
2436 /***********************************************************************
2437 * ConvertToGlobalHandle (KERNEL.476)
2438 * ConvertToGlobalHandle (KERNEL32.@)
2440 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2442 HANDLE ret = INVALID_HANDLE_VALUE;
2443 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2444 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2449 /***********************************************************************
2450 * SetHandleContext (KERNEL32.@)
2452 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2454 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2455 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2456 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2461 /***********************************************************************
2462 * GetHandleContext (KERNEL32.@)
2464 DWORD WINAPI GetHandleContext(HANDLE hnd)
2466 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2467 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2468 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2473 /***********************************************************************
2474 * CreateSocketHandle (KERNEL32.@)
2476 HANDLE WINAPI CreateSocketHandle(void)
2478 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2479 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2480 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2481 return INVALID_HANDLE_VALUE;
2485 /***********************************************************************
2486 * SetPriorityClass (KERNEL32.@)
2488 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2491 PROCESS_PRIORITY_CLASS ppc;
2493 ppc.Foreground = FALSE;
2494 switch (priorityclass)
2496 case IDLE_PRIORITY_CLASS:
2497 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2498 case BELOW_NORMAL_PRIORITY_CLASS:
2499 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2500 case NORMAL_PRIORITY_CLASS:
2501 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2502 case ABOVE_NORMAL_PRIORITY_CLASS:
2503 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2504 case HIGH_PRIORITY_CLASS:
2505 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2506 case REALTIME_PRIORITY_CLASS:
2507 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2509 SetLastError(ERROR_INVALID_PARAMETER);
2513 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2516 if (status != STATUS_SUCCESS)
2518 SetLastError( RtlNtStatusToDosError(status) );
2525 /***********************************************************************
2526 * GetPriorityClass (KERNEL32.@)
2528 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2531 PROCESS_BASIC_INFORMATION pbi;
2533 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2535 if (status != STATUS_SUCCESS)
2537 SetLastError( RtlNtStatusToDosError(status) );
2540 switch (pbi.BasePriority)
2542 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2543 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2544 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2545 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2546 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2547 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2549 SetLastError( ERROR_INVALID_PARAMETER );
2554 /***********************************************************************
2555 * SetProcessAffinityMask (KERNEL32.@)
2557 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2561 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2562 &affmask, sizeof(DWORD_PTR));
2565 SetLastError( RtlNtStatusToDosError(status) );
2572 /**********************************************************************
2573 * GetProcessAffinityMask (KERNEL32.@)
2575 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2576 PDWORD_PTR lpProcessAffinityMask,
2577 PDWORD_PTR lpSystemAffinityMask )
2579 PROCESS_BASIC_INFORMATION pbi;
2582 status = NtQueryInformationProcess(hProcess,
2583 ProcessBasicInformation,
2584 &pbi, sizeof(pbi), NULL);
2587 SetLastError( RtlNtStatusToDosError(status) );
2590 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2592 if (lpSystemAffinityMask) *lpSystemAffinityMask = 1;
2597 /***********************************************************************
2598 * GetProcessVersion (KERNEL32.@)
2600 DWORD WINAPI GetProcessVersion( DWORD processid )
2602 IMAGE_NT_HEADERS *nt;
2604 if (processid && processid != GetCurrentProcessId())
2606 FIXME("should use ReadProcessMemory\n");
2609 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2610 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2611 nt->OptionalHeader.MinorSubsystemVersion);
2616 /***********************************************************************
2617 * SetProcessWorkingSetSize [KERNEL32.@]
2618 * Sets the min/max working set sizes for a specified process.
2621 * hProcess [I] Handle to the process of interest
2622 * minset [I] Specifies minimum working set size
2623 * maxset [I] Specifies maximum working set size
2629 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2632 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2633 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2634 /* Trim the working set to zero */
2635 /* Swap the process out of physical RAM */
2640 /***********************************************************************
2641 * GetProcessWorkingSetSize (KERNEL32.@)
2643 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2646 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2647 /* 32 MB working set size */
2648 if (minset) *minset = 32*1024*1024;
2649 if (maxset) *maxset = 32*1024*1024;
2654 /***********************************************************************
2655 * SetProcessShutdownParameters (KERNEL32.@)
2657 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2659 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2660 shutdown_flags = flags;
2661 shutdown_priority = level;
2666 /***********************************************************************
2667 * GetProcessShutdownParameters (KERNEL32.@)
2670 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2672 *lpdwLevel = shutdown_priority;
2673 *lpdwFlags = shutdown_flags;
2678 /***********************************************************************
2679 * GetProcessPriorityBoost (KERNEL32.@)
2681 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2683 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2685 /* Report that no boost is present.. */
2686 *pDisablePriorityBoost = FALSE;
2691 /***********************************************************************
2692 * SetProcessPriorityBoost (KERNEL32.@)
2694 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2696 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2697 /* Say we can do it. I doubt the program will notice that we don't. */
2702 /***********************************************************************
2703 * ReadProcessMemory (KERNEL32.@)
2705 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2706 SIZE_T *bytes_read )
2708 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2709 if (status) SetLastError( RtlNtStatusToDosError(status) );
2714 /***********************************************************************
2715 * WriteProcessMemory (KERNEL32.@)
2717 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2718 SIZE_T *bytes_written )
2720 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2721 if (status) SetLastError( RtlNtStatusToDosError(status) );
2726 /****************************************************************************
2727 * FlushInstructionCache (KERNEL32.@)
2729 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2732 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2733 if (status) SetLastError( RtlNtStatusToDosError(status) );
2738 /******************************************************************
2739 * GetProcessIoCounters (KERNEL32.@)
2741 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2745 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2746 ioc, sizeof(*ioc), NULL);
2747 if (status) SetLastError( RtlNtStatusToDosError(status) );
2751 /***********************************************************************
2752 * ProcessIdToSessionId (KERNEL32.@)
2753 * This function is available on Terminal Server 4SP4 and Windows 2000
2755 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2757 /* According to MSDN, if the calling process is not in a terminal
2758 * services environment, then the sessionid returned is zero.
2765 /***********************************************************************
2766 * RegisterServiceProcess (KERNEL.491)
2767 * RegisterServiceProcess (KERNEL32.@)
2769 * A service process calls this function to ensure that it continues to run
2770 * even after a user logged off.
2772 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2774 /* I don't think that Wine needs to do anything in this function */
2775 return 1; /* success */
2779 /***********************************************************************
2780 * GetCurrentProcess (KERNEL32.@)
2782 * Get a handle to the current process.
2788 * A handle representing the current process.
2790 #undef GetCurrentProcess
2791 HANDLE WINAPI GetCurrentProcess(void)
2793 return (HANDLE)0xffffffff;
2796 /***********************************************************************
2797 * CmdBatNotification (KERNEL32.@)
2799 * Notifies the system that a batch file has started or finished.
2802 * bBatchRunning [I] TRUE if a batch file has started or
2803 * FALSE if a batch file has finished executing.
2808 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
2810 FIXME("%d\n", bBatchRunning);