4 * Copyright 1996, 1998 Alexandre Julliard
15 #include "wine/winbase16.h"
16 #include "wine/exception.h"
17 #include "wine/library.h"
24 #include "wine/server.h"
27 #include "debugtools.h"
29 DEFAULT_DEBUG_CHANNEL(process);
30 DECLARE_DEBUG_CHANNEL(relay);
31 DECLARE_DEBUG_CHANNEL(win32);
35 /* Win32 process database */
38 LONG header[2]; /* 00 Kernel object header */
39 HMODULE module; /* 08 Main exe module (NT) */
40 void *event; /* 0c Pointer to an event object (unused) */
41 DWORD exit_code; /* 10 Process exit code */
42 DWORD unknown2; /* 14 Unknown */
43 HANDLE heap; /* 18 Default process heap */
44 HANDLE mem_context; /* 1c Process memory context */
45 DWORD flags; /* 20 Flags */
46 void *pdb16; /* 24 DOS PSP */
47 WORD PSP_sel; /* 28 Selector to DOS PSP */
48 WORD imte; /* 2a IMTE for the process module */
49 WORD threads; /* 2c Number of threads */
50 WORD running_threads; /* 2e Number of running threads */
51 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
52 WORD ring0_threads; /* 32 Number of ring 0 threads */
53 HANDLE system_heap; /* 34 System heap to allocate handles */
54 HTASK task; /* 38 Win16 task */
55 void *mem_map_files; /* 3c Pointer to mem-mapped files */
56 struct _ENVDB *env_db; /* 40 Environment database */
57 void *handle_table; /* 44 Handle table */
58 struct _PDB *parent; /* 48 Parent process */
59 void *modref_list; /* 4c MODREF list */
60 void *thread_list; /* 50 List of threads */
61 void *debuggee_CB; /* 54 Debuggee context block */
62 void *local_heap_free; /* 58 Head of local heap free list */
63 DWORD unknown4; /* 5c Unknown */
64 CRITICAL_SECTION crit_section; /* 60 Critical section */
65 DWORD unknown5[3]; /* 78 Unknown */
66 void *console; /* 84 Console */
67 DWORD tls_bits[2]; /* 88 TLS in-use bits */
68 DWORD process_dword; /* 90 Unknown */
69 struct _PDB *group; /* 94 Process group */
70 void *exe_modref; /* 98 MODREF for the process EXE */
71 void *top_filter; /* 9c Top exception filter */
72 DWORD priority; /* a0 Priority level */
73 HANDLE heap_list; /* a4 Head of process heap list */
74 void *heap_handles; /* a8 Head of heap handles list */
75 DWORD unknown6; /* ac Unknown */
76 void *console_provider; /* b0 Console provider (??) */
77 WORD env_selector; /* b4 Selector to process environment */
78 WORD error_mode; /* b6 Error mode */
79 HANDLE load_done_evt; /* b8 Event for process loading done */
80 void *UTState; /* bc Head of Univeral Thunk list */
81 DWORD unknown8; /* c0 Unknown (NT) */
82 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
88 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
89 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
90 #define PDB32_DOS_PROC 0x0010 /* Dos process */
91 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
92 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
93 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
95 static int app_argc; /* argc/argv seen by the application */
96 static char **app_argv;
97 static WCHAR **app_wargv;
98 static char main_exe_name[MAX_PATH];
99 static char *main_exe_name_ptr = main_exe_name;
100 static HANDLE main_exe_file;
102 unsigned int server_startticks;
104 /* memory/environ.c */
105 extern struct _ENVDB *ENV_BuildEnvironment(void);
106 extern BOOL ENV_BuildCommandLine( char **argv );
107 extern STARTUPINFOA current_startupinfo;
109 /* scheduler/pthread.c */
110 extern void PTHREAD_init_done(void);
112 extern BOOL MAIN_MainInit(void);
115 /***********************************************************************
116 * PROCESS_CallUserSignalProc
118 * FIXME: Some of the signals aren't sent correctly!
120 * The exact meaning of the USER signals is undocumented, but this
121 * should cover the basic idea:
123 * USIG_DLL_UNLOAD_WIN16
124 * This is sent when a 16-bit module is unloaded.
126 * USIG_DLL_UNLOAD_WIN32
127 * This is sent when a 32-bit module is unloaded.
129 * USIG_DLL_UNLOAD_ORPHANS
130 * This is sent after the last Win3.1 module is unloaded,
131 * to allow removal of orphaned menus.
133 * USIG_FAULT_DIALOG_PUSH
134 * USIG_FAULT_DIALOG_POP
135 * These are called to allow USER to prepare for displaying a
136 * fault dialog, even though the fault might have happened while
137 * inside a USER critical section.
140 * This is called from the context of a new thread, as soon as it
141 * has started to run.
144 * This is called, still in its context, just before a thread is
145 * about to terminate.
147 * USIG_PROCESS_CREATE
148 * This is called, in the parent process context, after a new process
152 * This is called in the new process context, just after the main thread
153 * has started execution (after the main thread's USIG_THREAD_INIT has
156 * USIG_PROCESS_LOADED
157 * This is called after the executable file has been loaded into the
158 * new process context.
160 * USIG_PROCESS_RUNNING
161 * This is called immediately before the main entry point is called.
164 * This is called in the context of a process that is about to
165 * terminate (but before the last thread's USIG_THREAD_EXIT has
168 * USIG_PROCESS_DESTROY
169 * This is called after a process has terminated.
172 * The meaning of the dwFlags bits is as follows:
175 * Current process is 32-bit.
178 * Current process is a (Win32) GUI process.
180 * USIG_FLAGS_FEEDBACK
181 * Current process needs 'feedback' (determined from the STARTUPINFO
182 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
185 * The signal is being sent due to a fault.
187 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
189 DWORD flags = current_process.flags;
190 DWORD startup_flags = current_startupinfo.dwFlags;
193 if (!Callout.UserSignalProc) return;
195 /* Determine dwFlags */
197 if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
199 if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
201 if ( dwFlags & USIG_FLAGS_GUI )
203 /* Feedback defaults to ON */
204 if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
205 dwFlags |= USIG_FLAGS_FEEDBACK;
209 /* Feedback defaults to OFF */
210 if (startup_flags & STARTF_FORCEONFEEDBACK)
211 dwFlags |= USIG_FLAGS_FEEDBACK;
214 /* Call USER signal proc */
216 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
217 Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
219 Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
222 /***********************************************************************
225 * Main process initialisation code
227 static BOOL process_init( char *argv[] )
230 int create_flags = 0;
232 /* store the program name */
236 /* Fill the initial process structure */
237 current_process.exit_code = STILL_ACTIVE;
238 current_process.threads = 1;
239 current_process.running_threads = 1;
240 current_process.ring0_threads = 1;
241 current_process.group = ¤t_process;
242 current_process.priority = 8; /* Normal */
244 /* Setup the server connection */
247 /* Retrieve startup info from the server */
248 SERVER_START_REQ( init_process )
250 req->ldt_copy = &wine_ldt_copy;
251 req->ppid = getppid();
252 wine_server_set_reply( req, main_exe_name, sizeof(main_exe_name)-1 );
253 if ((ret = !wine_server_call_err( req )))
255 size_t len = wine_server_reply_size( reply );
256 main_exe_name[len] = 0;
257 main_exe_file = reply->exe_file;
258 create_flags = reply->create_flags;
259 current_startupinfo.dwFlags = reply->start_flags;
260 server_startticks = reply->server_start;
261 current_startupinfo.wShowWindow = reply->cmd_show;
262 current_startupinfo.hStdInput = reply->hstdin;
263 current_startupinfo.hStdOutput = reply->hstdout;
264 current_startupinfo.hStdError = reply->hstderr;
268 if (!ret) return FALSE;
270 /* Create the process heap */
271 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
273 if (create_flags == 0 &&
274 current_startupinfo.hStdInput == 0 &&
275 current_startupinfo.hStdOutput == 0 &&
276 current_startupinfo.hStdError == 0)
278 /* no parent, and no new console requested, create a simple console with bare handles to
279 * unix stdio input & output streams (aka simple console)
281 SetStdHandle( STD_INPUT_HANDLE, FILE_DupUnixHandle( 0, GENERIC_READ, TRUE ));
282 SetStdHandle( STD_OUTPUT_HANDLE, FILE_DupUnixHandle( 1, GENERIC_WRITE, TRUE ));
283 SetStdHandle( STD_ERROR_HANDLE, FILE_DupUnixHandle( 1, GENERIC_WRITE, TRUE ));
285 else if (!(create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
287 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
288 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
289 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
292 /* Now we can use the pthreads routines */
295 /* Copy the parent environment */
296 if (!(current_process.env_db = ENV_BuildEnvironment())) return FALSE;
298 /* Parse command line arguments */
299 OPTIONS_ParseOptions( argv );
301 while (argv[app_argc]) app_argc++;
303 ret = MAIN_MainInit();
305 if (create_flags & CREATE_NEW_CONSOLE)
311 /***********************************************************************
314 * Startup routine of a new process. Runs on the new process stack.
316 static void start_process(void)
318 int debugged, console_app;
319 LPTHREAD_START_ROUTINE entry;
321 HFILE main_file = main_exe_file;
323 /* use original argv[0] as name for the main module */
324 if (!main_exe_name[0])
326 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
327 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
332 UINT drive_type = GetDriveTypeA( main_exe_name );
333 /* don't keep the file handle open on removable media */
334 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
337 /* Retrieve entry point address */
338 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
339 PE_HEADER(current_process.module)->OptionalHeader.AddressOfEntryPoint);
340 console_app = (PE_HEADER(current_process.module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
341 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
343 /* Signal the parent process to continue */
344 SERVER_START_REQ( init_process_done )
346 req->module = (void *)current_process.module;
348 /* API requires a double indirection */
349 req->name = &main_exe_name_ptr;
350 req->exe_file = main_file;
351 req->gui = !console_app;
352 wine_server_call( req );
353 debugged = reply->debugged;
357 /* Install signal handlers; this cannot be done before, since we cannot
358 * send exceptions to the debugger before the create process event that
359 * is sent by REQ_INIT_PROCESS_DONE */
360 if (!SIGNAL_Init()) goto error;
362 /* create the main modref and load dependencies */
363 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
367 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
371 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
374 /* Get pointers to USER routines called by KERNEL */
377 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
378 * context of the parent process. Actually, the USER signal proc
379 * doesn't really care about that, but it *does* require that the
380 * startup parameters are correctly set up, so that GetProcessDword
381 * works. Furthermore, before calling the USER signal proc the
382 * 16-bit stack must be set up, which it is only after TASK_Create
383 * in the case of a 16-bit process. Thus, we send the signal here.
385 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
386 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
387 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
388 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
389 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
390 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
393 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
394 GetCurrentThreadId(), main_exe_name, entry );
395 if (debugged) DbgBreakPoint();
396 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
397 * Dunno about other OSs */
398 SetLastError(0); /* clear error code */
399 ExitThread( entry(NULL) );
402 ExitProcess( GetLastError() );
406 /***********************************************************************
409 * Try to open the Winelib app .so file based on argv[0] or WINEPRELOAD.
411 void *open_winelib_app( char *argv[] )
418 if ((name = getenv( "WINEPRELOAD" )))
420 if (!(ret = wine_dll_load_main_exe( name, 0, errStr, sizeof(errStr) )))
422 MESSAGE( "%s: could not load '%s' as specified in the WINEPRELOAD environment variable: %s\n",
423 argv[0], name, errStr );
429 const char *argv0 = main_exe_name;
432 /* if argv[0] is "wine", don't try to load anything */
434 if (!(name = strrchr( argv0, '/' ))) name = argv0;
436 if (!strcmp( name, "wine" )) return NULL;
439 /* now try argv[0] with ".so" appended */
440 if ((tmp = HeapAlloc( GetProcessHeap(), 0, strlen(argv0) + 4 )))
442 strcpy( tmp, argv0 );
443 strcat( tmp, ".so" );
444 /* search in PATH only if there was no '/' in argv[0] */
445 ret = wine_dll_load_main_exe( tmp, (name == argv0), errStr, sizeof(errStr) );
446 if (!ret && !argv[1])
448 /* if no argv[1], this will be better than displaying usage */
449 MESSAGE( "%s: could not load library '%s' as Winelib application: %s\n",
450 argv[0], tmp, errStr );
453 HeapFree( GetProcessHeap(), 0, tmp );
459 /***********************************************************************
462 * Wine initialisation: load and start the main exe file.
464 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
466 DWORD stack_size = 0;
468 /* Initialize everything */
469 if (!process_init( argv )) exit(1);
471 if (open_winelib_app( app_argv )) goto found; /* try to open argv[0] as a winelib app */
473 app_argv++; /* remove argv[0] (wine itself) */
476 if (!main_exe_name[0])
478 if (!app_argv[0]) OPTIONS_Usage();
480 /* open the exe file */
481 if (!SearchPathA( NULL, app_argv[0], ".exe", sizeof(main_exe_name), main_exe_name, NULL) &&
482 !SearchPathA( NULL, app_argv[0], NULL, sizeof(main_exe_name), main_exe_name, NULL))
484 MESSAGE( "%s: cannot find '%s'\n", argv0, app_argv[0] );
491 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
492 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
494 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
499 /* first try Win32 format; this will fail if the file is not a PE binary */
500 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 )))
502 if (PE_HEADER(current_process.module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
503 ExitProcess( ERROR_BAD_EXE_FORMAT );
507 /* it must be 16-bit or DOS format */
508 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
509 current_process.flags |= PDB32_WIN16_PROC;
510 strcpy( win16_exe_name, main_exe_name );
511 main_exe_name[0] = 0;
512 *win16_exe_file = main_exe_file;
517 /* build command line */
518 if (!ENV_BuildCommandLine( app_argv )) goto error;
520 /* create 32-bit module for main exe */
521 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
522 stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
524 /* allocate main thread stack */
525 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
527 /* switch to the new stack */
528 SYSDEPS_SwitchToThreadStack( start_process );
531 ExitProcess( GetLastError() );
535 /***********************************************************************
536 * __wine_get_main_args (NTDLL.@)
538 * Return the argc/argv that the application should see.
539 * Used by the startup code generated in the .spec.c file.
541 int __wine_get_main_args( char ***argv )
548 /***********************************************************************
549 * __wine_get_wmain_args (NTDLL.@)
551 * Same as __wine_get_main_args but for Unicode.
553 int __wine_get_wmain_args( WCHAR ***argv )
561 for (i = 0; i < app_argc; i++)
562 total += MultiByteToWideChar( CP_ACP, 0, app_argv[i], -1, NULL, 0 );
564 app_wargv = HeapAlloc( GetProcessHeap(), 0,
565 total * sizeof(WCHAR) + (app_argc + 1) * sizeof(*app_wargv) );
566 p = (WCHAR *)(app_wargv + app_argc + 1);
567 for (i = 0; i < app_argc; i++)
569 DWORD len = MultiByteToWideChar( CP_ACP, 0, app_argv[i], -1, p, total );
574 app_wargv[app_argc] = NULL;
581 /***********************************************************************
584 * Build an argv array from a command-line.
585 * The command-line is modified to insert nulls.
586 * 'reserved' is the number of args to reserve before the first one.
588 static char **build_argv( char *cmdline, int reserved )
593 int in_quotes,bcount;
600 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
603 /* skip the remaining spaces */
604 while (*s==' ' || *s=='\t') {
611 } else if (*s=='\\') {
612 /* '\', count them */
614 } else if ((*s=='"') && ((bcount & 1)==0)) {
616 in_quotes=!in_quotes;
619 /* a regular character */
624 argv=malloc(argc*sizeof(*argv));
633 if ((*s==' ' || *s=='\t') && !in_quotes) {
634 /* Close the argument and copy it */
638 /* skip the remaining spaces */
641 } while (*s==' ' || *s=='\t');
643 /* Start with a new argument */
646 } else if (*s=='\\') {
650 } else if (*s=='"') {
652 if ((bcount & 1)==0) {
653 /* Preceeded by an even number of '\', this is half that
654 * number of '\', plus a '"' which we discard.
658 in_quotes=!in_quotes;
660 /* Preceeded by an odd number of '\', this is half that
661 * number of '\' followed by a '"'
669 /* a regular character */
684 /***********************************************************************
687 * Build the environment of a new child process.
689 static char **build_envp( const char *env, const char *extra_env )
695 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
696 for (p = env; *p; count++) p += strlen(p) + 1;
699 if ((envp = malloc( count * sizeof(*envp) )))
701 extern char **environ;
702 char **envptr = envp;
703 char **unixptr = environ;
704 /* first the extra strings */
705 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
706 /* then put PATH, HOME and WINEPREFIX from the unix env */
707 for (unixptr = environ; unixptr && *unixptr; unixptr++)
708 if (!memcmp( *unixptr, "PATH=", 5 ) ||
709 !memcmp( *unixptr, "HOME=", 5 ) ||
710 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
711 /* now put the Windows environment strings */
712 for (p = env; *p; p += strlen(p) + 1)
714 if (memcmp( p, "PATH=", 5 ) &&
715 memcmp( p, "HOME=", 5 ) &&
716 memcmp( p, "WINEPRELOAD=", 12 ) &&
717 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
725 /***********************************************************************
728 * Locate the Wine binary to exec for a new Win32 process.
730 static void exec_wine_binary( char **argv, char **envp )
732 const char *path, *pos, *ptr;
734 /* first, try for a WINELOADER environment variable */
735 argv[0] = getenv("WINELOADER");
737 execve( argv[0], argv, envp );
739 /* next, try bin directory */
740 argv[0] = BINDIR "/wine";
741 execve( argv[0], argv, envp );
743 /* now try the path of argv0 of the current binary */
744 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
745 if ((ptr = strrchr( full_argv0, '/' )))
747 memcpy( argv[0], full_argv0, ptr - full_argv0 );
748 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
749 execve( argv[0], argv, envp );
753 /* now search in the Unix path */
754 if ((path = getenv( "PATH" )))
756 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
760 while (*pos == ':') pos++;
762 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
763 memcpy( argv[0], pos, ptr - pos );
764 strcpy( argv[0] + (ptr - pos), "/wine" );
765 execve( argv[0], argv, envp );
771 /* finally try the current directory */
773 execve( argv[0], argv, envp );
777 /***********************************************************************
780 * Fork and exec a new Unix process, checking for errors.
782 static int fork_and_exec( const char *filename, char *cmdline,
783 const char *env, const char *newdir )
787 char *extra_env = NULL;
791 env = GetEnvironmentStringsA();
792 extra_env = DRIVE_BuildEnv();
800 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
801 if (!(pid = fork())) /* child */
803 char **argv = build_argv( cmdline, filename ? 0 : 2 );
804 char **envp = build_envp( env, extra_env );
807 if (newdir) chdir(newdir);
814 exec_wine_binary( argv, envp );
816 else execve( filename, argv, envp );
819 write( fd[1], &err, sizeof(err) );
823 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
828 if (pid == -1) FILE_SetDosError();
830 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
835 /***********************************************************************
838 * Create a new process. If hFile is a valid handle we have an exe
839 * file, and we exec a new copy of wine to load it; otherwise we
840 * simply exec the specified filename as a Unix process.
842 BOOL PROCESS_Create( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
843 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
844 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
845 LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
848 const char *unixfilename = NULL;
849 const char *unixdir = NULL;
850 DOS_FULL_NAME full_dir, full_name;
851 HANDLE load_done_evt = 0;
854 info->hThread = info->hProcess = 0;
855 info->dwProcessId = info->dwThreadId = 0;
857 if (lpCurrentDirectory)
859 if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_dir ))
860 unixdir = full_dir.long_name;
865 if (GetCurrentDirectoryA(sizeof(buf),buf))
867 if (DOSFS_GetFullName( buf, TRUE, &full_dir ))
868 unixdir = full_dir.long_name;
872 /* create the process on the server side */
874 SERVER_START_REQ( new_process )
878 req->inherit_all = inherit;
879 req->create_flags = flags;
880 req->start_flags = startup->dwFlags;
881 req->exe_file = hFile;
882 if (startup->dwFlags & STARTF_USESTDHANDLES)
884 req->hstdin = startup->hStdInput;
885 req->hstdout = startup->hStdOutput;
886 req->hstderr = startup->hStdError;
890 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
891 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
892 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
894 req->cmd_show = startup->wShowWindow;
896 if (!hFile) /* unix process */
898 unixfilename = filename;
899 if (DOSFS_GetFullName( filename, TRUE, &full_name ))
900 unixfilename = full_name.long_name;
901 wine_server_add_data( req, unixfilename, strlen(unixfilename) );
903 else /* new wine process */
905 if (GetLongPathNameA( filename, buf, MAX_PATH ))
906 wine_server_add_data( req, buf, strlen(buf) );
908 wine_server_add_data( req, filename, strlen(filename) );
910 ret = !wine_server_call_err( req );
911 process_info = reply->info;
914 if (!ret) return FALSE;
916 /* fork and execute */
918 if (fork_and_exec( unixfilename, cmd_line, env, unixdir ) == -1)
920 CloseHandle( process_info );
924 /* wait for the new process info to be ready */
926 ret = TRUE; /* pretend success even if we don't get the new process info */
927 if (WaitForSingleObject( process_info, 2000 ) == STATUS_WAIT_0)
929 SERVER_START_REQ( get_new_process_info )
931 req->info = process_info;
932 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
933 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
934 if ((ret = !wine_server_call_err( req )))
936 info->dwProcessId = (DWORD)reply->pid;
937 info->dwThreadId = (DWORD)reply->tid;
938 info->hProcess = reply->phandle;
939 info->hThread = reply->thandle;
940 load_done_evt = reply->event;
945 CloseHandle( process_info );
946 if (!ret) return FALSE;
948 /* Wait until process is initialized (or initialization failed) */
954 handles[0] = info->hProcess;
955 handles[1] = load_done_evt;
956 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
957 CloseHandle( load_done_evt );
958 if (res == STATUS_WAIT_0) /* the process died */
961 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
962 CloseHandle( info->hThread );
963 CloseHandle( info->hProcess );
971 /***********************************************************************
972 * ExitProcess (KERNEL32.@)
974 void WINAPI ExitProcess( DWORD status )
976 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
977 SERVER_START_REQ( terminate_process )
979 /* send the exit code to the server */
980 req->handle = GetCurrentProcess();
981 req->exit_code = status;
982 wine_server_call( req );
988 /***********************************************************************
989 * ExitProcess (KERNEL.466)
991 void WINAPI ExitProcess16( WORD status )
994 ReleaseThunkLock( &count );
995 ExitProcess( status );
998 /******************************************************************************
999 * TerminateProcess (KERNEL32.@)
1001 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1003 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1004 if (status) SetLastError( RtlNtStatusToDosError(status) );
1009 /***********************************************************************
1010 * GetProcessDword (KERNEL.485)
1011 * GetProcessDword (KERNEL32.18)
1012 * 'Of course you cannot directly access Windows internal structures'
1014 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1018 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1020 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1022 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1028 case GPD_APP_COMPAT_FLAGS:
1029 return GetAppCompatFlags16(0);
1031 case GPD_LOAD_DONE_EVENT:
1032 return current_process.load_done_evt;
1034 case GPD_HINSTANCE16:
1035 return GetTaskDS16();
1037 case GPD_WINDOWS_VERSION:
1038 return GetExeVersion16();
1041 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1044 return (DWORD)¤t_process;
1046 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1047 return current_startupinfo.hStdOutput;
1049 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1050 return current_startupinfo.hStdInput;
1052 case GPD_STARTF_SHOWWINDOW:
1053 return current_startupinfo.wShowWindow;
1055 case GPD_STARTF_SIZE:
1056 x = current_startupinfo.dwXSize;
1057 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1058 y = current_startupinfo.dwYSize;
1059 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1060 return MAKELONG( x, y );
1062 case GPD_STARTF_POSITION:
1063 x = current_startupinfo.dwX;
1064 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1065 y = current_startupinfo.dwY;
1066 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1067 return MAKELONG( x, y );
1069 case GPD_STARTF_FLAGS:
1070 return current_startupinfo.dwFlags;
1076 return current_process.flags;
1079 return current_process.process_dword;
1082 ERR_(win32)("Unknown offset %d\n", offset );
1087 /***********************************************************************
1088 * SetProcessDword (KERNEL.484)
1089 * 'Of course you cannot directly access Windows internal structures'
1091 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1093 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1095 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1097 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1103 case GPD_APP_COMPAT_FLAGS:
1104 case GPD_LOAD_DONE_EVENT:
1105 case GPD_HINSTANCE16:
1106 case GPD_WINDOWS_VERSION:
1109 case GPD_STARTF_SHELLDATA:
1110 case GPD_STARTF_HOTKEY:
1111 case GPD_STARTF_SHOWWINDOW:
1112 case GPD_STARTF_SIZE:
1113 case GPD_STARTF_POSITION:
1114 case GPD_STARTF_FLAGS:
1117 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1121 current_process.process_dword = value;
1125 ERR_(win32)("Unknown offset %d\n", offset );
1131 /*********************************************************************
1132 * OpenProcess (KERNEL32.@)
1134 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1137 SERVER_START_REQ( open_process )
1139 req->pid = (void *)id;
1140 req->access = access;
1141 req->inherit = inherit;
1142 if (!wine_server_call_err( req )) ret = reply->handle;
1148 /*********************************************************************
1149 * MapProcessHandle (KERNEL.483)
1151 DWORD WINAPI MapProcessHandle( HANDLE handle )
1154 SERVER_START_REQ( get_process_info )
1156 req->handle = handle;
1157 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1163 /***********************************************************************
1164 * SetPriorityClass (KERNEL32.@)
1166 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1169 SERVER_START_REQ( set_process_info )
1171 req->handle = hprocess;
1172 req->priority = priorityclass;
1173 req->mask = SET_PROCESS_INFO_PRIORITY;
1174 ret = !wine_server_call_err( req );
1181 /***********************************************************************
1182 * GetPriorityClass (KERNEL32.@)
1184 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1187 SERVER_START_REQ( get_process_info )
1189 req->handle = hprocess;
1190 if (!wine_server_call_err( req )) ret = reply->priority;
1197 /***********************************************************************
1198 * SetProcessAffinityMask (KERNEL32.@)
1200 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1203 SERVER_START_REQ( set_process_info )
1205 req->handle = hProcess;
1206 req->affinity = affmask;
1207 req->mask = SET_PROCESS_INFO_AFFINITY;
1208 ret = !wine_server_call_err( req );
1214 /**********************************************************************
1215 * GetProcessAffinityMask (KERNEL32.@)
1217 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1218 LPDWORD lpProcessAffinityMask,
1219 LPDWORD lpSystemAffinityMask )
1222 SERVER_START_REQ( get_process_info )
1224 req->handle = hProcess;
1225 if (!wine_server_call_err( req ))
1227 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1228 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1237 /***********************************************************************
1238 * GetProcessVersion (KERNEL32.@)
1240 DWORD WINAPI GetProcessVersion( DWORD processid )
1242 IMAGE_NT_HEADERS *nt;
1244 if (processid && processid != GetCurrentProcessId())
1246 FIXME("should use ReadProcessMemory\n");
1249 if ((nt = RtlImageNtHeader( current_process.module )))
1250 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1251 nt->OptionalHeader.MinorSubsystemVersion);
1255 /***********************************************************************
1256 * GetProcessFlags (KERNEL32.@)
1258 DWORD WINAPI GetProcessFlags( DWORD processid )
1260 if (processid && processid != GetCurrentProcessId()) return 0;
1261 return current_process.flags;
1265 /***********************************************************************
1266 * SetProcessWorkingSetSize [KERNEL32.@]
1267 * Sets the min/max working set sizes for a specified process.
1270 * hProcess [I] Handle to the process of interest
1271 * minset [I] Specifies minimum working set size
1272 * maxset [I] Specifies maximum working set size
1276 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1279 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1280 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1281 /* Trim the working set to zero */
1282 /* Swap the process out of physical RAM */
1287 /***********************************************************************
1288 * GetProcessWorkingSetSize (KERNEL32.@)
1290 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1293 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1294 /* 32 MB working set size */
1295 if (minset) *minset = 32*1024*1024;
1296 if (maxset) *maxset = 32*1024*1024;
1300 /***********************************************************************
1301 * SetProcessShutdownParameters (KERNEL32.@)
1303 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1304 * Now tracks changes made (but does not act on these changes)
1306 static DWORD shutdown_flags = 0;
1307 static DWORD shutdown_priority = 0x280;
1309 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1311 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1312 shutdown_flags = flags;
1313 shutdown_priority = level;
1318 /***********************************************************************
1319 * GetProcessShutdownParameters (KERNEL32.@)
1322 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1324 *lpdwLevel = shutdown_priority;
1325 *lpdwFlags = shutdown_flags;
1330 /***********************************************************************
1331 * SetProcessPriorityBoost (KERNEL32.@)
1333 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1335 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1336 /* Say we can do it. I doubt the program will notice that we don't. */
1341 /***********************************************************************
1342 * ReadProcessMemory (KERNEL32.@)
1344 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1345 LPDWORD bytes_read )
1349 SERVER_START_REQ( read_process_memory )
1351 req->handle = process;
1352 req->addr = (void *)addr;
1353 wine_server_set_reply( req, buffer, size );
1354 if ((res = wine_server_call_err( req ))) size = 0;
1357 if (bytes_read) *bytes_read = size;
1362 /***********************************************************************
1363 * WriteProcessMemory (KERNEL32.@)
1365 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1366 LPDWORD bytes_written )
1368 static const int zero;
1369 unsigned int first_offset, last_offset, first_mask, last_mask;
1374 SetLastError( ERROR_INVALID_PARAMETER );
1378 /* compute the mask for the first int */
1380 first_offset = (unsigned int)addr % sizeof(int);
1381 memset( &first_mask, 0, first_offset );
1383 /* compute the mask for the last int */
1384 last_offset = (size + first_offset) % sizeof(int);
1386 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1388 SERVER_START_REQ( write_process_memory )
1390 req->handle = process;
1391 req->addr = (char *)addr - first_offset;
1392 req->first_mask = first_mask;
1393 req->last_mask = last_mask;
1394 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1395 wine_server_add_data( req, buffer, size );
1396 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1398 if ((res = wine_server_call_err( req ))) size = 0;
1401 if (bytes_written) *bytes_written = size;
1405 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1411 /***********************************************************************
1412 * RegisterServiceProcess (KERNEL.491)
1413 * RegisterServiceProcess (KERNEL32.@)
1415 * A service process calls this function to ensure that it continues to run
1416 * even after a user logged off.
1418 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1420 /* I don't think that Wine needs to do anything in that function */
1421 return 1; /* success */
1424 /***********************************************************************
1425 * GetExitCodeProcess [KERNEL32.@]
1427 * Gets termination status of specified process
1433 BOOL WINAPI GetExitCodeProcess(
1434 HANDLE hProcess, /* [in] handle to the process */
1435 LPDWORD lpExitCode) /* [out] address to receive termination status */
1438 SERVER_START_REQ( get_process_info )
1440 req->handle = hProcess;
1441 ret = !wine_server_call_err( req );
1442 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1449 /***********************************************************************
1450 * SetErrorMode (KERNEL32.@)
1452 UINT WINAPI SetErrorMode( UINT mode )
1454 UINT old = current_process.error_mode;
1455 current_process.error_mode = mode;
1460 /**************************************************************************
1461 * SetFileApisToOEM (KERNEL32.@)
1463 VOID WINAPI SetFileApisToOEM(void)
1465 current_process.flags |= PDB32_FILE_APIS_OEM;
1469 /**************************************************************************
1470 * SetFileApisToANSI (KERNEL32.@)
1472 VOID WINAPI SetFileApisToANSI(void)
1474 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1478 /******************************************************************************
1479 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1482 * TRUE: Set of file functions is using ANSI code page
1483 * FALSE: Set of file functions is using OEM code page
1485 BOOL WINAPI AreFileApisANSI(void)
1487 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1491 /**********************************************************************
1492 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1494 * Allocates a thread local storage index
1497 * Success: TLS Index
1498 * Failure: 0xFFFFFFFF
1500 DWORD WINAPI TlsAlloc( void )
1502 DWORD i, mask, ret = 0;
1503 DWORD *bits = current_process.tls_bits;
1504 RtlAcquirePebLock();
1505 if (*bits == 0xffffffff)
1509 if (*bits == 0xffffffff)
1511 RtlReleasePebLock();
1512 SetLastError( ERROR_NO_MORE_ITEMS );
1516 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1518 RtlReleasePebLock();
1519 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1524 /**********************************************************************
1525 * TlsFree [KERNEL32.@] Releases a TLS index.
1527 * Releases a thread local storage index, making it available for reuse
1533 BOOL WINAPI TlsFree(
1534 DWORD index) /* [in] TLS Index to free */
1536 DWORD mask = (1 << (index & 31));
1537 DWORD *bits = current_process.tls_bits;
1540 SetLastError( ERROR_INVALID_PARAMETER );
1543 if (index >= 32) bits++;
1544 RtlAcquirePebLock();
1545 if (!(*bits & mask)) /* already free? */
1547 RtlReleasePebLock();
1548 SetLastError( ERROR_INVALID_PARAMETER );
1552 NtCurrentTeb()->tls_array[index] = 0;
1553 /* FIXME: should zero all other thread values */
1554 RtlReleasePebLock();
1559 /**********************************************************************
1560 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1563 * Success: Value stored in calling thread's TLS slot for index
1564 * Failure: 0 and GetLastError returns NO_ERROR
1566 LPVOID WINAPI TlsGetValue(
1567 DWORD index) /* [in] TLS index to retrieve value for */
1571 SetLastError( ERROR_INVALID_PARAMETER );
1574 SetLastError( ERROR_SUCCESS );
1575 return NtCurrentTeb()->tls_array[index];
1579 /**********************************************************************
1580 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1586 BOOL WINAPI TlsSetValue(
1587 DWORD index, /* [in] TLS index to set value for */
1588 LPVOID value) /* [in] Value to be stored */
1592 SetLastError( ERROR_INVALID_PARAMETER );
1595 NtCurrentTeb()->tls_array[index] = value;
1600 /***********************************************************************
1601 * GetCurrentProcess (KERNEL32.@)
1603 #undef GetCurrentProcess
1604 HANDLE WINAPI GetCurrentProcess(void)