4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 #include "wine/winbase16.h"
30 #include "wine/winuser16.h"
31 #include "wine/exception.h"
32 #include "wine/library.h"
39 #include "wine/server.h"
41 #include "wine/debug.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(process);
44 WINE_DECLARE_DEBUG_CHANNEL(relay);
45 WINE_DECLARE_DEBUG_CHANNEL(win32);
49 /* Win32 process database */
52 LONG header[2]; /* 00 Kernel object header */
53 HMODULE module; /* 08 Main exe module (NT) */
54 void *event; /* 0c Pointer to an event object (unused) */
55 DWORD exit_code; /* 10 Process exit code */
56 DWORD unknown2; /* 14 Unknown */
57 HANDLE heap; /* 18 Default process heap */
58 HANDLE mem_context; /* 1c Process memory context */
59 DWORD flags; /* 20 Flags */
60 void *pdb16; /* 24 DOS PSP */
61 WORD PSP_sel; /* 28 Selector to DOS PSP */
62 WORD imte; /* 2a IMTE for the process module */
63 WORD threads; /* 2c Number of threads */
64 WORD running_threads; /* 2e Number of running threads */
65 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
66 WORD ring0_threads; /* 32 Number of ring 0 threads */
67 HANDLE system_heap; /* 34 System heap to allocate handles */
68 HTASK task; /* 38 Win16 task */
69 void *mem_map_files; /* 3c Pointer to mem-mapped files */
70 struct _ENVDB *env_db; /* 40 Environment database */
71 void *handle_table; /* 44 Handle table */
72 struct _PDB *parent; /* 48 Parent process */
73 void *modref_list; /* 4c MODREF list */
74 void *thread_list; /* 50 List of threads */
75 void *debuggee_CB; /* 54 Debuggee context block */
76 void *local_heap_free; /* 58 Head of local heap free list */
77 DWORD unknown4; /* 5c Unknown */
78 CRITICAL_SECTION crit_section; /* 60 Critical section */
79 DWORD unknown5[3]; /* 78 Unknown */
80 void *console; /* 84 Console */
81 DWORD tls_bits[2]; /* 88 TLS in-use bits */
82 DWORD process_dword; /* 90 Unknown */
83 struct _PDB *group; /* 94 Process group */
84 void *exe_modref; /* 98 MODREF for the process EXE */
85 void *top_filter; /* 9c Top exception filter */
86 DWORD priority; /* a0 Priority level */
87 HANDLE heap_list; /* a4 Head of process heap list */
88 void *heap_handles; /* a8 Head of heap handles list */
89 DWORD unknown6; /* ac Unknown */
90 void *console_provider; /* b0 Console provider (??) */
91 WORD env_selector; /* b4 Selector to process environment */
92 WORD error_mode; /* b6 Error mode */
93 HANDLE load_done_evt; /* b8 Event for process loading done */
94 void *UTState; /* bc Head of Univeral Thunk list */
95 DWORD unknown8; /* c0 Unknown (NT) */
96 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
102 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
103 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
104 #define PDB32_DOS_PROC 0x0010 /* Dos process */
105 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
106 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
107 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
109 static int app_argc; /* argc/argv seen by the application */
110 static char **app_argv;
111 static WCHAR **app_wargv;
112 static char main_exe_name[MAX_PATH];
113 static char *main_exe_name_ptr = main_exe_name;
114 static HANDLE main_exe_file;
116 unsigned int server_startticks;
118 /* memory/environ.c */
119 extern struct _ENVDB *ENV_InitStartupInfo( handle_t info_handle, size_t info_size,
120 char *main_exe_name, size_t main_exe_size );
121 extern BOOL ENV_BuildCommandLine( char **argv );
122 extern STARTUPINFOA current_startupinfo;
124 /* scheduler/pthread.c */
125 extern void PTHREAD_init_done(void);
127 extern BOOL MAIN_MainInit(void);
129 typedef WORD (WINAPI *pUserSignalProc)( UINT, DWORD, DWORD, HMODULE16 );
131 /***********************************************************************
132 * PROCESS_CallUserSignalProc
134 * FIXME: Some of the signals aren't sent correctly!
136 * The exact meaning of the USER signals is undocumented, but this
137 * should cover the basic idea:
139 * USIG_DLL_UNLOAD_WIN16
140 * This is sent when a 16-bit module is unloaded.
142 * USIG_DLL_UNLOAD_WIN32
143 * This is sent when a 32-bit module is unloaded.
145 * USIG_DLL_UNLOAD_ORPHANS
146 * This is sent after the last Win3.1 module is unloaded,
147 * to allow removal of orphaned menus.
149 * USIG_FAULT_DIALOG_PUSH
150 * USIG_FAULT_DIALOG_POP
151 * These are called to allow USER to prepare for displaying a
152 * fault dialog, even though the fault might have happened while
153 * inside a USER critical section.
156 * This is called from the context of a new thread, as soon as it
157 * has started to run.
160 * This is called, still in its context, just before a thread is
161 * about to terminate.
163 * USIG_PROCESS_CREATE
164 * This is called, in the parent process context, after a new process
168 * This is called in the new process context, just after the main thread
169 * has started execution (after the main thread's USIG_THREAD_INIT has
172 * USIG_PROCESS_LOADED
173 * This is called after the executable file has been loaded into the
174 * new process context.
176 * USIG_PROCESS_RUNNING
177 * This is called immediately before the main entry point is called.
180 * This is called in the context of a process that is about to
181 * terminate (but before the last thread's USIG_THREAD_EXIT has
184 * USIG_PROCESS_DESTROY
185 * This is called after a process has terminated.
188 * The meaning of the dwFlags bits is as follows:
191 * Current process is 32-bit.
194 * Current process is a (Win32) GUI process.
196 * USIG_FLAGS_FEEDBACK
197 * Current process needs 'feedback' (determined from the STARTUPINFO
198 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
201 * The signal is being sent due to a fault.
203 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
207 pUserSignalProc proc;
209 if (!(user = GetModuleHandleA( "user32.dll" ))) return;
210 if (!(proc = (pUserSignalProc)GetProcAddress( user, "UserSignalProc" ))) return;
212 /* Determine dwFlags */
214 if ( !(current_process.flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
215 if ( !(current_process.flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
217 if ( dwFlags & USIG_FLAGS_GUI )
219 /* Feedback defaults to ON */
220 if ( !(current_startupinfo.dwFlags & STARTF_FORCEOFFFEEDBACK) )
221 dwFlags |= USIG_FLAGS_FEEDBACK;
225 /* Feedback defaults to OFF */
226 if (current_startupinfo.dwFlags & STARTF_FORCEONFEEDBACK)
227 dwFlags |= USIG_FLAGS_FEEDBACK;
230 /* Call USER signal proc */
232 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
233 proc( uCode, GetCurrentThreadId(), dwFlags, hModule );
235 proc( uCode, GetCurrentProcessId(), dwFlags, hModule );
238 /***********************************************************************
241 * Main process initialisation code
243 static BOOL process_init( char *argv[] )
246 int create_flags = 0;
247 size_t info_size = 0;
250 /* store the program name */
254 /* Fill the initial process structure */
255 current_process.exit_code = STILL_ACTIVE;
256 current_process.threads = 1;
257 current_process.running_threads = 1;
258 current_process.ring0_threads = 1;
259 current_process.group = ¤t_process;
260 current_process.priority = 8; /* Normal */
262 /* Setup the server connection */
265 /* Retrieve startup info from the server */
266 SERVER_START_REQ( init_process )
268 req->ldt_copy = &wine_ldt_copy;
269 req->ppid = getppid();
270 wine_server_set_reply( req, main_exe_name, sizeof(main_exe_name)-1 );
271 if ((ret = !wine_server_call_err( req )))
273 size_t len = wine_server_reply_size( reply );
274 main_exe_name[len] = 0;
275 main_exe_file = reply->exe_file;
276 create_flags = reply->create_flags;
277 info_size = reply->info_size;
279 server_startticks = reply->server_start;
280 current_startupinfo.hStdInput = reply->hstdin;
281 current_startupinfo.hStdOutput = reply->hstdout;
282 current_startupinfo.hStdError = reply->hstderr;
286 if (!ret) return FALSE;
288 /* Create the process heap */
289 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
291 if (create_flags == 0 &&
292 current_startupinfo.hStdInput == 0 &&
293 current_startupinfo.hStdOutput == 0 &&
294 current_startupinfo.hStdError == 0)
296 /* no parent, and no new console requested, create a simple console with bare handles to
297 * unix stdio input & output streams (aka simple console)
299 SetStdHandle( STD_INPUT_HANDLE, FILE_DupUnixHandle( 0, GENERIC_READ|SYNCHRONIZE, TRUE ));
300 SetStdHandle( STD_OUTPUT_HANDLE, FILE_DupUnixHandle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE ));
301 SetStdHandle( STD_ERROR_HANDLE, FILE_DupUnixHandle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE ));
303 else if (!(create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
305 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
306 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
307 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
310 /* Now we can use the pthreads routines */
313 /* Copy the parent environment */
314 if (!(current_process.env_db = ENV_InitStartupInfo( info, info_size,
315 main_exe_name, sizeof(main_exe_name) )))
318 /* Parse command line arguments */
319 OPTIONS_ParseOptions( argv );
321 while (argv[app_argc]) app_argc++;
323 ret = MAIN_MainInit();
325 if (create_flags & CREATE_NEW_CONSOLE)
331 /***********************************************************************
334 * Startup routine of a new process. Runs on the new process stack.
336 static void start_process(void)
338 int debugged, console_app;
339 LPTHREAD_START_ROUTINE entry;
341 HFILE main_file = main_exe_file;
343 /* use original argv[0] as name for the main module */
344 if (!main_exe_name[0])
346 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
347 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
352 UINT drive_type = GetDriveTypeA( main_exe_name );
353 /* don't keep the file handle open on removable media */
354 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
357 /* Retrieve entry point address */
358 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
359 PE_HEADER(current_process.module)->OptionalHeader.AddressOfEntryPoint);
360 console_app = (PE_HEADER(current_process.module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
361 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
363 /* Signal the parent process to continue */
364 SERVER_START_REQ( init_process_done )
366 req->module = (void *)current_process.module;
367 req->module_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfImage;
369 /* API requires a double indirection */
370 req->name = &main_exe_name_ptr;
371 req->exe_file = main_file;
372 req->gui = !console_app;
373 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
374 wine_server_call( req );
375 debugged = reply->debugged;
379 /* Install signal handlers; this cannot be done before, since we cannot
380 * send exceptions to the debugger before the create process event that
381 * is sent by REQ_INIT_PROCESS_DONE */
382 if (!SIGNAL_Init()) goto error;
384 /* create the main modref and load dependencies */
385 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
389 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
391 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
393 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
394 * context of the parent process. Actually, the USER signal proc
395 * doesn't really care about that, but it *does* require that the
396 * startup parameters are correctly set up, so that GetProcessDword
397 * works. Furthermore, before calling the USER signal proc the
398 * 16-bit stack must be set up, which it is only after TASK_Create
399 * in the case of a 16-bit process. Thus, we send the signal here.
401 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
402 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
403 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
404 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
405 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
406 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
409 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
410 GetCurrentThreadId(), main_exe_name, entry );
411 if (debugged) DbgBreakPoint();
412 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
413 * Dunno about other OSs */
414 SetLastError(0); /* clear error code */
415 ExitThread( entry(NULL) );
418 ExitProcess( GetLastError() );
422 /***********************************************************************
425 * Try to open the Winelib app .so file based on argv[0] or WINEPRELOAD.
427 void *open_winelib_app( char *argv[] )
434 if ((name = getenv( "WINEPRELOAD" )))
436 if (!(ret = wine_dll_load_main_exe( name, 0, errStr, sizeof(errStr) )))
438 MESSAGE( "%s: could not load '%s' as specified in the WINEPRELOAD environment variable: %s\n",
439 argv[0], name, errStr );
445 const char *argv0 = main_exe_name;
448 /* if argv[0] is "wine", don't try to load anything */
450 if (!(name = strrchr( argv0, '/' ))) name = argv0;
452 if (!strcmp( name, "wine" )) return NULL;
455 /* now try argv[0] with ".so" appended */
456 if ((tmp = HeapAlloc( GetProcessHeap(), 0, strlen(argv0) + 4 )))
458 strcpy( tmp, argv0 );
459 strcat( tmp, ".so" );
460 /* search in PATH only if there was no '/' in argv[0] */
461 ret = wine_dll_load_main_exe( tmp, (name == argv0), errStr, sizeof(errStr) );
462 if (!ret && !argv[1])
464 /* if no argv[1], this will be better than displaying usage */
465 MESSAGE( "%s: could not load library '%s' as Winelib application: %s\n",
466 argv[0], tmp, errStr );
469 HeapFree( GetProcessHeap(), 0, tmp );
475 /***********************************************************************
478 * Wine initialisation: load and start the main exe file.
480 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
482 DWORD stack_size = 0;
484 /* Initialize everything */
485 if (!process_init( argv )) exit(1);
487 if (open_winelib_app( app_argv )) goto found; /* try to open argv[0] as a winelib app */
489 app_argv++; /* remove argv[0] (wine itself) */
492 if (!main_exe_name[0])
494 if (!app_argv[0]) OPTIONS_Usage();
496 /* open the exe file */
497 if (!SearchPathA( NULL, app_argv[0], ".exe", sizeof(main_exe_name), main_exe_name, NULL) &&
498 !SearchPathA( NULL, app_argv[0], NULL, sizeof(main_exe_name), main_exe_name, NULL))
500 MESSAGE( "%s: cannot find '%s'\n", argv0, app_argv[0] );
507 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
508 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
510 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
515 /* first try Win32 format; this will fail if the file is not a PE binary */
516 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 )))
518 if (PE_HEADER(current_process.module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
519 ExitProcess( ERROR_BAD_EXE_FORMAT );
523 /* it must be 16-bit or DOS format */
524 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
525 current_process.flags |= PDB32_WIN16_PROC;
526 strcpy( win16_exe_name, main_exe_name );
527 main_exe_name[0] = 0;
528 *win16_exe_file = main_exe_file;
533 /* build command line */
534 if (!ENV_BuildCommandLine( app_argv )) goto error;
536 /* create 32-bit module for main exe */
537 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
538 stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
540 /* allocate main thread stack */
541 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
543 /* switch to the new stack */
544 SYSDEPS_SwitchToThreadStack( start_process );
547 ExitProcess( GetLastError() );
551 /***********************************************************************
552 * __wine_get_main_args (NTDLL.@)
554 * Return the argc/argv that the application should see.
555 * Used by the startup code generated in the .spec.c file.
557 int __wine_get_main_args( char ***argv )
564 /***********************************************************************
565 * __wine_get_wmain_args (NTDLL.@)
567 * Same as __wine_get_main_args but for Unicode.
569 int __wine_get_wmain_args( WCHAR ***argv )
577 for (i = 0; i < app_argc; i++)
578 total += MultiByteToWideChar( CP_ACP, 0, app_argv[i], -1, NULL, 0 );
580 app_wargv = HeapAlloc( GetProcessHeap(), 0,
581 total * sizeof(WCHAR) + (app_argc + 1) * sizeof(*app_wargv) );
582 p = (WCHAR *)(app_wargv + app_argc + 1);
583 for (i = 0; i < app_argc; i++)
585 DWORD len = MultiByteToWideChar( CP_ACP, 0, app_argv[i], -1, p, total );
590 app_wargv[app_argc] = NULL;
597 /***********************************************************************
600 * Build an argv array from a command-line.
601 * The command-line is modified to insert nulls.
602 * 'reserved' is the number of args to reserve before the first one.
604 static char **build_argv( char *cmdline, int reserved )
609 int in_quotes,bcount;
616 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
619 /* skip the remaining spaces */
620 while (*s==' ' || *s=='\t') {
627 } else if (*s=='\\') {
628 /* '\', count them */
630 } else if ((*s=='"') && ((bcount & 1)==0)) {
632 in_quotes=!in_quotes;
635 /* a regular character */
640 argv=malloc(argc*sizeof(*argv));
649 if ((*s==' ' || *s=='\t') && !in_quotes) {
650 /* Close the argument and copy it */
654 /* skip the remaining spaces */
657 } while (*s==' ' || *s=='\t');
659 /* Start with a new argument */
662 } else if (*s=='\\') {
666 } else if (*s=='"') {
668 if ((bcount & 1)==0) {
669 /* Preceeded by an even number of '\', this is half that
670 * number of '\', plus a '"' which we discard.
674 in_quotes=!in_quotes;
676 /* Preceeded by an odd number of '\', this is half that
677 * number of '\' followed by a '"'
685 /* a regular character */
700 /***********************************************************************
703 * Build the environment of a new child process.
705 static char **build_envp( const char *env, const char *extra_env )
711 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
712 for (p = env; *p; count++) p += strlen(p) + 1;
715 if ((envp = malloc( count * sizeof(*envp) )))
717 extern char **environ;
718 char **envptr = envp;
719 char **unixptr = environ;
720 /* first the extra strings */
721 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
722 /* then put PATH, HOME and WINEPREFIX from the unix env */
723 for (unixptr = environ; unixptr && *unixptr; unixptr++)
724 if (!memcmp( *unixptr, "PATH=", 5 ) ||
725 !memcmp( *unixptr, "HOME=", 5 ) ||
726 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
727 /* now put the Windows environment strings */
728 for (p = env; *p; p += strlen(p) + 1)
730 if (memcmp( p, "PATH=", 5 ) &&
731 memcmp( p, "HOME=", 5 ) &&
732 memcmp( p, "WINEPRELOAD=", 12 ) &&
733 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
741 /***********************************************************************
744 * Locate the Wine binary to exec for a new Win32 process.
746 static void exec_wine_binary( char **argv, char **envp )
748 const char *path, *pos, *ptr;
750 /* first, try for a WINELOADER environment variable */
751 argv[0] = getenv("WINELOADER");
753 execve( argv[0], argv, envp );
755 /* next, try bin directory */
756 argv[0] = BINDIR "/wine";
757 execve( argv[0], argv, envp );
759 /* now try the path of argv0 of the current binary */
760 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
761 if ((ptr = strrchr( full_argv0, '/' )))
763 memcpy( argv[0], full_argv0, ptr - full_argv0 );
764 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
765 execve( argv[0], argv, envp );
769 /* now search in the Unix path */
770 if ((path = getenv( "PATH" )))
772 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
776 while (*pos == ':') pos++;
778 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
779 memcpy( argv[0], pos, ptr - pos );
780 strcpy( argv[0] + (ptr - pos), "/wine" );
781 execve( argv[0], argv, envp );
787 /* finally try the current directory */
789 execve( argv[0], argv, envp );
793 /***********************************************************************
796 * Fork and exec a new Unix process, checking for errors.
798 static int fork_and_exec( const char *filename, char *cmdline,
799 const char *env, const char *newdir )
803 char *extra_env = NULL;
807 env = GetEnvironmentStringsA();
808 extra_env = DRIVE_BuildEnv();
816 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
817 if (!(pid = fork())) /* child */
819 char **argv = build_argv( cmdline, filename ? 0 : 2 );
820 char **envp = build_envp( env, extra_env );
823 if (newdir) chdir(newdir);
830 exec_wine_binary( argv, envp );
832 else execve( filename, argv, envp );
835 write( fd[1], &err, sizeof(err) );
839 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
844 if (pid == -1) FILE_SetDosError();
846 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
851 /***********************************************************************
854 * Create a new process. If hFile is a valid handle we have an exe
855 * file, and we exec a new copy of wine to load it; otherwise we
856 * simply exec the specified filename as a Unix process.
858 BOOL PROCESS_Create( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
859 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
860 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
861 LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
864 const char *unixfilename = NULL;
865 const char *unixdir = NULL;
866 DOS_FULL_NAME full_dir, full_name;
867 HANDLE load_done_evt = 0;
869 startup_info_t startup_info;
871 info->hThread = info->hProcess = 0;
872 info->dwProcessId = info->dwThreadId = 0;
874 if (lpCurrentDirectory)
876 if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_dir ))
877 unixdir = full_dir.long_name;
882 if (GetCurrentDirectoryA(sizeof(buf),buf))
884 if (DOSFS_GetFullName( buf, TRUE, &full_dir ))
885 unixdir = full_dir.long_name;
889 /* fill the startup info structure */
891 startup_info.size = sizeof(startup_info);
892 /* startup_info.filename_len is set below */
893 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
894 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
895 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
896 startup_info.x = startup->dwX;
897 startup_info.y = startup->dwY;
898 startup_info.cx = startup->dwXSize;
899 startup_info.cy = startup->dwYSize;
900 startup_info.x_chars = startup->dwXCountChars;
901 startup_info.y_chars = startup->dwYCountChars;
902 startup_info.attribute = startup->dwFillAttribute;
903 startup_info.cmd_show = startup->wShowWindow;
904 startup_info.flags = startup->dwFlags;
906 /* create the process on the server side */
908 SERVER_START_REQ( new_process )
913 req->inherit_all = inherit;
914 req->create_flags = flags;
915 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
916 req->exe_file = hFile;
917 if (startup->dwFlags & STARTF_USESTDHANDLES)
919 req->hstdin = startup->hStdInput;
920 req->hstdout = startup->hStdOutput;
921 req->hstderr = startup->hStdError;
925 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
926 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
927 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
930 if (!hFile) /* unix process */
932 unixfilename = filename;
933 if (DOSFS_GetFullName( filename, TRUE, &full_name ))
934 unixfilename = full_name.long_name;
935 nameptr = unixfilename;
937 else /* new wine process */
939 if (GetLongPathNameA( filename, buf, MAX_PATH ))
944 startup_info.filename_len = strlen(nameptr);
945 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
946 wine_server_add_data( req, nameptr, startup_info.filename_len );
947 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
948 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
949 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
951 ret = !wine_server_call_err( req );
952 process_info = reply->info;
955 if (!ret) return FALSE;
957 /* fork and execute */
959 if (fork_and_exec( unixfilename, cmd_line, env, unixdir ) == -1)
961 CloseHandle( process_info );
965 /* wait for the new process info to be ready */
967 ret = TRUE; /* pretend success even if we don't get the new process info */
968 if (WaitForSingleObject( process_info, 2000 ) == STATUS_WAIT_0)
970 SERVER_START_REQ( get_new_process_info )
972 req->info = process_info;
973 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
974 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
975 if ((ret = !wine_server_call_err( req )))
977 info->dwProcessId = (DWORD)reply->pid;
978 info->dwThreadId = (DWORD)reply->tid;
979 info->hProcess = reply->phandle;
980 info->hThread = reply->thandle;
981 load_done_evt = reply->event;
986 CloseHandle( process_info );
987 if (!ret) return FALSE;
989 /* Wait until process is initialized (or initialization failed) */
995 handles[0] = info->hProcess;
996 handles[1] = load_done_evt;
997 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
998 CloseHandle( load_done_evt );
999 if (res == STATUS_WAIT_0) /* the process died */
1002 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1003 CloseHandle( info->hThread );
1004 CloseHandle( info->hProcess );
1012 /***********************************************************************
1013 * ExitProcess (KERNEL32.@)
1015 void WINAPI ExitProcess( DWORD status )
1017 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1018 SERVER_START_REQ( terminate_process )
1020 /* send the exit code to the server */
1021 req->handle = GetCurrentProcess();
1022 req->exit_code = status;
1023 wine_server_call( req );
1029 /***********************************************************************
1030 * ExitProcess (KERNEL.466)
1032 void WINAPI ExitProcess16( WORD status )
1035 ReleaseThunkLock( &count );
1036 ExitProcess( status );
1039 /******************************************************************************
1040 * TerminateProcess (KERNEL32.@)
1042 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1044 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1045 if (status) SetLastError( RtlNtStatusToDosError(status) );
1050 /***********************************************************************
1051 * GetProcessDword (KERNEL.485)
1052 * GetProcessDword (KERNEL32.18)
1053 * 'Of course you cannot directly access Windows internal structures'
1055 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1059 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1061 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1063 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1069 case GPD_APP_COMPAT_FLAGS:
1070 return GetAppCompatFlags16(0);
1072 case GPD_LOAD_DONE_EVENT:
1073 return current_process.load_done_evt;
1075 case GPD_HINSTANCE16:
1076 return GetTaskDS16();
1078 case GPD_WINDOWS_VERSION:
1079 return GetExeVersion16();
1082 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1085 return (DWORD)¤t_process;
1087 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1088 return current_startupinfo.hStdOutput;
1090 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1091 return current_startupinfo.hStdInput;
1093 case GPD_STARTF_SHOWWINDOW:
1094 return current_startupinfo.wShowWindow;
1096 case GPD_STARTF_SIZE:
1097 x = current_startupinfo.dwXSize;
1098 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1099 y = current_startupinfo.dwYSize;
1100 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1101 return MAKELONG( x, y );
1103 case GPD_STARTF_POSITION:
1104 x = current_startupinfo.dwX;
1105 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1106 y = current_startupinfo.dwY;
1107 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1108 return MAKELONG( x, y );
1110 case GPD_STARTF_FLAGS:
1111 return current_startupinfo.dwFlags;
1117 return current_process.flags;
1120 return current_process.process_dword;
1123 ERR_(win32)("Unknown offset %d\n", offset );
1128 /***********************************************************************
1129 * SetProcessDword (KERNEL.484)
1130 * 'Of course you cannot directly access Windows internal structures'
1132 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1134 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1136 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1138 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1144 case GPD_APP_COMPAT_FLAGS:
1145 case GPD_LOAD_DONE_EVENT:
1146 case GPD_HINSTANCE16:
1147 case GPD_WINDOWS_VERSION:
1150 case GPD_STARTF_SHELLDATA:
1151 case GPD_STARTF_HOTKEY:
1152 case GPD_STARTF_SHOWWINDOW:
1153 case GPD_STARTF_SIZE:
1154 case GPD_STARTF_POSITION:
1155 case GPD_STARTF_FLAGS:
1158 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1162 current_process.process_dword = value;
1166 ERR_(win32)("Unknown offset %d\n", offset );
1172 /*********************************************************************
1173 * OpenProcess (KERNEL32.@)
1175 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1178 SERVER_START_REQ( open_process )
1180 req->pid = (void *)id;
1181 req->access = access;
1182 req->inherit = inherit;
1183 if (!wine_server_call_err( req )) ret = reply->handle;
1189 /*********************************************************************
1190 * MapProcessHandle (KERNEL.483)
1192 DWORD WINAPI MapProcessHandle( HANDLE handle )
1195 SERVER_START_REQ( get_process_info )
1197 req->handle = handle;
1198 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1204 /***********************************************************************
1205 * SetPriorityClass (KERNEL32.@)
1207 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1210 SERVER_START_REQ( set_process_info )
1212 req->handle = hprocess;
1213 req->priority = priorityclass;
1214 req->mask = SET_PROCESS_INFO_PRIORITY;
1215 ret = !wine_server_call_err( req );
1222 /***********************************************************************
1223 * GetPriorityClass (KERNEL32.@)
1225 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1228 SERVER_START_REQ( get_process_info )
1230 req->handle = hprocess;
1231 if (!wine_server_call_err( req )) ret = reply->priority;
1238 /***********************************************************************
1239 * SetProcessAffinityMask (KERNEL32.@)
1241 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1244 SERVER_START_REQ( set_process_info )
1246 req->handle = hProcess;
1247 req->affinity = affmask;
1248 req->mask = SET_PROCESS_INFO_AFFINITY;
1249 ret = !wine_server_call_err( req );
1255 /**********************************************************************
1256 * GetProcessAffinityMask (KERNEL32.@)
1258 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1259 LPDWORD lpProcessAffinityMask,
1260 LPDWORD lpSystemAffinityMask )
1263 SERVER_START_REQ( get_process_info )
1265 req->handle = hProcess;
1266 if (!wine_server_call_err( req ))
1268 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1269 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1278 /***********************************************************************
1279 * GetProcessVersion (KERNEL32.@)
1281 DWORD WINAPI GetProcessVersion( DWORD processid )
1283 IMAGE_NT_HEADERS *nt;
1285 if (processid && processid != GetCurrentProcessId())
1287 FIXME("should use ReadProcessMemory\n");
1290 if ((nt = RtlImageNtHeader( current_process.module )))
1291 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1292 nt->OptionalHeader.MinorSubsystemVersion);
1296 /***********************************************************************
1297 * GetProcessFlags (KERNEL32.@)
1299 DWORD WINAPI GetProcessFlags( DWORD processid )
1301 if (processid && processid != GetCurrentProcessId()) return 0;
1302 return current_process.flags;
1306 /***********************************************************************
1307 * SetProcessWorkingSetSize [KERNEL32.@]
1308 * Sets the min/max working set sizes for a specified process.
1311 * hProcess [I] Handle to the process of interest
1312 * minset [I] Specifies minimum working set size
1313 * maxset [I] Specifies maximum working set size
1317 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1320 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1321 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1322 /* Trim the working set to zero */
1323 /* Swap the process out of physical RAM */
1328 /***********************************************************************
1329 * GetProcessWorkingSetSize (KERNEL32.@)
1331 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1334 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1335 /* 32 MB working set size */
1336 if (minset) *minset = 32*1024*1024;
1337 if (maxset) *maxset = 32*1024*1024;
1341 /***********************************************************************
1342 * SetProcessShutdownParameters (KERNEL32.@)
1344 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1345 * Now tracks changes made (but does not act on these changes)
1347 static DWORD shutdown_flags = 0;
1348 static DWORD shutdown_priority = 0x280;
1350 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1352 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1353 shutdown_flags = flags;
1354 shutdown_priority = level;
1359 /***********************************************************************
1360 * GetProcessShutdownParameters (KERNEL32.@)
1363 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1365 *lpdwLevel = shutdown_priority;
1366 *lpdwFlags = shutdown_flags;
1371 /***********************************************************************
1372 * SetProcessPriorityBoost (KERNEL32.@)
1374 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1376 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1377 /* Say we can do it. I doubt the program will notice that we don't. */
1382 /***********************************************************************
1383 * ReadProcessMemory (KERNEL32.@)
1385 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1386 LPDWORD bytes_read )
1390 SERVER_START_REQ( read_process_memory )
1392 req->handle = process;
1393 req->addr = (void *)addr;
1394 wine_server_set_reply( req, buffer, size );
1395 if ((res = wine_server_call_err( req ))) size = 0;
1398 if (bytes_read) *bytes_read = size;
1403 /***********************************************************************
1404 * WriteProcessMemory (KERNEL32.@)
1406 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1407 LPDWORD bytes_written )
1409 static const int zero;
1410 unsigned int first_offset, last_offset, first_mask, last_mask;
1415 SetLastError( ERROR_INVALID_PARAMETER );
1419 /* compute the mask for the first int */
1421 first_offset = (unsigned int)addr % sizeof(int);
1422 memset( &first_mask, 0, first_offset );
1424 /* compute the mask for the last int */
1425 last_offset = (size + first_offset) % sizeof(int);
1427 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1429 SERVER_START_REQ( write_process_memory )
1431 req->handle = process;
1432 req->addr = (char *)addr - first_offset;
1433 req->first_mask = first_mask;
1434 req->last_mask = last_mask;
1435 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1436 wine_server_add_data( req, buffer, size );
1437 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1439 if ((res = wine_server_call_err( req ))) size = 0;
1442 if (bytes_written) *bytes_written = size;
1446 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1452 /***********************************************************************
1453 * RegisterServiceProcess (KERNEL.491)
1454 * RegisterServiceProcess (KERNEL32.@)
1456 * A service process calls this function to ensure that it continues to run
1457 * even after a user logged off.
1459 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1461 /* I don't think that Wine needs to do anything in that function */
1462 return 1; /* success */
1465 /***********************************************************************
1466 * GetExitCodeProcess [KERNEL32.@]
1468 * Gets termination status of specified process
1474 BOOL WINAPI GetExitCodeProcess(
1475 HANDLE hProcess, /* [in] handle to the process */
1476 LPDWORD lpExitCode) /* [out] address to receive termination status */
1479 SERVER_START_REQ( get_process_info )
1481 req->handle = hProcess;
1482 ret = !wine_server_call_err( req );
1483 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1490 /***********************************************************************
1491 * SetErrorMode (KERNEL32.@)
1493 UINT WINAPI SetErrorMode( UINT mode )
1495 UINT old = current_process.error_mode;
1496 current_process.error_mode = mode;
1501 /**************************************************************************
1502 * SetFileApisToOEM (KERNEL32.@)
1504 VOID WINAPI SetFileApisToOEM(void)
1506 current_process.flags |= PDB32_FILE_APIS_OEM;
1510 /**************************************************************************
1511 * SetFileApisToANSI (KERNEL32.@)
1513 VOID WINAPI SetFileApisToANSI(void)
1515 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1519 /******************************************************************************
1520 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1523 * TRUE: Set of file functions is using ANSI code page
1524 * FALSE: Set of file functions is using OEM code page
1526 BOOL WINAPI AreFileApisANSI(void)
1528 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1532 /**********************************************************************
1533 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1535 * Allocates a thread local storage index
1538 * Success: TLS Index
1539 * Failure: 0xFFFFFFFF
1541 DWORD WINAPI TlsAlloc( void )
1543 DWORD i, mask, ret = 0;
1544 DWORD *bits = current_process.tls_bits;
1545 RtlAcquirePebLock();
1546 if (*bits == 0xffffffff)
1550 if (*bits == 0xffffffff)
1552 RtlReleasePebLock();
1553 SetLastError( ERROR_NO_MORE_ITEMS );
1557 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1559 RtlReleasePebLock();
1560 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1565 /**********************************************************************
1566 * TlsFree [KERNEL32.@] Releases a TLS index.
1568 * Releases a thread local storage index, making it available for reuse
1574 BOOL WINAPI TlsFree(
1575 DWORD index) /* [in] TLS Index to free */
1577 DWORD mask = (1 << (index & 31));
1578 DWORD *bits = current_process.tls_bits;
1581 SetLastError( ERROR_INVALID_PARAMETER );
1584 if (index >= 32) bits++;
1585 RtlAcquirePebLock();
1586 if (!(*bits & mask)) /* already free? */
1588 RtlReleasePebLock();
1589 SetLastError( ERROR_INVALID_PARAMETER );
1593 NtCurrentTeb()->tls_array[index] = 0;
1594 /* FIXME: should zero all other thread values */
1595 RtlReleasePebLock();
1600 /**********************************************************************
1601 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1604 * Success: Value stored in calling thread's TLS slot for index
1605 * Failure: 0 and GetLastError returns NO_ERROR
1607 LPVOID WINAPI TlsGetValue(
1608 DWORD index) /* [in] TLS index to retrieve value for */
1612 SetLastError( ERROR_INVALID_PARAMETER );
1615 SetLastError( ERROR_SUCCESS );
1616 return NtCurrentTeb()->tls_array[index];
1620 /**********************************************************************
1621 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1627 BOOL WINAPI TlsSetValue(
1628 DWORD index, /* [in] TLS index to set value for */
1629 LPVOID value) /* [in] Value to be stored */
1633 SetLastError( ERROR_INVALID_PARAMETER );
1636 NtCurrentTeb()->tls_array[index] = value;
1641 /***********************************************************************
1642 * GetCurrentProcess (KERNEL32.@)
1644 #undef GetCurrentProcess
1645 HANDLE WINAPI GetCurrentProcess(void)