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"
30 #ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
39 #ifdef HAVE_SYS_PRCTL_H
40 # include <sys/prctl.h>
42 #include <sys/types.h>
45 #define WIN32_NO_STATUS
46 #include "wine/winbase16.h"
47 #include "wine/winuser16.h"
49 #include "kernel_private.h"
50 #include "wine/exception.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(process);
56 WINE_DECLARE_DEBUG_CHANNEL(file);
57 WINE_DECLARE_DEBUG_CHANNEL(relay);
67 static UINT process_error_mode;
69 static DWORD shutdown_flags = 0;
70 static DWORD shutdown_priority = 0x280;
71 static DWORD process_dword;
73 HMODULE kernel32_handle = 0;
75 const WCHAR *DIR_Windows = NULL;
76 const WCHAR *DIR_System = NULL;
79 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
80 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
81 #define PDB32_DOS_PROC 0x0010 /* Dos process */
82 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
83 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
84 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
86 static const WCHAR comW[] = {'.','c','o','m',0};
87 static const WCHAR batW[] = {'.','b','a','t',0};
88 static const WCHAR cmdW[] = {'.','c','m','d',0};
89 static const WCHAR pifW[] = {'.','p','i','f',0};
90 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
92 static void exec_process( LPCWSTR name );
94 extern void SHELL_LoadRegistry(void);
97 /***********************************************************************
100 static inline int contains_path( LPCWSTR name )
102 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
106 /***********************************************************************
109 * Check if an environment variable needs to be handled specially when
110 * passed through the Unix environment (i.e. prefixed with "WINE").
112 static inline int is_special_env_var( const char *var )
114 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
115 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
116 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
117 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
121 /***************************************************************************
124 * Get the path of a builtin module when the native file does not exist.
126 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
129 UINT len = strlenW( DIR_System );
131 if (contains_path( libname ))
133 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
134 filename, &file_part ) > size * sizeof(WCHAR))
135 return FALSE; /* too long */
137 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
139 while (filename[len] == '\\') len++;
140 if (filename + len != file_part) return FALSE;
144 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
145 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
146 file_part = filename + len;
147 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
148 strcpyW( file_part, libname );
150 if (ext && !strchrW( file_part, '.' ))
152 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
153 return FALSE; /* too long */
154 strcatW( file_part, ext );
160 /***********************************************************************
161 * open_builtin_exe_file
163 * Open an exe file for a builtin exe.
165 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
166 int test_only, int *file_exists )
168 char exename[MAX_PATH];
173 if ((p = strrchrW( name, '/' ))) name = p + 1;
174 if ((p = strrchrW( name, '\\' ))) name = p + 1;
176 /* we don't want to depend on the current codepage here */
177 len = strlenW( name ) + 1;
178 if (len >= sizeof(exename)) return NULL;
179 for (i = 0; i < len; i++)
181 if (name[i] > 127) return NULL;
182 exename[i] = (char)name[i];
183 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
185 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
189 /***********************************************************************
192 * Open a specific exe file, taking load order into account.
193 * Returns the file handle or 0 for a builtin exe.
195 static HANDLE open_exe_file( const WCHAR *name )
199 TRACE("looking for %s\n", debugstr_w(name) );
201 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
202 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
204 WCHAR buffer[MAX_PATH];
205 /* file doesn't exist, check for builtin */
206 if (!contains_path( name )) goto error;
207 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
213 SetLastError( ERROR_FILE_NOT_FOUND );
214 return INVALID_HANDLE_VALUE;
218 /***********************************************************************
221 * Open an exe file, and return the full name and file handle.
222 * Returns FALSE if file could not be found.
223 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
224 * If file is a builtin exe, returns TRUE and sets handle to 0.
226 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
228 static const WCHAR exeW[] = {'.','e','x','e',0};
231 TRACE("looking for %s\n", debugstr_w(name) );
233 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
234 !get_builtin_path( name, exeW, buffer, buflen ))
236 /* no builtin found, try native without extension in case it is a Unix app */
238 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
240 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
241 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
242 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
248 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
249 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
250 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
253 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
254 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
265 /***********************************************************************
266 * build_initial_environment
268 * Build the Win32 environment from the Unix environment
270 static BOOL build_initial_environment( char **environ )
277 /* Compute the total size of the Unix environment */
278 for (e = environ; *e; e++)
280 if (is_special_env_var( *e )) continue;
281 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
283 size *= sizeof(WCHAR);
285 /* Now allocate the environment */
287 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
288 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
291 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
292 endptr = p + size / sizeof(WCHAR);
294 /* And fill it with the Unix environment */
295 for (e = environ; *e; e++)
299 /* skip Unix special variables and use the Wine variants instead */
300 if (!strncmp( str, "WINE", 4 ))
302 if (is_special_env_var( str + 4 )) str += 4;
303 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
305 else if (is_special_env_var( str )) continue; /* skip it */
307 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
315 /***********************************************************************
316 * set_registry_variables
318 * Set environment variables by enumerating the values of a key;
319 * helper for set_registry_environment().
320 * Note that Windows happily truncates the value if it's too big.
322 static void set_registry_variables( HANDLE hkey, ULONG type )
324 UNICODE_STRING env_name, env_value;
328 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
329 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
331 for (index = 0; ; index++)
333 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
334 buffer, sizeof(buffer), &size );
335 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
337 if (info->Type != type)
339 env_name.Buffer = info->Name;
340 env_name.Length = env_name.MaximumLength = info->NameLength;
341 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
342 env_value.Length = env_value.MaximumLength = info->DataLength;
343 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
344 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
345 if (info->Type == REG_EXPAND_SZ)
347 WCHAR buf_expanded[1024];
348 UNICODE_STRING env_expanded;
349 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
350 env_expanded.Buffer=buf_expanded;
351 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
352 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
353 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
357 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
363 /***********************************************************************
364 * set_registry_environment
366 * Set the environment variables specified in the registry.
368 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
369 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
370 * on the order in which the variables are processed. But on Windows it
371 * does not really matter since they only use %SystemDrive% and
372 * %SystemRoot% which are predefined. But Wine defines these in the
373 * registry, so we need two passes.
375 static BOOL set_registry_environment(void)
377 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
378 'S','y','s','t','e','m','\\',
379 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
380 'C','o','n','t','r','o','l','\\',
381 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
382 'E','n','v','i','r','o','n','m','e','n','t',0};
383 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
385 OBJECT_ATTRIBUTES attr;
386 UNICODE_STRING nameW;
390 attr.Length = sizeof(attr);
391 attr.RootDirectory = 0;
392 attr.ObjectName = &nameW;
394 attr.SecurityDescriptor = NULL;
395 attr.SecurityQualityOfService = NULL;
397 /* first the system environment variables */
398 RtlInitUnicodeString( &nameW, env_keyW );
399 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
401 set_registry_variables( hkey, REG_SZ );
402 set_registry_variables( hkey, REG_EXPAND_SZ );
407 /* then the ones for the current user */
408 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
409 RtlInitUnicodeString( &nameW, envW );
410 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
412 set_registry_variables( hkey, REG_SZ );
413 set_registry_variables( hkey, REG_EXPAND_SZ );
416 NtClose( attr.RootDirectory );
420 /***********************************************************************
421 * set_additional_environment
423 * Set some additional environment variables not specified in the registry.
425 static void set_additional_environment(void)
427 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
428 const char *name = wine_get_user_name();
429 DWORD len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
432 LPWSTR nameW = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
433 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, nameW, len );
434 SetEnvironmentVariableW( usernameW, nameW );
435 HeapFree( GetProcessHeap(), 0, nameW );
439 /***********************************************************************
442 * Set the Wine library Unicode argv global variables.
444 static void set_library_wargv( char **argv )
452 for (argc = 0; argv[argc]; argc++)
453 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
455 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
456 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
457 p = (WCHAR *)(wargv + argc + 1);
458 for (argc = 0; argv[argc]; argc++)
460 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
467 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
469 for (argc = 0; wargv[argc]; argc++)
470 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
472 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
473 q = (char *)(argv + argc + 1);
474 for (argc = 0; wargv[argc]; argc++)
476 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
483 __wine_main_argc = argc;
484 __wine_main_argv = argv;
485 __wine_main_wargv = wargv;
489 /***********************************************************************
492 * Build the command line of a process from the argv array.
494 * Note that it does NOT necessarily include the file name.
495 * Sometimes we don't even have any command line options at all.
497 * We must quote and escape characters so that the argv array can be rebuilt
498 * from the command line:
499 * - spaces and tabs must be quoted
501 * - quotes must be escaped
503 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
504 * resulting in an odd number of '\' followed by a '"'
507 * - '\'s that are not followed by a '"' can be left as is
511 static BOOL build_command_line( WCHAR **argv )
516 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
518 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
521 for (arg = argv; *arg; arg++)
523 int has_space,bcount;
529 if( !*a ) has_space=1;
534 if (*a==' ' || *a=='\t') {
536 } else if (*a=='"') {
537 /* doubling of '\' preceding a '"',
538 * plus escaping of said '"'
546 len+=(a-*arg)+1 /* for the separating space */;
548 len+=2; /* for the quotes */
551 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
554 p = rupp->CommandLine.Buffer;
555 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
556 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
557 for (arg = argv; *arg; arg++)
559 int has_space,has_quote;
562 /* Check for quotes and spaces in this argument */
563 has_space=has_quote=0;
565 if( !*a ) has_space=1;
567 if (*a==' ' || *a=='\t') {
571 } else if (*a=='"') {
579 /* Now transfer it to the command line */
596 /* Double all the '\\' preceding this '"', plus one */
597 for (i=0;i<=bcount;i++)
609 while ((*p=*x++)) p++;
615 if (p > rupp->CommandLine.Buffer)
616 p--; /* remove last space */
623 /***********************************************************************
624 * init_current_directory
626 * Initialize the current directory from the Unix cwd or the parent info.
628 static void init_current_directory( CURDIR *cur_dir )
630 UNICODE_STRING dir_str;
634 /* if we received a cur dir from the parent, try this first */
636 if (cur_dir->DosPath.Length)
638 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
641 /* now try to get it from the Unix cwd */
643 for (size = 256; ; size *= 2)
645 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
646 if (getcwd( cwd, size )) break;
647 HeapFree( GetProcessHeap(), 0, cwd );
648 if (errno == ERANGE) continue;
656 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
657 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
659 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
660 RtlInitUnicodeString( &dir_str, dirW );
661 RtlSetCurrentDirectory_U( &dir_str );
662 RtlFreeUnicodeString( &dir_str );
666 if (!cur_dir->DosPath.Length) /* still not initialized */
668 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
669 "starting in the Windows directory.\n", cwd ? cwd : "" );
670 RtlInitUnicodeString( &dir_str, DIR_Windows );
671 RtlSetCurrentDirectory_U( &dir_str );
673 HeapFree( GetProcessHeap(), 0, cwd );
676 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
677 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
681 /***********************************************************************
684 * Initialize the windows and system directories from the environment.
686 static void init_windows_dirs(void)
688 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
690 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
691 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
692 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
693 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
698 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
700 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
701 GetEnvironmentVariableW( windirW, buffer, len );
702 DIR_Windows = buffer;
704 else DIR_Windows = default_windirW;
706 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
708 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
709 GetEnvironmentVariableW( winsysdirW, buffer, len );
714 len = strlenW( DIR_Windows );
715 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
716 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
717 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
721 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
722 ERR( "directory %s could not be created, error %u\n",
723 debugstr_w(DIR_Windows), GetLastError() );
724 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
725 ERR( "directory %s could not be created, error %u\n",
726 debugstr_w(DIR_System), GetLastError() );
728 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
729 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
731 /* set the directories in ntdll too */
732 __wine_init_windows_dir( DIR_Windows, DIR_System );
736 /***********************************************************************
739 * Start the wineboot process if necessary. Return the event to wait on.
741 static HANDLE start_wineboot(void)
743 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
746 if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
748 ERR( "failed to create wineboot event, expect trouble\n" );
751 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
753 static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
755 PROCESS_INFORMATION pi;
756 WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];
758 memset( &si, 0, sizeof(si) );
760 si.dwFlags = STARTF_USESTDHANDLES;
763 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
765 GetSystemDirectoryW( cmdline, MAX_PATH );
766 lstrcatW( cmdline, command_line );
767 if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
769 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
770 CloseHandle( pi.hThread );
771 CloseHandle( pi.hProcess );
774 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
780 /***********************************************************************
783 * Startup routine of a new process. Runs on the new process stack.
785 static void start_process( void *arg )
789 PEB *peb = NtCurrentTeb()->Peb;
790 IMAGE_NT_HEADERS *nt;
791 LPTHREAD_START_ROUTINE entry;
793 nt = RtlImageNtHeader( peb->ImageBaseAddress );
794 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
795 nt->OptionalHeader.AddressOfEntryPoint);
798 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
799 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
801 SetLastError( 0 ); /* clear error code */
802 if (peb->BeingDebugged) DbgBreakPoint();
803 ExitThread( entry( peb ) );
805 __EXCEPT(UnhandledExceptionFilter)
807 TerminateThread( GetCurrentThread(), GetExceptionCode() );
813 /***********************************************************************
816 * Change the process name in the ps output.
818 static void set_process_name( int argc, char *argv[] )
820 #ifdef HAVE_SETPROCTITLE
821 setproctitle("-%s", argv[1]);
826 char *p, *prctl_name = argv[1];
827 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
830 # define PR_SET_NAME 15
833 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
834 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
836 if (prctl( PR_SET_NAME, prctl_name ) != -1)
838 offset = argv[1] - argv[0];
839 memmove( argv[1] - offset, argv[1], end - argv[1] );
840 memset( end - offset, 0, offset );
841 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
845 #endif /* HAVE_PRCTL */
848 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
853 /***********************************************************************
856 * Wine initialisation: load and start the main exe file.
858 void __wine_kernel_init(void)
860 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
861 static const WCHAR dotW[] = {'.',0};
862 static const WCHAR exeW[] = {'.','e','x','e',0};
864 WCHAR *p, main_exe_name[MAX_PATH+1];
865 PEB *peb = NtCurrentTeb()->Peb;
866 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
867 HANDLE boot_event = 0;
868 BOOL got_environment = TRUE;
870 /* Initialize everything */
876 kernel32_handle = GetModuleHandleW(kernel32W);
880 if (!params->Environment)
882 /* Copy the parent environment */
883 if (!build_initial_environment( __wine_main_environ )) exit(1);
885 /* convert old configuration to new format */
886 convert_old_config();
888 got_environment = set_registry_environment();
889 set_additional_environment();
893 init_current_directory( ¶ms->CurrentDirectory );
895 set_process_name( __wine_main_argc, __wine_main_argv );
896 set_library_wargv( __wine_main_argv );
898 if (peb->ProcessParameters->ImagePathName.Buffer)
900 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
904 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
905 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
907 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
908 ExitProcess( GetLastError() );
910 if (!build_command_line( __wine_main_wargv )) goto error;
911 boot_event = start_wineboot();
914 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
915 p = strrchrW( main_exe_name, '.' );
916 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
918 TRACE( "starting process name=%s argv[0]=%s\n",
919 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
921 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
922 MODULE_get_dll_load_path(main_exe_name) );
924 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
927 DWORD error = GetLastError();
929 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
930 if (error == ERROR_BAD_EXE_FORMAT ||
931 error == ERROR_INVALID_ADDRESS ||
932 error == ERROR_NOT_ENOUGH_MEMORY)
934 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
935 /* if we get back here, it failed */
938 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
939 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
940 ExitProcess( error );
945 if (WaitForSingleObject( boot_event, 30000 )) WARN( "boot event wait timed out\n" );
946 CloseHandle( boot_event );
947 /* if we didn't find environment section, try again now that wineboot has run */
948 if (!got_environment) set_registry_environment();
951 LdrInitializeThunk( 0, 0, 0, 0 );
952 /* switch to the new stack */
953 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
956 ExitProcess( GetLastError() );
960 /***********************************************************************
963 * Build an argv array from a command-line.
964 * 'reserved' is the number of args to reserve before the first one.
966 static char **build_argv( const WCHAR *cmdlineW, int reserved )
970 char *arg,*s,*d,*cmdline;
971 int in_quotes,bcount,len;
973 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
974 if (!(cmdline = malloc(len))) return NULL;
975 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
982 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
985 /* skip the remaining spaces */
986 while (*s==' ' || *s=='\t') {
993 } else if (*s=='\\') {
994 /* '\', count them */
996 } else if ((*s=='"') && ((bcount & 1)==0)) {
998 in_quotes=!in_quotes;
1001 /* a regular character */
1006 argv=malloc(argc*sizeof(*argv));
1015 if ((*s==' ' || *s=='\t') && !in_quotes) {
1016 /* Close the argument and copy it */
1020 /* skip the remaining spaces */
1023 } while (*s==' ' || *s=='\t');
1025 /* Start with a new argument */
1028 } else if (*s=='\\') {
1032 } else if (*s=='"') {
1034 if ((bcount & 1)==0) {
1035 /* Preceded by an even number of '\', this is half that
1036 * number of '\', plus a '"' which we discard.
1040 in_quotes=!in_quotes;
1042 /* Preceded by an odd number of '\', this is half that
1043 * number of '\' followed by a '"'
1051 /* a regular character */
1066 /***********************************************************************
1069 * Allocate an environment string; helper for build_envp
1071 static char *alloc_env_string( const char *name, const char *value )
1073 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1074 strcpy( ret, name );
1075 strcat( ret, value );
1079 /***********************************************************************
1082 * Build the environment of a new child process.
1084 static char **build_envp( const WCHAR *envW )
1089 int count = 0, length;
1091 for (end = envW; *end; count++) end += strlenW(end) + 1;
1093 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1094 if (!(env = malloc( length ))) return NULL;
1095 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1099 if ((envp = malloc( count * sizeof(*envp) )))
1101 char **envptr = envp;
1103 /* some variables must not be modified, so we get them directly from the unix env */
1104 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1105 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1106 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1107 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1108 /* now put the Windows environment strings */
1109 for (p = env; *p; p += strlen(p) + 1)
1111 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1112 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1113 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1114 if (is_special_env_var( p )) /* prefix it with "WINE" */
1115 *envptr++ = alloc_env_string( "WINE", p );
1125 /***********************************************************************
1128 * Fork and exec a new Unix binary, checking for errors.
1130 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1131 const WCHAR *env, const char *newdir, DWORD flags )
1136 if (!env) env = GetEnvironmentStringsW();
1140 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1143 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1144 if (!(pid = fork())) /* child */
1146 char **argv = build_argv( cmdline, 0 );
1147 char **envp = build_envp( env );
1150 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1153 if (!(pid = fork()))
1155 int fd = open( "/dev/null", O_RDWR );
1157 /* close stdin and stdout */
1165 else if (pid != -1) _exit(0); /* parent */
1168 /* Reset signals that we previously set to SIG_IGN */
1169 signal( SIGPIPE, SIG_DFL );
1170 signal( SIGCHLD, SIG_DFL );
1172 if (newdir) chdir(newdir);
1174 if (argv && envp) execve( filename, argv, envp );
1176 write( fd[1], &err, sizeof(err) );
1180 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1185 if (pid == -1) FILE_SetDosError();
1191 /***********************************************************************
1192 * create_user_params
1194 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1195 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1196 const STARTUPINFOW *startup )
1198 RTL_USER_PROCESS_PARAMETERS *params;
1199 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1201 WCHAR buffer[MAX_PATH];
1203 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1204 lstrcpynW( buffer, filename, MAX_PATH );
1205 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1206 lstrcpynW( buffer, filename, MAX_PATH );
1207 RtlInitUnicodeString( &image_str, buffer );
1209 RtlInitUnicodeString( &cmdline_str, cmdline );
1210 newdir.Buffer = NULL;
1213 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1215 /* skip \??\ prefix */
1216 curdir_str.Buffer = newdir.Buffer + 4;
1217 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1218 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1220 else cur_dir = NULL;
1222 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1223 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1224 if (startup->lpReserved2 && startup->cbReserved2)
1227 runtime.MaximumLength = startup->cbReserved2;
1228 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1231 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1232 cur_dir ? &curdir_str : NULL,
1234 startup->lpTitle ? &title : NULL,
1235 startup->lpDesktop ? &desktop : NULL,
1237 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1238 RtlFreeUnicodeString( &newdir );
1239 if (status != STATUS_SUCCESS)
1241 SetLastError( RtlNtStatusToDosError(status) );
1245 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1246 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1248 if (startup->dwFlags & STARTF_USESTDHANDLES)
1250 params->hStdInput = startup->hStdInput;
1251 params->hStdOutput = startup->hStdOutput;
1252 params->hStdError = startup->hStdError;
1256 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1257 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1258 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1260 params->dwX = startup->dwX;
1261 params->dwY = startup->dwY;
1262 params->dwXSize = startup->dwXSize;
1263 params->dwYSize = startup->dwYSize;
1264 params->dwXCountChars = startup->dwXCountChars;
1265 params->dwYCountChars = startup->dwYCountChars;
1266 params->dwFillAttribute = startup->dwFillAttribute;
1267 params->dwFlags = startup->dwFlags;
1268 params->wShowWindow = startup->wShowWindow;
1273 /***********************************************************************
1276 * Create a new process. If hFile is a valid handle we have an exe
1277 * file, otherwise it is a Winelib app.
1279 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1280 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1281 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1282 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1283 void *res_start, void *res_end, int exec_only )
1285 BOOL ret, success = FALSE;
1286 HANDLE process_info;
1288 char *winedebug = NULL;
1289 RTL_USER_PROCESS_PARAMETERS *params;
1294 if (!env) RtlAcquirePebLock();
1296 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1298 if (!env) RtlReleasePebLock();
1301 env_end = params->Environment;
1304 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1305 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1307 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1308 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1309 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1311 env_end += strlenW(env_end) + 1;
1315 /* create the socket for the new process */
1317 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1319 if (!env) RtlReleasePebLock();
1320 HeapFree( GetProcessHeap(), 0, winedebug );
1321 RtlDestroyProcessParameters( params );
1322 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1325 wine_server_send_fd( socketfd[1] );
1326 close( socketfd[1] );
1328 /* create the process on the server side */
1330 SERVER_START_REQ( new_process )
1332 req->inherit_all = inherit;
1333 req->create_flags = flags;
1334 req->socket_fd = socketfd[1];
1335 req->exe_file = hFile;
1336 req->process_access = PROCESS_ALL_ACCESS;
1337 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1338 req->thread_access = THREAD_ALL_ACCESS;
1339 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1340 req->hstdin = params->hStdInput;
1341 req->hstdout = params->hStdOutput;
1342 req->hstderr = params->hStdError;
1344 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1346 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1347 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1348 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1349 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1353 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1354 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1355 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1358 wine_server_add_data( req, params, params->Size );
1359 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1360 if ((ret = !wine_server_call_err( req )))
1362 info->dwProcessId = (DWORD)reply->pid;
1363 info->dwThreadId = (DWORD)reply->tid;
1364 info->hProcess = reply->phandle;
1365 info->hThread = reply->thandle;
1367 process_info = reply->info;
1371 if (!env) RtlReleasePebLock();
1372 RtlDestroyProcessParameters( params );
1375 close( socketfd[0] );
1376 HeapFree( GetProcessHeap(), 0, winedebug );
1380 /* create the child process */
1382 if (exec_only || !(pid = fork())) /* child */
1384 char preloader_reserve[64], socket_env[64];
1385 char **argv = build_argv( cmd_line, 1 );
1387 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1389 if (!(pid = fork()))
1391 int fd = open( "/dev/null", O_RDWR );
1393 /* close stdin and stdout */
1401 else if (pid != -1) _exit(0); /* parent */
1404 /* Reset signals that we previously set to SIG_IGN */
1405 signal( SIGPIPE, SIG_DFL );
1406 signal( SIGCHLD, SIG_DFL );
1408 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1409 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1410 (unsigned long)res_start, (unsigned long)res_end );
1412 putenv( preloader_reserve );
1413 putenv( socket_env );
1414 if (winedebug) putenv( winedebug );
1415 if (unixdir) chdir(unixdir);
1417 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1421 /* this is the parent */
1423 close( socketfd[0] );
1424 HeapFree( GetProcessHeap(), 0, winedebug );
1431 /* wait for the new process info to be ready */
1433 WaitForSingleObject( process_info, INFINITE );
1434 SERVER_START_REQ( get_new_process_info )
1436 req->info = process_info;
1437 wine_server_call( req );
1438 success = reply->success;
1439 err = reply->exit_code;
1445 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1448 CloseHandle( process_info );
1452 CloseHandle( process_info );
1453 CloseHandle( info->hProcess );
1454 CloseHandle( info->hThread );
1455 info->hProcess = info->hThread = 0;
1456 info->dwProcessId = info->dwThreadId = 0;
1461 /***********************************************************************
1462 * create_vdm_process
1464 * Create a new VDM process for a 16-bit or DOS application.
1466 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1467 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1468 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1469 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1471 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1474 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1475 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1479 SetLastError( ERROR_OUTOFMEMORY );
1482 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1483 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1484 flags, startup, info, unixdir, NULL, NULL, exec_only );
1485 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1490 /***********************************************************************
1491 * create_cmd_process
1493 * Create a new cmd shell process for a .BAT file.
1495 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1496 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1497 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1498 LPPROCESS_INFORMATION info )
1501 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1502 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1503 WCHAR comspec[MAX_PATH];
1507 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1509 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1510 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1513 strcpyW( newcmdline, comspec );
1514 strcatW( newcmdline, slashcW );
1515 strcatW( newcmdline, cmd_line );
1516 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1517 flags, env, cur_dir, startup, info );
1518 HeapFree( GetProcessHeap(), 0, newcmdline );
1523 /*************************************************************************
1526 * Helper for CreateProcess: retrieve the file name to load from the
1527 * app name and command line. Store the file name in buffer, and
1528 * return a possibly modified command line.
1529 * Also returns a handle to the opened file if it's a Windows binary.
1531 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1532 int buflen, HANDLE *handle )
1534 static const WCHAR quotesW[] = {'"','%','s','"',0};
1536 WCHAR *name, *pos, *ret = NULL;
1540 /* if we have an app name, everything is easy */
1544 /* use the unmodified app name as file name */
1545 lstrcpynW( buffer, appname, buflen );
1546 *handle = open_exe_file( buffer );
1547 if (!(ret = cmdline) || !cmdline[0])
1549 /* no command-line, create one */
1550 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1551 sprintfW( ret, quotesW, appname );
1558 SetLastError( ERROR_INVALID_PARAMETER );
1562 /* first check for a quoted file name */
1564 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1566 int len = p - cmdline - 1;
1567 /* extract the quoted portion as file name */
1568 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1569 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1572 if (find_exe_file( name, buffer, buflen, handle ))
1573 ret = cmdline; /* no change necessary */
1577 /* now try the command-line word by word */
1579 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1587 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1589 if (find_exe_file( name, buffer, buflen, handle ))
1594 if (*p) got_space = TRUE;
1597 if (ret && got_space) /* now build a new command-line with quotes */
1599 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1601 sprintfW( ret, quotesW, name );
1606 HeapFree( GetProcessHeap(), 0, name );
1611 /**********************************************************************
1612 * CreateProcessA (KERNEL32.@)
1614 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1615 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1616 DWORD flags, LPVOID env, LPCSTR cur_dir,
1617 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1620 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1621 UNICODE_STRING desktopW, titleW;
1624 desktopW.Buffer = NULL;
1625 titleW.Buffer = NULL;
1626 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1627 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1628 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1630 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1631 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1633 memcpy( &infoW, startup_info, sizeof(infoW) );
1634 infoW.lpDesktop = desktopW.Buffer;
1635 infoW.lpTitle = titleW.Buffer;
1637 if (startup_info->lpReserved)
1638 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1639 debugstr_a(startup_info->lpReserved));
1641 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1642 inherit, flags, env, cur_dirW, &infoW, info );
1644 HeapFree( GetProcessHeap(), 0, app_nameW );
1645 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1646 HeapFree( GetProcessHeap(), 0, cur_dirW );
1647 RtlFreeUnicodeString( &desktopW );
1648 RtlFreeUnicodeString( &titleW );
1653 /**********************************************************************
1654 * CreateProcessW (KERNEL32.@)
1656 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1657 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1658 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1659 LPPROCESS_INFORMATION info )
1663 char *unixdir = NULL;
1664 WCHAR name[MAX_PATH];
1665 WCHAR *tidy_cmdline, *p, *envW = env;
1666 void *res_start, *res_end;
1668 /* Process the AppName and/or CmdLine to get module name and path */
1670 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1672 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1674 if (hFile == INVALID_HANDLE_VALUE) goto done;
1676 /* Warn if unsupported features are used */
1678 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1679 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1680 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1681 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1682 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1686 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1688 SetLastError(ERROR_DIRECTORY);
1694 WCHAR buf[MAX_PATH];
1695 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1698 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1703 while (*p) p += strlen(p) + 1;
1704 p++; /* final null */
1705 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1706 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1707 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1708 flags |= CREATE_UNICODE_ENVIRONMENT;
1711 info->hThread = info->hProcess = 0;
1712 info->dwProcessId = info->dwThreadId = 0;
1714 /* Determine executable type */
1716 if (!hFile) /* builtin exe */
1718 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1719 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1720 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1724 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1727 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1728 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1729 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1734 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1735 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1736 inherit, flags, startup_info, info, unixdir, FALSE );
1739 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1740 SetLastError( ERROR_BAD_EXE_FORMAT );
1742 case BINARY_UNIX_LIB:
1743 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1744 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1745 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1747 case BINARY_UNKNOWN:
1748 /* check for .com or .bat extension */
1749 if ((p = strrchrW( name, '.' )))
1751 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1753 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1754 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1755 inherit, flags, startup_info, info, unixdir, FALSE );
1758 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1760 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1761 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1762 inherit, flags, startup_info, info );
1767 case BINARY_UNIX_EXE:
1769 /* unknown file, try as unix executable */
1772 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1774 if ((unix_name = wine_get_unix_file_name( name )))
1776 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags ) != -1);
1777 HeapFree( GetProcessHeap(), 0, unix_name );
1782 CloseHandle( hFile );
1785 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1786 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1787 HeapFree( GetProcessHeap(), 0, unixdir );
1792 /**********************************************************************
1795 static void exec_process( LPCWSTR name )
1799 void *res_start, *res_end;
1800 STARTUPINFOW startup_info;
1801 PROCESS_INFORMATION info;
1803 hFile = open_exe_file( name );
1804 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
1806 memset( &startup_info, 0, sizeof(startup_info) );
1807 startup_info.cb = sizeof(startup_info);
1809 /* Determine executable type */
1811 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1814 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1815 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1816 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
1818 case BINARY_UNIX_LIB:
1819 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1820 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1821 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
1823 case BINARY_UNKNOWN:
1824 /* check for .com or .pif extension */
1825 if (!(p = strrchrW( name, '.' ))) break;
1826 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
1831 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1832 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1833 FALSE, 0, &startup_info, &info, NULL, TRUE );
1838 CloseHandle( hFile );
1842 /***********************************************************************
1845 * Wrapper to call WaitForInputIdle USER function
1847 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1849 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1851 HMODULE mod = GetModuleHandleA( "user32.dll" );
1854 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1855 if (ptr) return ptr( process, timeout );
1861 /***********************************************************************
1862 * WinExec (KERNEL32.@)
1864 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1866 PROCESS_INFORMATION info;
1867 STARTUPINFOA startup;
1871 memset( &startup, 0, sizeof(startup) );
1872 startup.cb = sizeof(startup);
1873 startup.dwFlags = STARTF_USESHOWWINDOW;
1874 startup.wShowWindow = nCmdShow;
1876 /* cmdline needs to be writable for CreateProcess */
1877 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1878 strcpy( cmdline, lpCmdLine );
1880 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1881 0, NULL, NULL, &startup, &info ))
1883 /* Give 30 seconds to the app to come up */
1884 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1885 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1887 /* Close off the handles */
1888 CloseHandle( info.hThread );
1889 CloseHandle( info.hProcess );
1891 else if ((ret = GetLastError()) >= 32)
1893 FIXME("Strange error set by CreateProcess: %d\n", ret );
1896 HeapFree( GetProcessHeap(), 0, cmdline );
1901 /**********************************************************************
1902 * LoadModule (KERNEL32.@)
1904 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1906 LOADPARMS32 *params = paramBlock;
1907 PROCESS_INFORMATION info;
1908 STARTUPINFOA startup;
1909 HINSTANCE hInstance;
1911 char filename[MAX_PATH];
1914 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1916 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1917 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1918 return ULongToHandle(GetLastError());
1920 len = (BYTE)params->lpCmdLine[0];
1921 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1922 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1924 strcpy( cmdline, filename );
1925 p = cmdline + strlen(cmdline);
1927 memcpy( p, params->lpCmdLine + 1, len );
1930 memset( &startup, 0, sizeof(startup) );
1931 startup.cb = sizeof(startup);
1932 if (params->lpCmdShow)
1934 startup.dwFlags = STARTF_USESHOWWINDOW;
1935 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1938 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1939 params->lpEnvAddress, NULL, &startup, &info ))
1941 /* Give 30 seconds to the app to come up */
1942 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1943 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1944 hInstance = (HINSTANCE)33;
1945 /* Close off the handles */
1946 CloseHandle( info.hThread );
1947 CloseHandle( info.hProcess );
1949 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
1951 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1952 hInstance = (HINSTANCE)11;
1955 HeapFree( GetProcessHeap(), 0, cmdline );
1960 /******************************************************************************
1961 * TerminateProcess (KERNEL32.@)
1963 * Terminates a process.
1966 * handle [I] Process to terminate.
1967 * exit_code [I] Exit code.
1971 * Failure: FALSE, check GetLastError().
1973 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1975 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1976 if (status) SetLastError( RtlNtStatusToDosError(status) );
1981 /***********************************************************************
1982 * ExitProcess (KERNEL32.@)
1984 * Exits the current process.
1987 * status [I] Status code to exit with.
1992 void WINAPI ExitProcess( DWORD status )
1994 LdrShutdownProcess();
1995 NtTerminateProcess(GetCurrentProcess(), status);
2000 /***********************************************************************
2001 * GetExitCodeProcess [KERNEL32.@]
2003 * Gets termination status of specified process.
2006 * hProcess [in] Handle to the process.
2007 * lpExitCode [out] Address to receive termination status.
2013 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2016 PROCESS_BASIC_INFORMATION pbi;
2018 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2020 if (status == STATUS_SUCCESS)
2022 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2025 SetLastError( RtlNtStatusToDosError(status) );
2030 /***********************************************************************
2031 * SetErrorMode (KERNEL32.@)
2033 UINT WINAPI SetErrorMode( UINT mode )
2035 UINT old = process_error_mode;
2036 process_error_mode = mode;
2041 /**********************************************************************
2042 * TlsAlloc [KERNEL32.@]
2044 * Allocates a thread local storage index.
2047 * Success: TLS index.
2048 * Failure: 0xFFFFFFFF
2050 DWORD WINAPI TlsAlloc( void )
2053 PEB * const peb = NtCurrentTeb()->Peb;
2055 RtlAcquirePebLock();
2056 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2057 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2060 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2063 if (!NtCurrentTeb()->TlsExpansionSlots &&
2064 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2065 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2067 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2069 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2073 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2074 index += TLS_MINIMUM_AVAILABLE;
2077 else SetLastError( ERROR_NO_MORE_ITEMS );
2079 RtlReleasePebLock();
2084 /**********************************************************************
2085 * TlsFree [KERNEL32.@]
2087 * Releases a thread local storage index, making it available for reuse.
2090 * index [in] TLS index to free.
2096 BOOL WINAPI TlsFree( DWORD index )
2100 RtlAcquirePebLock();
2101 if (index >= TLS_MINIMUM_AVAILABLE)
2103 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2104 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2108 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2109 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2111 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2112 else SetLastError( ERROR_INVALID_PARAMETER );
2113 RtlReleasePebLock();
2118 /**********************************************************************
2119 * TlsGetValue [KERNEL32.@]
2121 * Gets value in a thread's TLS slot.
2124 * index [in] TLS index to retrieve value for.
2127 * Success: Value stored in calling thread's TLS slot for index.
2128 * Failure: 0 and GetLastError() returns NO_ERROR.
2130 LPVOID WINAPI TlsGetValue( DWORD index )
2134 if (index < TLS_MINIMUM_AVAILABLE)
2136 ret = NtCurrentTeb()->TlsSlots[index];
2140 index -= TLS_MINIMUM_AVAILABLE;
2141 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2143 SetLastError( ERROR_INVALID_PARAMETER );
2146 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2147 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2149 SetLastError( ERROR_SUCCESS );
2154 /**********************************************************************
2155 * TlsSetValue [KERNEL32.@]
2157 * Stores a value in the thread's TLS slot.
2160 * index [in] TLS index to set value for.
2161 * value [in] Value to be stored.
2167 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2169 if (index < TLS_MINIMUM_AVAILABLE)
2171 NtCurrentTeb()->TlsSlots[index] = value;
2175 index -= TLS_MINIMUM_AVAILABLE;
2176 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2178 SetLastError( ERROR_INVALID_PARAMETER );
2181 if (!NtCurrentTeb()->TlsExpansionSlots &&
2182 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2183 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2185 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2188 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2194 /***********************************************************************
2195 * GetProcessFlags (KERNEL32.@)
2197 DWORD WINAPI GetProcessFlags( DWORD processid )
2199 IMAGE_NT_HEADERS *nt;
2202 if (processid && processid != GetCurrentProcessId()) return 0;
2204 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2206 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2207 flags |= PDB32_CONSOLE_PROC;
2209 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2210 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2215 /***********************************************************************
2216 * GetProcessDword (KERNEL.485)
2217 * GetProcessDword (KERNEL32.18)
2218 * 'Of course you cannot directly access Windows internal structures'
2220 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2225 TRACE("(%d, %d)\n", dwProcessID, offset );
2227 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2229 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2235 case GPD_APP_COMPAT_FLAGS:
2236 return GetAppCompatFlags16(0);
2237 case GPD_LOAD_DONE_EVENT:
2239 case GPD_HINSTANCE16:
2240 return GetTaskDS16();
2241 case GPD_WINDOWS_VERSION:
2242 return GetExeVersion16();
2244 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2246 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2247 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2248 GetStartupInfoW(&siw);
2249 return HandleToULong(siw.hStdOutput);
2250 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2251 GetStartupInfoW(&siw);
2252 return HandleToULong(siw.hStdInput);
2253 case GPD_STARTF_SHOWWINDOW:
2254 GetStartupInfoW(&siw);
2255 return siw.wShowWindow;
2256 case GPD_STARTF_SIZE:
2257 GetStartupInfoW(&siw);
2259 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2261 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2262 return MAKELONG( x, y );
2263 case GPD_STARTF_POSITION:
2264 GetStartupInfoW(&siw);
2266 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2268 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2269 return MAKELONG( x, y );
2270 case GPD_STARTF_FLAGS:
2271 GetStartupInfoW(&siw);
2276 return GetProcessFlags(0);
2278 return process_dword;
2280 ERR("Unknown offset %d\n", offset );
2285 /***********************************************************************
2286 * SetProcessDword (KERNEL.484)
2287 * 'Of course you cannot directly access Windows internal structures'
2289 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2291 TRACE("(%d, %d)\n", dwProcessID, offset );
2293 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2295 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2301 case GPD_APP_COMPAT_FLAGS:
2302 case GPD_LOAD_DONE_EVENT:
2303 case GPD_HINSTANCE16:
2304 case GPD_WINDOWS_VERSION:
2307 case GPD_STARTF_SHELLDATA:
2308 case GPD_STARTF_HOTKEY:
2309 case GPD_STARTF_SHOWWINDOW:
2310 case GPD_STARTF_SIZE:
2311 case GPD_STARTF_POSITION:
2312 case GPD_STARTF_FLAGS:
2315 ERR("Not allowed to modify offset %d\n", offset );
2318 process_dword = value;
2321 ERR("Unknown offset %d\n", offset );
2327 /***********************************************************************
2328 * ExitProcess (KERNEL.466)
2330 void WINAPI ExitProcess16( WORD status )
2333 ReleaseThunkLock( &count );
2334 ExitProcess( status );
2338 /*********************************************************************
2339 * OpenProcess (KERNEL32.@)
2341 * Opens a handle to a process.
2344 * access [I] Desired access rights assigned to the returned handle.
2345 * inherit [I] Determines whether or not child processes will inherit the handle.
2346 * id [I] Process identifier of the process to get a handle to.
2349 * Success: Valid handle to the specified process.
2350 * Failure: NULL, check GetLastError().
2352 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2356 OBJECT_ATTRIBUTES attr;
2359 cid.UniqueProcess = ULongToHandle(id);
2360 cid.UniqueThread = 0; /* FIXME ? */
2362 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2363 attr.RootDirectory = NULL;
2364 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2365 attr.SecurityDescriptor = NULL;
2366 attr.SecurityQualityOfService = NULL;
2367 attr.ObjectName = NULL;
2369 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2371 status = NtOpenProcess(&handle, access, &attr, &cid);
2372 if (status != STATUS_SUCCESS)
2374 SetLastError( RtlNtStatusToDosError(status) );
2381 /*********************************************************************
2382 * MapProcessHandle (KERNEL.483)
2383 * GetProcessId (KERNEL32.@)
2385 * Gets the a unique identifier of a process.
2388 * hProcess [I] Handle to the process.
2392 * Failure: FALSE, check GetLastError().
2396 * The identifier is unique only on the machine and only until the process
2397 * exits (including system shutdown).
2399 DWORD WINAPI GetProcessId( HANDLE hProcess )
2402 PROCESS_BASIC_INFORMATION pbi;
2404 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2406 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2407 SetLastError( RtlNtStatusToDosError(status) );
2412 /*********************************************************************
2413 * CloseW32Handle (KERNEL.474)
2414 * CloseHandle (KERNEL32.@)
2419 * handle [I] Handle to close.
2423 * Failure: FALSE, check GetLastError().
2425 BOOL WINAPI CloseHandle( HANDLE handle )
2429 /* stdio handles need special treatment */
2430 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2431 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2432 (handle == (HANDLE)STD_ERROR_HANDLE))
2433 handle = GetStdHandle( HandleToULong(handle) );
2435 if (is_console_handle(handle))
2436 return CloseConsoleHandle(handle);
2438 status = NtClose( handle );
2439 if (status) SetLastError( RtlNtStatusToDosError(status) );
2444 /*********************************************************************
2445 * GetHandleInformation (KERNEL32.@)
2447 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2449 OBJECT_DATA_INFORMATION info;
2450 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2452 if (status) SetLastError( RtlNtStatusToDosError(status) );
2456 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2457 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2463 /*********************************************************************
2464 * SetHandleInformation (KERNEL32.@)
2466 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2468 OBJECT_DATA_INFORMATION info;
2471 /* if not setting both fields, retrieve current value first */
2472 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2473 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2475 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2477 SetLastError( RtlNtStatusToDosError(status) );
2481 if (mask & HANDLE_FLAG_INHERIT)
2482 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2483 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2484 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2486 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2487 if (status) SetLastError( RtlNtStatusToDosError(status) );
2492 /*********************************************************************
2493 * DuplicateHandle (KERNEL32.@)
2495 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2496 HANDLE dest_process, HANDLE *dest,
2497 DWORD access, BOOL inherit, DWORD options )
2501 if (is_console_handle(source))
2503 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2504 if (source_process != dest_process ||
2505 source_process != GetCurrentProcess())
2507 SetLastError(ERROR_INVALID_PARAMETER);
2510 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2511 return (*dest != INVALID_HANDLE_VALUE);
2513 status = NtDuplicateObject( source_process, source, dest_process, dest,
2514 access, inherit ? OBJ_INHERIT : 0, options );
2515 if (status) SetLastError( RtlNtStatusToDosError(status) );
2520 /***********************************************************************
2521 * ConvertToGlobalHandle (KERNEL.476)
2522 * ConvertToGlobalHandle (KERNEL32.@)
2524 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2526 HANDLE ret = INVALID_HANDLE_VALUE;
2527 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2528 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2533 /***********************************************************************
2534 * SetHandleContext (KERNEL32.@)
2536 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2538 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2539 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2540 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2545 /***********************************************************************
2546 * GetHandleContext (KERNEL32.@)
2548 DWORD WINAPI GetHandleContext(HANDLE hnd)
2550 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2551 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2552 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2557 /***********************************************************************
2558 * CreateSocketHandle (KERNEL32.@)
2560 HANDLE WINAPI CreateSocketHandle(void)
2562 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2563 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2564 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2565 return INVALID_HANDLE_VALUE;
2569 /***********************************************************************
2570 * SetPriorityClass (KERNEL32.@)
2572 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2575 PROCESS_PRIORITY_CLASS ppc;
2577 ppc.Foreground = FALSE;
2578 switch (priorityclass)
2580 case IDLE_PRIORITY_CLASS:
2581 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2582 case BELOW_NORMAL_PRIORITY_CLASS:
2583 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2584 case NORMAL_PRIORITY_CLASS:
2585 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2586 case ABOVE_NORMAL_PRIORITY_CLASS:
2587 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2588 case HIGH_PRIORITY_CLASS:
2589 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2590 case REALTIME_PRIORITY_CLASS:
2591 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2593 SetLastError(ERROR_INVALID_PARAMETER);
2597 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2600 if (status != STATUS_SUCCESS)
2602 SetLastError( RtlNtStatusToDosError(status) );
2609 /***********************************************************************
2610 * GetPriorityClass (KERNEL32.@)
2612 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2615 PROCESS_BASIC_INFORMATION pbi;
2617 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2619 if (status != STATUS_SUCCESS)
2621 SetLastError( RtlNtStatusToDosError(status) );
2624 switch (pbi.BasePriority)
2626 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2627 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2628 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2629 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2630 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2631 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2633 SetLastError( ERROR_INVALID_PARAMETER );
2638 /***********************************************************************
2639 * SetProcessAffinityMask (KERNEL32.@)
2641 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2645 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2646 &affmask, sizeof(DWORD_PTR));
2649 SetLastError( RtlNtStatusToDosError(status) );
2656 /**********************************************************************
2657 * GetProcessAffinityMask (KERNEL32.@)
2659 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2660 PDWORD_PTR lpProcessAffinityMask,
2661 PDWORD_PTR lpSystemAffinityMask )
2663 PROCESS_BASIC_INFORMATION pbi;
2666 status = NtQueryInformationProcess(hProcess,
2667 ProcessBasicInformation,
2668 &pbi, sizeof(pbi), NULL);
2671 SetLastError( RtlNtStatusToDosError(status) );
2674 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2675 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2680 /***********************************************************************
2681 * GetProcessVersion (KERNEL32.@)
2683 DWORD WINAPI GetProcessVersion( DWORD processid )
2685 IMAGE_NT_HEADERS *nt;
2687 if (processid && processid != GetCurrentProcessId())
2689 FIXME("should use ReadProcessMemory\n");
2692 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2693 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2694 nt->OptionalHeader.MinorSubsystemVersion);
2699 /***********************************************************************
2700 * SetProcessWorkingSetSize [KERNEL32.@]
2701 * Sets the min/max working set sizes for a specified process.
2704 * hProcess [I] Handle to the process of interest
2705 * minset [I] Specifies minimum working set size
2706 * maxset [I] Specifies maximum working set size
2712 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2715 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2716 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2717 /* Trim the working set to zero */
2718 /* Swap the process out of physical RAM */
2723 /***********************************************************************
2724 * GetProcessWorkingSetSize (KERNEL32.@)
2726 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2729 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2730 /* 32 MB working set size */
2731 if (minset) *minset = 32*1024*1024;
2732 if (maxset) *maxset = 32*1024*1024;
2737 /***********************************************************************
2738 * SetProcessShutdownParameters (KERNEL32.@)
2740 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2742 FIXME("(%08x, %08x): partial stub.\n", level, flags);
2743 shutdown_flags = flags;
2744 shutdown_priority = level;
2749 /***********************************************************************
2750 * GetProcessShutdownParameters (KERNEL32.@)
2753 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2755 *lpdwLevel = shutdown_priority;
2756 *lpdwFlags = shutdown_flags;
2761 /***********************************************************************
2762 * GetProcessPriorityBoost (KERNEL32.@)
2764 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2766 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2768 /* Report that no boost is present.. */
2769 *pDisablePriorityBoost = FALSE;
2774 /***********************************************************************
2775 * SetProcessPriorityBoost (KERNEL32.@)
2777 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2779 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2780 /* Say we can do it. I doubt the program will notice that we don't. */
2785 /***********************************************************************
2786 * ReadProcessMemory (KERNEL32.@)
2788 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2789 SIZE_T *bytes_read )
2791 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2792 if (status) SetLastError( RtlNtStatusToDosError(status) );
2797 /***********************************************************************
2798 * WriteProcessMemory (KERNEL32.@)
2800 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2801 SIZE_T *bytes_written )
2803 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2804 if (status) SetLastError( RtlNtStatusToDosError(status) );
2809 /****************************************************************************
2810 * FlushInstructionCache (KERNEL32.@)
2812 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2815 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2816 if (status) SetLastError( RtlNtStatusToDosError(status) );
2821 /******************************************************************
2822 * GetProcessIoCounters (KERNEL32.@)
2824 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2828 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2829 ioc, sizeof(*ioc), NULL);
2830 if (status) SetLastError( RtlNtStatusToDosError(status) );
2834 /******************************************************************
2835 * GetProcessHandleCount (KERNEL32.@)
2837 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
2841 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
2842 cnt, sizeof(*cnt), NULL);
2843 if (status) SetLastError( RtlNtStatusToDosError(status) );
2847 /***********************************************************************
2848 * ProcessIdToSessionId (KERNEL32.@)
2849 * This function is available on Terminal Server 4SP4 and Windows 2000
2851 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2853 /* According to MSDN, if the calling process is not in a terminal
2854 * services environment, then the sessionid returned is zero.
2861 /***********************************************************************
2862 * RegisterServiceProcess (KERNEL.491)
2863 * RegisterServiceProcess (KERNEL32.@)
2865 * A service process calls this function to ensure that it continues to run
2866 * even after a user logged off.
2868 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2870 /* I don't think that Wine needs to do anything in this function */
2871 return 1; /* success */
2875 /**********************************************************************
2876 * IsWow64Process (KERNEL32.@)
2878 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
2883 status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );
2885 if (status != STATUS_SUCCESS)
2887 SetLastError( RtlNtStatusToDosError( status ) );
2890 *Wow64Process = (pbi != 0);
2895 /***********************************************************************
2896 * GetCurrentProcess (KERNEL32.@)
2898 * Get a handle to the current process.
2904 * A handle representing the current process.
2906 #undef GetCurrentProcess
2907 HANDLE WINAPI GetCurrentProcess(void)
2909 return (HANDLE)0xffffffff;
2912 /***********************************************************************
2913 * CmdBatNotification (KERNEL32.@)
2915 * Notifies the system that a batch file has started or finished.
2918 * bBatchRunning [I] TRUE if a batch file has started or
2919 * FALSE if a batch file has finished executing.
2924 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
2926 FIXME("%d\n", bBatchRunning);
2931 /***********************************************************************
2932 * RegisterApplicationRestart (KERNEL32.@)
2934 HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
2936 FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);