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 #ifdef HAVE_VALGRIND_MEMCHECK_H
56 #include <valgrind/memcheck.h>
59 WINE_DEFAULT_DEBUG_CHANNEL(process);
60 WINE_DECLARE_DEBUG_CHANNEL(file);
61 WINE_DECLARE_DEBUG_CHANNEL(relay);
71 static UINT process_error_mode;
73 static DWORD shutdown_flags = 0;
74 static DWORD shutdown_priority = 0x280;
75 static DWORD process_dword;
77 HMODULE kernel32_handle = 0;
79 const WCHAR *DIR_Windows = NULL;
80 const WCHAR *DIR_System = NULL;
83 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
84 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
85 #define PDB32_DOS_PROC 0x0010 /* Dos process */
86 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
87 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
88 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
90 static const WCHAR comW[] = {'.','c','o','m',0};
91 static const WCHAR batW[] = {'.','b','a','t',0};
92 static const WCHAR cmdW[] = {'.','c','m','d',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 static inline 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 static inline 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 -= sizeof(WCHAR); /* 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 );
421 /***********************************************************************
422 * set_additional_environment
424 * Set some additional environment variables not specified in the registry.
426 static void set_additional_environment(void)
428 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
429 const char *name = wine_get_user_name();
430 DWORD len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
433 LPWSTR nameW = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
434 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, nameW, len );
435 SetEnvironmentVariableW( usernameW, nameW );
436 HeapFree( GetProcessHeap(), 0, nameW );
440 /***********************************************************************
443 * Set the Wine library Unicode argv global variables.
445 static void set_library_wargv( char **argv )
453 for (argc = 0; argv[argc]; argc++)
454 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
456 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
457 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
458 p = (WCHAR *)(wargv + argc + 1);
459 for (argc = 0; argv[argc]; argc++)
461 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
468 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
470 for (argc = 0; wargv[argc]; argc++)
471 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
473 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
474 q = (char *)(argv + argc + 1);
475 for (argc = 0; wargv[argc]; argc++)
477 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
484 __wine_main_argc = argc;
485 __wine_main_argv = argv;
486 __wine_main_wargv = wargv;
490 /***********************************************************************
493 * Build the command line of a process from the argv array.
495 * Note that it does NOT necessarily include the file name.
496 * Sometimes we don't even have any command line options at all.
498 * We must quote and escape characters so that the argv array can be rebuilt
499 * from the command line:
500 * - spaces and tabs must be quoted
502 * - quotes must be escaped
504 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
505 * resulting in an odd number of '\' followed by a '"'
508 * - '\'s that are not followed by a '"' can be left as is
512 static BOOL build_command_line( WCHAR **argv )
517 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
519 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
522 for (arg = argv; *arg; arg++)
524 int has_space,bcount;
530 if( !*a ) has_space=1;
535 if (*a==' ' || *a=='\t') {
537 } else if (*a=='"') {
538 /* doubling of '\' preceding a '"',
539 * plus escaping of said '"'
547 len+=(a-*arg)+1 /* for the separating space */;
549 len+=2; /* for the quotes */
552 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
555 p = rupp->CommandLine.Buffer;
556 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
557 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
558 for (arg = argv; *arg; arg++)
560 int has_space,has_quote;
563 /* Check for quotes and spaces in this argument */
564 has_space=has_quote=0;
566 if( !*a ) has_space=1;
568 if (*a==' ' || *a=='\t') {
572 } else if (*a=='"') {
580 /* Now transfer it to the command line */
597 /* Double all the '\\' preceding this '"', plus one */
598 for (i=0;i<=bcount;i++)
610 while ((*p=*x++)) p++;
616 if (p > rupp->CommandLine.Buffer)
617 p--; /* remove last space */
624 /***********************************************************************
625 * init_current_directory
627 * Initialize the current directory from the Unix cwd or the parent info.
629 static void init_current_directory( CURDIR *cur_dir )
631 UNICODE_STRING dir_str;
635 /* if we received a cur dir from the parent, try this first */
637 if (cur_dir->DosPath.Length)
639 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
642 /* now try to get it from the Unix cwd */
644 for (size = 256; ; size *= 2)
646 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
647 if (getcwd( cwd, size )) break;
648 HeapFree( GetProcessHeap(), 0, cwd );
649 if (errno == ERANGE) continue;
657 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
658 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
660 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
661 RtlInitUnicodeString( &dir_str, dirW );
662 RtlSetCurrentDirectory_U( &dir_str );
663 RtlFreeUnicodeString( &dir_str );
667 if (!cur_dir->DosPath.Length) /* still not initialized */
669 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
670 "starting in the Windows directory.\n", cwd ? cwd : "" );
671 RtlInitUnicodeString( &dir_str, DIR_Windows );
672 RtlSetCurrentDirectory_U( &dir_str );
674 HeapFree( GetProcessHeap(), 0, cwd );
677 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
678 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
682 /***********************************************************************
685 * Initialize the windows and system directories from the environment.
687 static void init_windows_dirs(void)
689 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
691 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
692 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
693 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
694 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
699 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
701 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
702 GetEnvironmentVariableW( windirW, buffer, len );
703 DIR_Windows = buffer;
705 else DIR_Windows = default_windirW;
707 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
709 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
710 GetEnvironmentVariableW( winsysdirW, buffer, len );
715 len = strlenW( DIR_Windows );
716 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
717 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
718 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
722 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
723 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
724 debugstr_w(DIR_Windows) );
725 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
726 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
727 debugstr_w(DIR_System) );
729 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
730 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
732 /* set the directories in ntdll too */
733 __wine_init_windows_dir( DIR_Windows, DIR_System );
737 /***********************************************************************
740 * Main process initialisation code
742 static BOOL process_init(void)
744 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
745 PEB *peb = NtCurrentTeb()->Peb;
746 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
753 kernel32_handle = GetModuleHandleW(kernel32W);
757 if (!params->Environment)
759 /* Copy the parent environment */
760 if (!build_initial_environment( __wine_main_environ )) return FALSE;
762 /* convert old configuration to new format */
763 convert_old_config();
765 set_registry_environment();
766 set_additional_environment();
770 init_current_directory( ¶ms->CurrentDirectory );
776 /***********************************************************************
779 * Allocate the stack of new process.
781 static void *init_stack(void)
784 SIZE_T stack_size, page_size = getpagesize();
785 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
787 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
788 stack_size += page_size; /* for the guard page */
789 stack_size = (stack_size + 0xffff) & ~0xffff; /* round to 64K boundary */
790 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
792 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_READWRITE )))
794 ERR( "failed to allocate main process stack\n" );
798 /* note: limit is lower than base since the stack grows down */
799 NtCurrentTeb()->DeallocationStack = base;
800 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
801 NtCurrentTeb()->Tib.StackLimit = (char *)base + page_size;
803 #ifdef VALGRIND_STACK_REGISTER
804 /* no need to de-register the stack as it's the one of the main thread */
805 VALGRIND_STACK_REGISTER(NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase);
808 /* setup guard page */
809 VirtualProtect( base, page_size, PAGE_NOACCESS, NULL );
810 return NtCurrentTeb()->Tib.StackBase;
814 /***********************************************************************
817 * Startup routine of a new process. Runs on the new process stack.
819 static void start_process( void *arg )
823 PEB *peb = NtCurrentTeb()->Peb;
824 IMAGE_NT_HEADERS *nt;
825 LPTHREAD_START_ROUTINE entry;
827 LdrInitializeThunk( 0, 0, 0, 0 );
829 nt = RtlImageNtHeader( peb->ImageBaseAddress );
830 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
831 nt->OptionalHeader.AddressOfEntryPoint);
834 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
835 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
837 SetLastError( 0 ); /* clear error code */
838 if (peb->BeingDebugged) DbgBreakPoint();
839 ExitThread( entry( peb ) );
841 __EXCEPT(UnhandledExceptionFilter)
843 TerminateThread( GetCurrentThread(), GetExceptionCode() );
849 /***********************************************************************
852 * Change the process name in the ps output.
854 static void set_process_name( int argc, char *argv[] )
858 char *p, *prctl_name = argv[1];
859 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
862 # define PR_SET_NAME 15
865 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
866 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
868 if (prctl( PR_SET_NAME, prctl_name ) != -1)
870 offset = argv[1] - argv[0];
871 memmove( argv[1] - offset, argv[1], end - argv[1] );
872 memset( end - offset, 0, offset );
873 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
877 #endif /* HAVE_PRCTL */
880 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
885 /***********************************************************************
888 * Wine initialisation: load and start the main exe file.
890 void __wine_kernel_init(void)
892 static const WCHAR dotW[] = {'.',0};
893 static const WCHAR exeW[] = {'.','e','x','e',0};
895 WCHAR *p, main_exe_name[MAX_PATH+1];
896 PEB *peb = NtCurrentTeb()->Peb;
898 /* Initialize everything */
899 if (!process_init()) exit(1);
900 set_process_name( __wine_main_argc, __wine_main_argv );
901 set_library_wargv( __wine_main_argv );
903 if (peb->ProcessParameters->ImagePathName.Buffer)
905 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
909 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
910 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
912 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
913 ExitProcess( GetLastError() );
915 if (!build_command_line( __wine_main_wargv )) goto error;
918 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
919 p = strrchrW( main_exe_name, '.' );
920 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
922 TRACE( "starting process name=%s argv[0]=%s\n",
923 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
925 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
926 MODULE_get_dll_load_path(main_exe_name) );
928 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
931 DWORD error = GetLastError();
933 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
934 if (error == ERROR_BAD_EXE_FORMAT ||
935 error == ERROR_INVALID_ADDRESS ||
936 error == ERROR_NOT_ENOUGH_MEMORY)
938 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
939 /* if we get back here, it failed */
942 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
943 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
944 ExitProcess( error );
947 /* switch to the new stack */
948 wine_switch_to_stack( start_process, NULL, init_stack() );
951 ExitProcess( GetLastError() );
955 /***********************************************************************
958 * Build an argv array from a command-line.
959 * 'reserved' is the number of args to reserve before the first one.
961 static char **build_argv( const WCHAR *cmdlineW, int reserved )
965 char *arg,*s,*d,*cmdline;
966 int in_quotes,bcount,len;
968 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
969 if (!(cmdline = malloc(len))) return NULL;
970 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
977 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
980 /* skip the remaining spaces */
981 while (*s==' ' || *s=='\t') {
988 } else if (*s=='\\') {
989 /* '\', count them */
991 } else if ((*s=='"') && ((bcount & 1)==0)) {
993 in_quotes=!in_quotes;
996 /* a regular character */
1001 argv=malloc(argc*sizeof(*argv));
1010 if ((*s==' ' || *s=='\t') && !in_quotes) {
1011 /* Close the argument and copy it */
1015 /* skip the remaining spaces */
1018 } while (*s==' ' || *s=='\t');
1020 /* Start with a new argument */
1023 } else if (*s=='\\') {
1027 } else if (*s=='"') {
1029 if ((bcount & 1)==0) {
1030 /* Preceded by an even number of '\', this is half that
1031 * number of '\', plus a '"' which we discard.
1035 in_quotes=!in_quotes;
1037 /* Preceded by an odd number of '\', this is half that
1038 * number of '\' followed by a '"'
1046 /* a regular character */
1061 /***********************************************************************
1064 * Allocate an environment string; helper for build_envp
1066 static char *alloc_env_string( const char *name, const char *value )
1068 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1069 strcpy( ret, name );
1070 strcat( ret, value );
1074 /***********************************************************************
1077 * Build the environment of a new child process.
1079 static char **build_envp( const WCHAR *envW )
1084 int count = 0, length;
1086 for (end = envW; *end; count++) end += strlenW(end) + 1;
1088 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1089 if (!(env = malloc( length ))) return NULL;
1090 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1094 if ((envp = malloc( count * sizeof(*envp) )))
1096 char **envptr = envp;
1098 /* some variables must not be modified, so we get them directly from the unix env */
1099 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1100 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1101 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1102 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1103 /* now put the Windows environment strings */
1104 for (p = env; *p; p += strlen(p) + 1)
1106 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1107 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1108 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1109 if (is_special_env_var( p )) /* prefix it with "WINE" */
1110 *envptr++ = alloc_env_string( "WINE", p );
1120 /***********************************************************************
1123 * Fork and exec a new Unix binary, checking for errors.
1125 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1126 const WCHAR *env, const char *newdir, DWORD flags )
1131 if (!env) env = GetEnvironmentStringsW();
1135 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1138 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1139 if (!(pid = fork())) /* child */
1141 char **argv = build_argv( cmdline, 0 );
1142 char **envp = build_envp( env );
1145 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)) setsid();
1147 /* Reset signals that we previously set to SIG_IGN */
1148 signal( SIGPIPE, SIG_DFL );
1149 signal( SIGCHLD, SIG_DFL );
1151 if (newdir) chdir(newdir);
1153 if (argv && envp) execve( filename, argv, envp );
1155 write( fd[1], &err, sizeof(err) );
1159 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1164 if (pid == -1) FILE_SetDosError();
1170 /***********************************************************************
1171 * create_user_params
1173 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1174 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1175 const STARTUPINFOW *startup )
1177 RTL_USER_PROCESS_PARAMETERS *params;
1178 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1180 WCHAR buffer[MAX_PATH];
1182 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1183 lstrcpynW( buffer, filename, MAX_PATH );
1184 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1185 lstrcpynW( buffer, filename, MAX_PATH );
1186 RtlInitUnicodeString( &image_str, buffer );
1188 RtlInitUnicodeString( &cmdline_str, cmdline );
1189 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1190 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1191 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1192 if (startup->lpReserved2 && startup->cbReserved2)
1195 runtime.MaximumLength = startup->cbReserved2;
1196 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1199 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1200 cur_dir ? &curdir_str : NULL,
1202 startup->lpTitle ? &title : NULL,
1203 startup->lpDesktop ? &desktop : NULL,
1205 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1206 if (status != STATUS_SUCCESS)
1208 SetLastError( RtlNtStatusToDosError(status) );
1212 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1213 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1215 if (startup->dwFlags & STARTF_USESTDHANDLES)
1217 params->hStdInput = startup->hStdInput;
1218 params->hStdOutput = startup->hStdOutput;
1219 params->hStdError = startup->hStdError;
1223 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1224 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1225 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1227 params->dwX = startup->dwX;
1228 params->dwY = startup->dwY;
1229 params->dwXSize = startup->dwXSize;
1230 params->dwYSize = startup->dwYSize;
1231 params->dwXCountChars = startup->dwXCountChars;
1232 params->dwYCountChars = startup->dwYCountChars;
1233 params->dwFillAttribute = startup->dwFillAttribute;
1234 params->dwFlags = startup->dwFlags;
1235 params->wShowWindow = startup->wShowWindow;
1240 /***********************************************************************
1243 * Create a new process. If hFile is a valid handle we have an exe
1244 * file, otherwise it is a Winelib app.
1246 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1247 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1248 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1249 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1250 void *res_start, void *res_end, int exec_only )
1252 BOOL ret, success = FALSE;
1253 HANDLE process_info;
1255 char *winedebug = NULL;
1256 RTL_USER_PROCESS_PARAMETERS *params;
1261 if (!env) RtlAcquirePebLock();
1263 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1265 if (!env) RtlReleasePebLock();
1268 env_end = params->Environment;
1271 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1272 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1274 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1275 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1276 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1278 env_end += strlenW(env_end) + 1;
1282 /* create the socket for the new process */
1284 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1286 if (!env) RtlReleasePebLock();
1287 HeapFree( GetProcessHeap(), 0, winedebug );
1288 RtlDestroyProcessParameters( params );
1289 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1292 wine_server_send_fd( socketfd[1] );
1293 close( socketfd[1] );
1295 /* create the process on the server side */
1297 SERVER_START_REQ( new_process )
1299 req->inherit_all = inherit;
1300 req->create_flags = flags;
1301 req->socket_fd = socketfd[1];
1302 req->exe_file = hFile;
1303 req->process_access = PROCESS_ALL_ACCESS;
1304 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1305 req->thread_access = THREAD_ALL_ACCESS;
1306 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1307 req->hstdin = params->hStdInput;
1308 req->hstdout = params->hStdOutput;
1309 req->hstderr = params->hStdError;
1311 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1313 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1314 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1315 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1316 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1320 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1321 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1322 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1325 wine_server_add_data( req, params, params->Size );
1326 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1327 if ((ret = !wine_server_call_err( req )))
1329 info->dwProcessId = (DWORD)reply->pid;
1330 info->dwThreadId = (DWORD)reply->tid;
1331 info->hProcess = reply->phandle;
1332 info->hThread = reply->thandle;
1334 process_info = reply->info;
1338 if (!env) RtlReleasePebLock();
1339 RtlDestroyProcessParameters( params );
1342 close( socketfd[0] );
1343 HeapFree( GetProcessHeap(), 0, winedebug );
1347 /* create the child process */
1349 if (exec_only || !(pid = fork())) /* child */
1351 char preloader_reserve[64], socket_env[64];
1352 char **argv = build_argv( cmd_line, 1 );
1354 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)) setsid();
1356 /* Reset signals that we previously set to SIG_IGN */
1357 signal( SIGPIPE, SIG_DFL );
1358 signal( SIGCHLD, SIG_DFL );
1360 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1361 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1362 (unsigned long)res_start, (unsigned long)res_end );
1364 putenv( preloader_reserve );
1365 putenv( socket_env );
1366 if (winedebug) putenv( winedebug );
1367 if (unixdir) chdir(unixdir);
1369 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1373 /* this is the parent */
1375 close( socketfd[0] );
1376 HeapFree( GetProcessHeap(), 0, winedebug );
1383 /* wait for the new process info to be ready */
1385 WaitForSingleObject( process_info, INFINITE );
1386 SERVER_START_REQ( get_new_process_info )
1388 req->info = process_info;
1389 wine_server_call( req );
1390 success = reply->success;
1391 err = reply->exit_code;
1397 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1400 CloseHandle( process_info );
1404 CloseHandle( process_info );
1405 CloseHandle( info->hProcess );
1406 CloseHandle( info->hThread );
1407 info->hProcess = info->hThread = 0;
1408 info->dwProcessId = info->dwThreadId = 0;
1413 /***********************************************************************
1414 * create_vdm_process
1416 * Create a new VDM process for a 16-bit or DOS application.
1418 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1419 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1420 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1421 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1423 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1426 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1427 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1431 SetLastError( ERROR_OUTOFMEMORY );
1434 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1435 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1436 flags, startup, info, unixdir, NULL, NULL, exec_only );
1437 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1442 /***********************************************************************
1443 * create_cmd_process
1445 * Create a new cmd shell process for a .BAT file.
1447 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1448 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1449 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1450 LPPROCESS_INFORMATION info )
1453 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1454 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1455 WCHAR comspec[MAX_PATH];
1459 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1461 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1462 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1465 strcpyW( newcmdline, comspec );
1466 strcatW( newcmdline, slashcW );
1467 strcatW( newcmdline, cmd_line );
1468 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1469 flags, env, cur_dir, startup, info );
1470 HeapFree( GetProcessHeap(), 0, newcmdline );
1475 /*************************************************************************
1478 * Helper for CreateProcess: retrieve the file name to load from the
1479 * app name and command line. Store the file name in buffer, and
1480 * return a possibly modified command line.
1481 * Also returns a handle to the opened file if it's a Windows binary.
1483 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1484 int buflen, HANDLE *handle )
1486 static const WCHAR quotesW[] = {'"','%','s','"',0};
1488 WCHAR *name, *pos, *ret = NULL;
1492 /* if we have an app name, everything is easy */
1496 /* use the unmodified app name as file name */
1497 lstrcpynW( buffer, appname, buflen );
1498 *handle = open_exe_file( buffer );
1499 if (!(ret = cmdline) || !cmdline[0])
1501 /* no command-line, create one */
1502 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1503 sprintfW( ret, quotesW, appname );
1510 SetLastError( ERROR_INVALID_PARAMETER );
1514 /* first check for a quoted file name */
1516 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1518 int len = p - cmdline - 1;
1519 /* extract the quoted portion as file name */
1520 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1521 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1524 if (find_exe_file( name, buffer, buflen, handle ))
1525 ret = cmdline; /* no change necessary */
1529 /* now try the command-line word by word */
1531 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1539 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1541 if (find_exe_file( name, buffer, buflen, handle ))
1546 if (*p) got_space = TRUE;
1549 if (ret && got_space) /* now build a new command-line with quotes */
1551 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1553 sprintfW( ret, quotesW, name );
1558 HeapFree( GetProcessHeap(), 0, name );
1563 /**********************************************************************
1564 * CreateProcessA (KERNEL32.@)
1566 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1567 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1568 DWORD flags, LPVOID env, LPCSTR cur_dir,
1569 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1572 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1573 UNICODE_STRING desktopW, titleW;
1576 desktopW.Buffer = NULL;
1577 titleW.Buffer = NULL;
1578 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1579 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1580 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1582 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1583 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1585 memcpy( &infoW, startup_info, sizeof(infoW) );
1586 infoW.lpDesktop = desktopW.Buffer;
1587 infoW.lpTitle = titleW.Buffer;
1589 if (startup_info->lpReserved)
1590 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1591 debugstr_a(startup_info->lpReserved));
1593 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1594 inherit, flags, env, cur_dirW, &infoW, info );
1596 HeapFree( GetProcessHeap(), 0, app_nameW );
1597 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1598 HeapFree( GetProcessHeap(), 0, cur_dirW );
1599 RtlFreeUnicodeString( &desktopW );
1600 RtlFreeUnicodeString( &titleW );
1605 /**********************************************************************
1606 * CreateProcessW (KERNEL32.@)
1608 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1609 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1610 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1611 LPPROCESS_INFORMATION info )
1615 char *unixdir = NULL;
1616 WCHAR name[MAX_PATH];
1617 WCHAR *tidy_cmdline, *p, *envW = env;
1618 void *res_start, *res_end;
1620 /* Process the AppName and/or CmdLine to get module name and path */
1622 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1624 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1626 if (hFile == INVALID_HANDLE_VALUE) goto done;
1628 /* Warn if unsupported features are used */
1630 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1631 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1632 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1633 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1634 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1638 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1640 SetLastError(ERROR_DIRECTORY);
1646 WCHAR buf[MAX_PATH];
1647 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1650 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1655 while (*p) p += strlen(p) + 1;
1656 p++; /* final null */
1657 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1658 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1659 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1660 flags |= CREATE_UNICODE_ENVIRONMENT;
1663 info->hThread = info->hProcess = 0;
1664 info->dwProcessId = info->dwThreadId = 0;
1666 /* Determine executable type */
1668 if (!hFile) /* builtin exe */
1670 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1671 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1672 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1676 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1679 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1680 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1681 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1686 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1687 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1688 inherit, flags, startup_info, info, unixdir, FALSE );
1691 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1692 SetLastError( ERROR_BAD_EXE_FORMAT );
1694 case BINARY_UNIX_LIB:
1695 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1696 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1697 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1699 case BINARY_UNKNOWN:
1700 /* check for .com or .bat extension */
1701 if ((p = strrchrW( name, '.' )))
1703 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1705 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1706 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1707 inherit, flags, startup_info, info, unixdir, FALSE );
1710 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1712 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1713 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1714 inherit, flags, startup_info, info );
1719 case BINARY_UNIX_EXE:
1721 /* unknown file, try as unix executable */
1724 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1726 if ((unix_name = wine_get_unix_file_name( name )))
1728 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags ) != -1);
1729 HeapFree( GetProcessHeap(), 0, unix_name );
1734 CloseHandle( hFile );
1737 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1738 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1739 HeapFree( GetProcessHeap(), 0, unixdir );
1744 /**********************************************************************
1747 static void exec_process( LPCWSTR name )
1751 void *res_start, *res_end;
1752 STARTUPINFOW startup_info;
1753 PROCESS_INFORMATION info;
1755 hFile = open_exe_file( name );
1756 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
1758 memset( &startup_info, 0, sizeof(startup_info) );
1759 startup_info.cb = sizeof(startup_info);
1761 /* Determine executable type */
1763 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1766 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1767 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1768 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
1770 case BINARY_UNIX_LIB:
1771 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1772 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1773 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
1775 case BINARY_UNKNOWN:
1776 /* check for .com or .pif extension */
1777 if (!(p = strrchrW( name, '.' ))) break;
1778 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
1783 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1784 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
1785 FALSE, 0, &startup_info, &info, NULL, TRUE );
1790 CloseHandle( hFile );
1794 /***********************************************************************
1797 * Wrapper to call WaitForInputIdle USER function
1799 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1801 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1803 HMODULE mod = GetModuleHandleA( "user32.dll" );
1806 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1807 if (ptr) return ptr( process, timeout );
1813 /***********************************************************************
1814 * WinExec (KERNEL32.@)
1816 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1818 PROCESS_INFORMATION info;
1819 STARTUPINFOA startup;
1823 memset( &startup, 0, sizeof(startup) );
1824 startup.cb = sizeof(startup);
1825 startup.dwFlags = STARTF_USESHOWWINDOW;
1826 startup.wShowWindow = nCmdShow;
1828 /* cmdline needs to be writable for CreateProcess */
1829 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1830 strcpy( cmdline, lpCmdLine );
1832 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1833 0, NULL, NULL, &startup, &info ))
1835 /* Give 30 seconds to the app to come up */
1836 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1837 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1839 /* Close off the handles */
1840 CloseHandle( info.hThread );
1841 CloseHandle( info.hProcess );
1843 else if ((ret = GetLastError()) >= 32)
1845 FIXME("Strange error set by CreateProcess: %d\n", ret );
1848 HeapFree( GetProcessHeap(), 0, cmdline );
1853 /**********************************************************************
1854 * LoadModule (KERNEL32.@)
1856 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1858 LOADPARMS32 *params = paramBlock;
1859 PROCESS_INFORMATION info;
1860 STARTUPINFOA startup;
1861 HINSTANCE hInstance;
1863 char filename[MAX_PATH];
1866 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1868 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1869 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1870 return ULongToHandle(GetLastError());
1872 len = (BYTE)params->lpCmdLine[0];
1873 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1874 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1876 strcpy( cmdline, filename );
1877 p = cmdline + strlen(cmdline);
1879 memcpy( p, params->lpCmdLine + 1, len );
1882 memset( &startup, 0, sizeof(startup) );
1883 startup.cb = sizeof(startup);
1884 if (params->lpCmdShow)
1886 startup.dwFlags = STARTF_USESHOWWINDOW;
1887 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1890 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1891 params->lpEnvAddress, NULL, &startup, &info ))
1893 /* Give 30 seconds to the app to come up */
1894 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1895 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
1896 hInstance = (HINSTANCE)33;
1897 /* Close off the handles */
1898 CloseHandle( info.hThread );
1899 CloseHandle( info.hProcess );
1901 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
1903 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1904 hInstance = (HINSTANCE)11;
1907 HeapFree( GetProcessHeap(), 0, cmdline );
1912 /******************************************************************************
1913 * TerminateProcess (KERNEL32.@)
1915 * Terminates a process.
1918 * handle [I] Process to terminate.
1919 * exit_code [I] Exit code.
1923 * Failure: FALSE, check GetLastError().
1925 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1927 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1928 if (status) SetLastError( RtlNtStatusToDosError(status) );
1933 /***********************************************************************
1934 * ExitProcess (KERNEL32.@)
1936 * Exits the current process.
1939 * status [I] Status code to exit with.
1944 void WINAPI ExitProcess( DWORD status )
1946 LdrShutdownProcess();
1947 NtTerminateProcess(GetCurrentProcess(), status);
1952 /***********************************************************************
1953 * GetExitCodeProcess [KERNEL32.@]
1955 * Gets termination status of specified process.
1958 * hProcess [in] Handle to the process.
1959 * lpExitCode [out] Address to receive termination status.
1965 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
1968 PROCESS_BASIC_INFORMATION pbi;
1970 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
1972 if (status == STATUS_SUCCESS)
1974 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
1977 SetLastError( RtlNtStatusToDosError(status) );
1982 /***********************************************************************
1983 * SetErrorMode (KERNEL32.@)
1985 UINT WINAPI SetErrorMode( UINT mode )
1987 UINT old = process_error_mode;
1988 process_error_mode = mode;
1993 /**********************************************************************
1994 * TlsAlloc [KERNEL32.@]
1996 * Allocates a thread local storage index.
1999 * Success: TLS index.
2000 * Failure: 0xFFFFFFFF
2002 DWORD WINAPI TlsAlloc( void )
2005 PEB * const peb = NtCurrentTeb()->Peb;
2007 RtlAcquirePebLock();
2008 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2009 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2012 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2015 if (!NtCurrentTeb()->TlsExpansionSlots &&
2016 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2017 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2019 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2021 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2025 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2026 index += TLS_MINIMUM_AVAILABLE;
2029 else SetLastError( ERROR_NO_MORE_ITEMS );
2031 RtlReleasePebLock();
2036 /**********************************************************************
2037 * TlsFree [KERNEL32.@]
2039 * Releases a thread local storage index, making it available for reuse.
2042 * index [in] TLS index to free.
2048 BOOL WINAPI TlsFree( DWORD index )
2052 RtlAcquirePebLock();
2053 if (index >= TLS_MINIMUM_AVAILABLE)
2055 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2056 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2060 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2061 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2063 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2064 else SetLastError( ERROR_INVALID_PARAMETER );
2065 RtlReleasePebLock();
2070 /**********************************************************************
2071 * TlsGetValue [KERNEL32.@]
2073 * Gets value in a thread's TLS slot.
2076 * index [in] TLS index to retrieve value for.
2079 * Success: Value stored in calling thread's TLS slot for index.
2080 * Failure: 0 and GetLastError() returns NO_ERROR.
2082 LPVOID WINAPI TlsGetValue( DWORD index )
2086 if (index < TLS_MINIMUM_AVAILABLE)
2088 ret = NtCurrentTeb()->TlsSlots[index];
2092 index -= TLS_MINIMUM_AVAILABLE;
2093 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2095 SetLastError( ERROR_INVALID_PARAMETER );
2098 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2099 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2101 SetLastError( ERROR_SUCCESS );
2106 /**********************************************************************
2107 * TlsSetValue [KERNEL32.@]
2109 * Stores a value in the thread's TLS slot.
2112 * index [in] TLS index to set value for.
2113 * value [in] Value to be stored.
2119 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2121 if (index < TLS_MINIMUM_AVAILABLE)
2123 NtCurrentTeb()->TlsSlots[index] = value;
2127 index -= TLS_MINIMUM_AVAILABLE;
2128 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2130 SetLastError( ERROR_INVALID_PARAMETER );
2133 if (!NtCurrentTeb()->TlsExpansionSlots &&
2134 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2135 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2137 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2140 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2146 /***********************************************************************
2147 * GetProcessFlags (KERNEL32.@)
2149 DWORD WINAPI GetProcessFlags( DWORD processid )
2151 IMAGE_NT_HEADERS *nt;
2154 if (processid && processid != GetCurrentProcessId()) return 0;
2156 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2158 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2159 flags |= PDB32_CONSOLE_PROC;
2161 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2162 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2167 /***********************************************************************
2168 * GetProcessDword (KERNEL.485)
2169 * GetProcessDword (KERNEL32.18)
2170 * 'Of course you cannot directly access Windows internal structures'
2172 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2177 TRACE("(%d, %d)\n", dwProcessID, offset );
2179 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2181 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2187 case GPD_APP_COMPAT_FLAGS:
2188 return GetAppCompatFlags16(0);
2189 case GPD_LOAD_DONE_EVENT:
2191 case GPD_HINSTANCE16:
2192 return GetTaskDS16();
2193 case GPD_WINDOWS_VERSION:
2194 return GetExeVersion16();
2196 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2198 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2199 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2200 GetStartupInfoW(&siw);
2201 return HandleToULong(siw.hStdOutput);
2202 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2203 GetStartupInfoW(&siw);
2204 return HandleToULong(siw.hStdInput);
2205 case GPD_STARTF_SHOWWINDOW:
2206 GetStartupInfoW(&siw);
2207 return siw.wShowWindow;
2208 case GPD_STARTF_SIZE:
2209 GetStartupInfoW(&siw);
2211 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2213 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2214 return MAKELONG( x, y );
2215 case GPD_STARTF_POSITION:
2216 GetStartupInfoW(&siw);
2218 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2220 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2221 return MAKELONG( x, y );
2222 case GPD_STARTF_FLAGS:
2223 GetStartupInfoW(&siw);
2228 return GetProcessFlags(0);
2230 return process_dword;
2232 ERR("Unknown offset %d\n", offset );
2237 /***********************************************************************
2238 * SetProcessDword (KERNEL.484)
2239 * 'Of course you cannot directly access Windows internal structures'
2241 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2243 TRACE("(%d, %d)\n", dwProcessID, offset );
2245 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2247 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2253 case GPD_APP_COMPAT_FLAGS:
2254 case GPD_LOAD_DONE_EVENT:
2255 case GPD_HINSTANCE16:
2256 case GPD_WINDOWS_VERSION:
2259 case GPD_STARTF_SHELLDATA:
2260 case GPD_STARTF_HOTKEY:
2261 case GPD_STARTF_SHOWWINDOW:
2262 case GPD_STARTF_SIZE:
2263 case GPD_STARTF_POSITION:
2264 case GPD_STARTF_FLAGS:
2267 ERR("Not allowed to modify offset %d\n", offset );
2270 process_dword = value;
2273 ERR("Unknown offset %d\n", offset );
2279 /***********************************************************************
2280 * ExitProcess (KERNEL.466)
2282 void WINAPI ExitProcess16( WORD status )
2285 ReleaseThunkLock( &count );
2286 ExitProcess( status );
2290 /*********************************************************************
2291 * OpenProcess (KERNEL32.@)
2293 * Opens a handle to a process.
2296 * access [I] Desired access rights assigned to the returned handle.
2297 * inherit [I] Determines whether or not child processes will inherit the handle.
2298 * id [I] Process identifier of the process to get a handle to.
2301 * Success: Valid handle to the specified process.
2302 * Failure: NULL, check GetLastError().
2304 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2308 OBJECT_ATTRIBUTES attr;
2311 cid.UniqueProcess = ULongToHandle(id);
2312 cid.UniqueThread = 0; /* FIXME ? */
2314 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2315 attr.RootDirectory = NULL;
2316 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2317 attr.SecurityDescriptor = NULL;
2318 attr.SecurityQualityOfService = NULL;
2319 attr.ObjectName = NULL;
2321 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2323 status = NtOpenProcess(&handle, access, &attr, &cid);
2324 if (status != STATUS_SUCCESS)
2326 SetLastError( RtlNtStatusToDosError(status) );
2333 /*********************************************************************
2334 * MapProcessHandle (KERNEL.483)
2335 * GetProcessId (KERNEL32.@)
2337 * Gets the a unique identifier of a process.
2340 * hProcess [I] Handle to the process.
2344 * Failure: FALSE, check GetLastError().
2348 * The identifier is unique only on the machine and only until the process
2349 * exits (including system shutdown).
2351 DWORD WINAPI GetProcessId( HANDLE hProcess )
2354 PROCESS_BASIC_INFORMATION pbi;
2356 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2358 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2359 SetLastError( RtlNtStatusToDosError(status) );
2364 /*********************************************************************
2365 * CloseW32Handle (KERNEL.474)
2366 * CloseHandle (KERNEL32.@)
2371 * handle [I] Handle to close.
2375 * Failure: FALSE, check GetLastError().
2377 BOOL WINAPI CloseHandle( HANDLE handle )
2381 /* stdio handles need special treatment */
2382 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2383 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2384 (handle == (HANDLE)STD_ERROR_HANDLE))
2385 handle = GetStdHandle( HandleToULong(handle) );
2387 if (is_console_handle(handle))
2388 return CloseConsoleHandle(handle);
2390 status = NtClose( handle );
2391 if (status) SetLastError( RtlNtStatusToDosError(status) );
2396 /*********************************************************************
2397 * GetHandleInformation (KERNEL32.@)
2399 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2401 OBJECT_DATA_INFORMATION info;
2402 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2404 if (status) SetLastError( RtlNtStatusToDosError(status) );
2408 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2409 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2415 /*********************************************************************
2416 * SetHandleInformation (KERNEL32.@)
2418 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2420 OBJECT_DATA_INFORMATION info;
2423 /* if not setting both fields, retrieve current value first */
2424 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2425 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2427 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2429 SetLastError( RtlNtStatusToDosError(status) );
2433 if (mask & HANDLE_FLAG_INHERIT)
2434 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2435 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2436 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2438 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2439 if (status) SetLastError( RtlNtStatusToDosError(status) );
2444 /*********************************************************************
2445 * DuplicateHandle (KERNEL32.@)
2447 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2448 HANDLE dest_process, HANDLE *dest,
2449 DWORD access, BOOL inherit, DWORD options )
2453 if (is_console_handle(source))
2455 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2456 if (source_process != dest_process ||
2457 source_process != GetCurrentProcess())
2459 SetLastError(ERROR_INVALID_PARAMETER);
2462 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2463 return (*dest != INVALID_HANDLE_VALUE);
2465 status = NtDuplicateObject( source_process, source, dest_process, dest,
2466 access, inherit ? OBJ_INHERIT : 0, options );
2467 if (status) SetLastError( RtlNtStatusToDosError(status) );
2472 /***********************************************************************
2473 * ConvertToGlobalHandle (KERNEL.476)
2474 * ConvertToGlobalHandle (KERNEL32.@)
2476 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2478 HANDLE ret = INVALID_HANDLE_VALUE;
2479 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2480 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2485 /***********************************************************************
2486 * SetHandleContext (KERNEL32.@)
2488 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2490 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2491 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2492 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2497 /***********************************************************************
2498 * GetHandleContext (KERNEL32.@)
2500 DWORD WINAPI GetHandleContext(HANDLE hnd)
2502 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2503 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2504 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2509 /***********************************************************************
2510 * CreateSocketHandle (KERNEL32.@)
2512 HANDLE WINAPI CreateSocketHandle(void)
2514 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2515 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2516 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2517 return INVALID_HANDLE_VALUE;
2521 /***********************************************************************
2522 * SetPriorityClass (KERNEL32.@)
2524 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2527 PROCESS_PRIORITY_CLASS ppc;
2529 ppc.Foreground = FALSE;
2530 switch (priorityclass)
2532 case IDLE_PRIORITY_CLASS:
2533 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2534 case BELOW_NORMAL_PRIORITY_CLASS:
2535 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2536 case NORMAL_PRIORITY_CLASS:
2537 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2538 case ABOVE_NORMAL_PRIORITY_CLASS:
2539 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2540 case HIGH_PRIORITY_CLASS:
2541 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2542 case REALTIME_PRIORITY_CLASS:
2543 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2545 SetLastError(ERROR_INVALID_PARAMETER);
2549 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2552 if (status != STATUS_SUCCESS)
2554 SetLastError( RtlNtStatusToDosError(status) );
2561 /***********************************************************************
2562 * GetPriorityClass (KERNEL32.@)
2564 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2567 PROCESS_BASIC_INFORMATION pbi;
2569 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2571 if (status != STATUS_SUCCESS)
2573 SetLastError( RtlNtStatusToDosError(status) );
2576 switch (pbi.BasePriority)
2578 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2579 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2580 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2581 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2582 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2583 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2585 SetLastError( ERROR_INVALID_PARAMETER );
2590 /***********************************************************************
2591 * SetProcessAffinityMask (KERNEL32.@)
2593 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2597 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2598 &affmask, sizeof(DWORD_PTR));
2601 SetLastError( RtlNtStatusToDosError(status) );
2608 /**********************************************************************
2609 * GetProcessAffinityMask (KERNEL32.@)
2611 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2612 PDWORD_PTR lpProcessAffinityMask,
2613 PDWORD_PTR lpSystemAffinityMask )
2615 PROCESS_BASIC_INFORMATION pbi;
2618 status = NtQueryInformationProcess(hProcess,
2619 ProcessBasicInformation,
2620 &pbi, sizeof(pbi), NULL);
2623 SetLastError( RtlNtStatusToDosError(status) );
2626 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2628 if (lpSystemAffinityMask) *lpSystemAffinityMask = 1;
2633 /***********************************************************************
2634 * GetProcessVersion (KERNEL32.@)
2636 DWORD WINAPI GetProcessVersion( DWORD processid )
2638 IMAGE_NT_HEADERS *nt;
2640 if (processid && processid != GetCurrentProcessId())
2642 FIXME("should use ReadProcessMemory\n");
2645 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2646 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2647 nt->OptionalHeader.MinorSubsystemVersion);
2652 /***********************************************************************
2653 * SetProcessWorkingSetSize [KERNEL32.@]
2654 * Sets the min/max working set sizes for a specified process.
2657 * hProcess [I] Handle to the process of interest
2658 * minset [I] Specifies minimum working set size
2659 * maxset [I] Specifies maximum working set size
2665 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2668 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2669 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2670 /* Trim the working set to zero */
2671 /* Swap the process out of physical RAM */
2676 /***********************************************************************
2677 * GetProcessWorkingSetSize (KERNEL32.@)
2679 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2682 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2683 /* 32 MB working set size */
2684 if (minset) *minset = 32*1024*1024;
2685 if (maxset) *maxset = 32*1024*1024;
2690 /***********************************************************************
2691 * SetProcessShutdownParameters (KERNEL32.@)
2693 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2695 FIXME("(%08x, %08x): partial stub.\n", level, flags);
2696 shutdown_flags = flags;
2697 shutdown_priority = level;
2702 /***********************************************************************
2703 * GetProcessShutdownParameters (KERNEL32.@)
2706 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2708 *lpdwLevel = shutdown_priority;
2709 *lpdwFlags = shutdown_flags;
2714 /***********************************************************************
2715 * GetProcessPriorityBoost (KERNEL32.@)
2717 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2719 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2721 /* Report that no boost is present.. */
2722 *pDisablePriorityBoost = FALSE;
2727 /***********************************************************************
2728 * SetProcessPriorityBoost (KERNEL32.@)
2730 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2732 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2733 /* Say we can do it. I doubt the program will notice that we don't. */
2738 /***********************************************************************
2739 * ReadProcessMemory (KERNEL32.@)
2741 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2742 SIZE_T *bytes_read )
2744 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2745 if (status) SetLastError( RtlNtStatusToDosError(status) );
2750 /***********************************************************************
2751 * WriteProcessMemory (KERNEL32.@)
2753 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2754 SIZE_T *bytes_written )
2756 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2757 if (status) SetLastError( RtlNtStatusToDosError(status) );
2762 /****************************************************************************
2763 * FlushInstructionCache (KERNEL32.@)
2765 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2768 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2769 if (status) SetLastError( RtlNtStatusToDosError(status) );
2774 /******************************************************************
2775 * GetProcessIoCounters (KERNEL32.@)
2777 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2781 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2782 ioc, sizeof(*ioc), NULL);
2783 if (status) SetLastError( RtlNtStatusToDosError(status) );
2787 /******************************************************************
2788 * GetProcessHandleCount (KERNEL32.@)
2790 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
2794 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
2795 cnt, sizeof(*cnt), NULL);
2796 if (status) SetLastError( RtlNtStatusToDosError(status) );
2800 /***********************************************************************
2801 * ProcessIdToSessionId (KERNEL32.@)
2802 * This function is available on Terminal Server 4SP4 and Windows 2000
2804 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2806 /* According to MSDN, if the calling process is not in a terminal
2807 * services environment, then the sessionid returned is zero.
2814 /***********************************************************************
2815 * RegisterServiceProcess (KERNEL.491)
2816 * RegisterServiceProcess (KERNEL32.@)
2818 * A service process calls this function to ensure that it continues to run
2819 * even after a user logged off.
2821 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2823 /* I don't think that Wine needs to do anything in this function */
2824 return 1; /* success */
2828 /**********************************************************************
2829 * IsWow64Process (KERNEL32.@)
2831 BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
2833 FIXME("(%p %p) stub!\n", hProcess, Wow64Process);
2834 *Wow64Process = FALSE;
2839 /***********************************************************************
2840 * GetCurrentProcess (KERNEL32.@)
2842 * Get a handle to the current process.
2848 * A handle representing the current process.
2850 #undef GetCurrentProcess
2851 HANDLE WINAPI GetCurrentProcess(void)
2853 return (HANDLE)0xffffffff;
2856 /***********************************************************************
2857 * CmdBatNotification (KERNEL32.@)
2859 * Notifies the system that a batch file has started or finished.
2862 * bBatchRunning [I] TRUE if a batch file has started or
2863 * FALSE if a batch file has finished executing.
2868 BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
2870 FIXME("%d\n", bBatchRunning);