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
22 #include "wine/port.h"
35 #include "wine/winbase16.h"
36 #include "wine/winuser16.h"
37 #include "wine/exception.h"
38 #include "wine/library.h"
46 #include "wine/server.h"
48 #include "wine/debug.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(process);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
52 WINE_DECLARE_DEBUG_CHANNEL(snoop);
53 WINE_DECLARE_DEBUG_CHANNEL(win32);
57 /* Win32 process database */
60 LONG header[2]; /* 00 Kernel object header */
61 HMODULE module; /* 08 Main exe module (NT) */
62 void *event; /* 0c Pointer to an event object (unused) */
63 DWORD exit_code; /* 10 Process exit code */
64 DWORD unknown2; /* 14 Unknown */
65 HANDLE heap; /* 18 Default process heap */
66 HANDLE mem_context; /* 1c Process memory context */
67 DWORD flags; /* 20 Flags */
68 void *pdb16; /* 24 DOS PSP */
69 WORD PSP_sel; /* 28 Selector to DOS PSP */
70 WORD imte; /* 2a IMTE for the process module */
71 WORD threads; /* 2c Number of threads */
72 WORD running_threads; /* 2e Number of running threads */
73 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
74 WORD ring0_threads; /* 32 Number of ring 0 threads */
75 HANDLE system_heap; /* 34 System heap to allocate handles */
76 HTASK task; /* 38 Win16 task */
77 void *mem_map_files; /* 3c Pointer to mem-mapped files */
78 struct _ENVDB *env_db; /* 40 Environment database */
79 void *handle_table; /* 44 Handle table */
80 struct _PDB *parent; /* 48 Parent process */
81 void *modref_list; /* 4c MODREF list */
82 void *thread_list; /* 50 List of threads */
83 void *debuggee_CB; /* 54 Debuggee context block */
84 void *local_heap_free; /* 58 Head of local heap free list */
85 DWORD unknown4; /* 5c Unknown */
86 CRITICAL_SECTION crit_section; /* 60 Critical section */
87 DWORD unknown5[3]; /* 78 Unknown */
88 void *console; /* 84 Console */
89 DWORD tls_bits[2]; /* 88 TLS in-use bits */
90 DWORD process_dword; /* 90 Unknown */
91 struct _PDB *group; /* 94 Process group */
92 void *exe_modref; /* 98 MODREF for the process EXE */
93 void *top_filter; /* 9c Top exception filter */
94 DWORD priority; /* a0 Priority level */
95 HANDLE heap_list; /* a4 Head of process heap list */
96 void *heap_handles; /* a8 Head of heap handles list */
97 DWORD unknown6; /* ac Unknown */
98 void *console_provider; /* b0 Console provider (??) */
99 WORD env_selector; /* b4 Selector to process environment */
100 WORD error_mode; /* b6 Error mode */
101 HANDLE load_done_evt; /* b8 Event for process loading done */
102 void *UTState; /* bc Head of Univeral Thunk list */
103 DWORD unknown8; /* c0 Unknown (NT) */
104 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
110 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
111 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
112 #define PDB32_DOS_PROC 0x0010 /* Dos process */
113 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
114 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
115 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
117 static char main_exe_name[MAX_PATH];
118 static char *main_exe_name_ptr = main_exe_name;
119 static HANDLE main_exe_file;
120 static unsigned int server_startticks;
122 int main_create_flags = 0;
124 /* memory/environ.c */
125 extern struct _ENVDB *ENV_InitStartupInfo( size_t info_size, char *main_exe_name,
126 size_t main_exe_size );
127 extern BOOL ENV_BuildCommandLine( char **argv );
128 extern STARTUPINFOA current_startupinfo;
130 /* scheduler/pthread.c */
131 extern void PTHREAD_init_done(void);
133 extern void RELAY_InitDebugLists(void);
134 extern BOOL MAIN_MainInit(void);
136 typedef WORD (WINAPI *pUserSignalProc)( UINT, DWORD, DWORD, HMODULE16 );
138 /***********************************************************************
139 * PROCESS_CallUserSignalProc
141 * FIXME: Some of the signals aren't sent correctly!
143 * The exact meaning of the USER signals is undocumented, but this
144 * should cover the basic idea:
146 * USIG_DLL_UNLOAD_WIN16
147 * This is sent when a 16-bit module is unloaded.
149 * USIG_DLL_UNLOAD_WIN32
150 * This is sent when a 32-bit module is unloaded.
152 * USIG_DLL_UNLOAD_ORPHANS
153 * This is sent after the last Win3.1 module is unloaded,
154 * to allow removal of orphaned menus.
156 * USIG_FAULT_DIALOG_PUSH
157 * USIG_FAULT_DIALOG_POP
158 * These are called to allow USER to prepare for displaying a
159 * fault dialog, even though the fault might have happened while
160 * inside a USER critical section.
163 * This is called from the context of a new thread, as soon as it
164 * has started to run.
167 * This is called, still in its context, just before a thread is
168 * about to terminate.
170 * USIG_PROCESS_CREATE
171 * This is called, in the parent process context, after a new process
175 * This is called in the new process context, just after the main thread
176 * has started execution (after the main thread's USIG_THREAD_INIT has
179 * USIG_PROCESS_LOADED
180 * This is called after the executable file has been loaded into the
181 * new process context.
183 * USIG_PROCESS_RUNNING
184 * This is called immediately before the main entry point is called.
187 * This is called in the context of a process that is about to
188 * terminate (but before the last thread's USIG_THREAD_EXIT has
191 * USIG_PROCESS_DESTROY
192 * This is called after a process has terminated.
195 * The meaning of the dwFlags bits is as follows:
198 * Current process is 32-bit.
201 * Current process is a (Win32) GUI process.
203 * USIG_FLAGS_FEEDBACK
204 * Current process needs 'feedback' (determined from the STARTUPINFO
205 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
208 * The signal is being sent due to a fault.
210 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
214 pUserSignalProc proc;
216 if (!(user = GetModuleHandleA( "user32.dll" ))) return;
217 if (!(proc = (pUserSignalProc)GetProcAddress( user, "UserSignalProc" ))) return;
219 /* Determine dwFlags */
221 if ( !(current_process.flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
222 if ( !(current_process.flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
224 if ( dwFlags & USIG_FLAGS_GUI )
226 /* Feedback defaults to ON */
227 if ( !(current_startupinfo.dwFlags & STARTF_FORCEOFFFEEDBACK) )
228 dwFlags |= USIG_FLAGS_FEEDBACK;
232 /* Feedback defaults to OFF */
233 if (current_startupinfo.dwFlags & STARTF_FORCEONFEEDBACK)
234 dwFlags |= USIG_FLAGS_FEEDBACK;
237 /* Call USER signal proc */
239 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
240 proc( uCode, GetCurrentThreadId(), dwFlags, hModule );
242 proc( uCode, GetCurrentProcessId(), dwFlags, hModule );
246 /***********************************************************************
249 inline static const char *get_basename( const char *name )
253 if ((p = strrchr( name, '/' ))) name = p + 1;
254 if ((p = strrchr( name, '\\' ))) name = p + 1;
259 /***********************************************************************
260 * open_builtin_exe_file
262 * Open an exe file for a builtin exe.
264 static void *open_builtin_exe_file( const char *name, char *error, int error_size, int test_only )
266 char exename[MAX_PATH], *p;
267 const char *basename = get_basename(name);
269 if (strlen(basename) >= sizeof(exename)) return NULL;
270 strcpy( exename, basename );
271 for (p = exename; *p; p++) *p = FILE_tolower(*p);
272 return wine_dll_load_main_exe( exename, error, error_size, test_only );
276 /***********************************************************************
279 * Open a specific exe file, taking load order into account.
280 * Returns the file handle or 0 for a builtin exe.
282 static HANDLE open_exe_file( const char *name )
284 enum loadorder_type loadorder[LOADORDER_NTYPES];
285 char buffer[MAX_PATH];
289 TRACE("looking for %s\n", debugstr_a(name) );
291 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
292 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
294 /* file doesn't exist, check for builtin */
295 if (!FILE_contains_path( name )) goto error;
296 if (!MODULE_GetBuiltinPath( name, "", buffer, sizeof(buffer) )) goto error;
300 MODULE_GetLoadOrder( loadorder, name, TRUE );
302 for(i = 0; i < LOADORDER_NTYPES; i++)
304 if (loadorder[i] == LOADORDER_INVALID) break;
308 TRACE( "Trying native exe %s\n", debugstr_a(name) );
309 if (handle != INVALID_HANDLE_VALUE) return handle;
312 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
313 if (open_builtin_exe_file( name, NULL, 0, 1 ))
315 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
322 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
325 SetLastError( ERROR_FILE_NOT_FOUND );
326 return INVALID_HANDLE_VALUE;
330 /***********************************************************************
333 * Open an exe file, and return the full name and file handle.
334 * Returns FALSE if file could not be found.
335 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
336 * If file is a builtin exe, returns TRUE and sets handle to 0.
338 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
340 enum loadorder_type loadorder[LOADORDER_NTYPES];
343 TRACE("looking for %s\n", debugstr_a(name) );
345 if (!SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) &&
346 !MODULE_GetBuiltinPath( name, ".exe", buffer, buflen ))
348 /* no builtin found, try native without extension in case it is a Unix app */
350 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
352 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
353 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
354 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
360 MODULE_GetLoadOrder( loadorder, buffer, TRUE );
362 for(i = 0; i < LOADORDER_NTYPES; i++)
364 if (loadorder[i] == LOADORDER_INVALID) break;
368 TRACE( "Trying native exe %s\n", debugstr_a(buffer) );
369 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
370 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
372 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
375 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
376 if (open_builtin_exe_file( buffer, NULL, 0, 1 ))
386 SetLastError( ERROR_FILE_NOT_FOUND );
391 /***********************************************************************
394 * Main process initialisation code
396 static BOOL process_init( char *argv[] )
399 size_t info_size = 0;
401 /* store the program name */
404 /* Fill the initial process structure */
405 current_process.exit_code = STILL_ACTIVE;
406 current_process.threads = 1;
407 current_process.running_threads = 1;
408 current_process.ring0_threads = 1;
409 current_process.group = ¤t_process;
410 current_process.priority = 8; /* Normal */
412 /* Setup the server connection */
415 /* Retrieve startup info from the server */
416 SERVER_START_REQ( init_process )
418 req->ldt_copy = &wine_ldt_copy;
419 req->ppid = getppid();
420 if ((ret = !wine_server_call_err( req )))
422 main_exe_file = reply->exe_file;
423 main_create_flags = reply->create_flags;
424 info_size = reply->info_size;
425 server_startticks = reply->server_start;
426 current_startupinfo.hStdInput = reply->hstdin;
427 current_startupinfo.hStdOutput = reply->hstdout;
428 current_startupinfo.hStdError = reply->hstderr;
432 if (!ret) return FALSE;
434 /* Create the process heap */
435 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
437 if (main_create_flags == 0 &&
438 current_startupinfo.hStdInput == 0 &&
439 current_startupinfo.hStdOutput == 0 &&
440 current_startupinfo.hStdError == 0)
442 /* no parent, and no new console requested, create a simple console with bare handles to
443 * unix stdio input & output streams (aka simple console)
446 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &handle );
447 SetStdHandle( STD_INPUT_HANDLE, handle );
448 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
449 SetStdHandle( STD_OUTPUT_HANDLE, handle );
450 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
451 SetStdHandle( STD_ERROR_HANDLE, handle );
453 else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
455 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
456 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
457 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
460 /* Now we can use the pthreads routines */
463 /* Copy the parent environment */
464 if (!(current_process.env_db = ENV_InitStartupInfo( info_size, main_exe_name,
465 sizeof(main_exe_name) )))
468 /* Parse command line arguments */
469 OPTIONS_ParseOptions( !info_size ? argv : NULL );
471 ret = MAIN_MainInit();
472 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
478 /***********************************************************************
481 * Startup routine of a new process. Runs on the new process stack.
483 static void start_process(void)
485 int debugged, console_app;
486 LPTHREAD_START_ROUTINE entry;
488 HANDLE main_file = main_exe_file;
489 IMAGE_NT_HEADERS *nt;
491 /* use original argv[0] as name for the main module */
492 if (!main_exe_name[0])
494 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
495 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
500 UINT drive_type = GetDriveTypeA( main_exe_name );
501 /* don't keep the file handle open on removable media */
502 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
505 /* Retrieve entry point address */
506 nt = RtlImageNtHeader( current_process.module );
507 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
508 nt->OptionalHeader.AddressOfEntryPoint);
509 console_app = (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
510 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
512 /* Signal the parent process to continue */
513 SERVER_START_REQ( init_process_done )
515 req->module = (void *)current_process.module;
516 req->module_size = nt->OptionalHeader.SizeOfImage;
518 /* API requires a double indirection */
519 req->name = &main_exe_name_ptr;
520 req->exe_file = main_file;
521 req->gui = !console_app;
522 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
523 wine_server_call( req );
524 debugged = reply->debugged;
528 /* Install signal handlers; this cannot be done before, since we cannot
529 * send exceptions to the debugger before the create process event that
530 * is sent by REQ_INIT_PROCESS_DONE */
531 if (!SIGNAL_Init()) goto error;
533 /* create the main modref and load dependencies */
534 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
538 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
540 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
542 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
543 * context of the parent process. Actually, the USER signal proc
544 * doesn't really care about that, but it *does* require that the
545 * startup parameters are correctly set up, so that GetProcessDword
546 * works. Furthermore, before calling the USER signal proc the
547 * 16-bit stack must be set up, which it is only after TASK_Create
548 * in the case of a 16-bit process. Thus, we send the signal here.
550 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
551 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
552 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
553 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
554 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
555 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
558 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
559 GetCurrentThreadId(), main_exe_name, entry );
560 if (debugged) DbgBreakPoint();
561 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
562 * Dunno about other OSs */
563 SetLastError(0); /* clear error code */
564 ExitThread( entry(NULL) );
567 ExitProcess( GetLastError() );
571 /***********************************************************************
574 * Wine initialisation: load and start the main exe file.
576 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
579 DWORD stack_size = 0;
581 /* Initialize everything */
582 if (!process_init( argv )) exit(1);
584 argv++; /* remove argv[0] (wine itself) */
586 TRACE( "starting process name=%s file=%x argv[0]=%s\n",
587 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
589 if (!main_exe_name[0])
591 if (!argv[0]) OPTIONS_Usage();
593 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
595 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
598 if (main_exe_file == INVALID_HANDLE_VALUE)
600 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
605 if (!main_exe_file) /* no file handle -> Winelib app */
607 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
608 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0 ))
610 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
614 switch( MODULE_GetBinaryType( main_exe_file ))
617 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
618 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
619 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
622 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
625 /* check for .com extension */
626 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
628 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
634 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
635 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
636 current_process.flags |= PDB32_WIN16_PROC;
637 strcpy( win16_exe_name, main_exe_name );
638 main_exe_name[0] = 0;
639 *win16_exe_file = main_exe_file;
644 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
646 case BINARY_UNIX_EXE:
647 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
649 case BINARY_UNIX_LIB:
651 DOS_FULL_NAME full_name;
652 const char *name = main_exe_name;
653 UNICODE_STRING nameW;
655 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
656 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
657 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
658 RtlFreeUnicodeString(&nameW);
659 CloseHandle( main_exe_file );
661 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
663 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
666 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
672 /* build command line */
673 if (!ENV_BuildCommandLine( argv )) goto error;
675 /* create 32-bit module for main exe */
676 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
677 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
679 /* allocate main thread stack */
680 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
682 /* switch to the new stack */
683 SYSDEPS_SwitchToThreadStack( start_process );
686 ExitProcess( GetLastError() );
690 /***********************************************************************
693 * Build an argv array from a command-line.
694 * The command-line is modified to insert nulls.
695 * 'reserved' is the number of args to reserve before the first one.
697 static char **build_argv( char *cmdline, int reserved )
702 int in_quotes,bcount;
709 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
712 /* skip the remaining spaces */
713 while (*s==' ' || *s=='\t') {
720 } else if (*s=='\\') {
721 /* '\', count them */
723 } else if ((*s=='"') && ((bcount & 1)==0)) {
725 in_quotes=!in_quotes;
728 /* a regular character */
733 argv=malloc(argc*sizeof(*argv));
742 if ((*s==' ' || *s=='\t') && !in_quotes) {
743 /* Close the argument and copy it */
747 /* skip the remaining spaces */
750 } while (*s==' ' || *s=='\t');
752 /* Start with a new argument */
755 } else if (*s=='\\') {
759 } else if (*s=='"') {
761 if ((bcount & 1)==0) {
762 /* Preceeded by an even number of '\', this is half that
763 * number of '\', plus a '"' which we discard.
767 in_quotes=!in_quotes;
769 /* Preceeded by an odd number of '\', this is half that
770 * number of '\' followed by a '"'
778 /* a regular character */
793 /***********************************************************************
796 * Build the environment of a new child process.
798 static char **build_envp( const char *env, const char *extra_env )
804 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
805 for (p = env; *p; count++) p += strlen(p) + 1;
808 if ((envp = malloc( count * sizeof(*envp) )))
810 extern char **environ;
811 char **envptr = envp;
812 char **unixptr = environ;
813 /* first the extra strings */
814 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
815 /* then put PATH, HOME and WINEPREFIX from the unix env */
816 for (unixptr = environ; unixptr && *unixptr; unixptr++)
817 if (!memcmp( *unixptr, "PATH=", 5 ) ||
818 !memcmp( *unixptr, "HOME=", 5 ) ||
819 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
820 /* now put the Windows environment strings */
821 for (p = env; *p; p += strlen(p) + 1)
823 if (memcmp( p, "PATH=", 5 ) &&
824 memcmp( p, "HOME=", 5 ) &&
825 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
833 /***********************************************************************
836 * Locate the Wine binary to exec for a new Win32 process.
838 static void exec_wine_binary( char **argv, char **envp )
840 const char *path, *pos, *ptr;
842 /* first, try for a WINELOADER environment variable */
843 argv[0] = getenv("WINELOADER");
845 execve( argv[0], argv, envp );
847 /* next, try bin directory */
848 argv[0] = BINDIR "/wine";
849 execve( argv[0], argv, envp );
851 /* now try the path of argv0 of the current binary */
852 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
853 if ((ptr = strrchr( full_argv0, '/' )))
855 memcpy( argv[0], full_argv0, ptr - full_argv0 );
856 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
857 execve( argv[0], argv, envp );
861 /* now search in the Unix path */
862 if ((path = getenv( "PATH" )))
864 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
868 while (*pos == ':') pos++;
870 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
871 memcpy( argv[0], pos, ptr - pos );
872 strcpy( argv[0] + (ptr - pos), "/wine" );
873 execve( argv[0], argv, envp );
881 /***********************************************************************
884 * Fork and exec a new Unix process, checking for errors.
886 static int fork_and_exec( const char *filename, char *cmdline,
887 const char *env, const char *newdir )
891 char *extra_env = NULL;
895 env = GetEnvironmentStringsA();
896 extra_env = DRIVE_BuildEnv();
904 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
905 if (!(pid = fork())) /* child */
907 char **argv = build_argv( cmdline, filename ? 0 : 1 );
908 char **envp = build_envp( env, extra_env );
911 /* Reset signals that we previously set to SIG_IGN */
912 signal( SIGPIPE, SIG_DFL );
913 signal( SIGCHLD, SIG_DFL );
915 if (newdir) chdir(newdir);
919 if (!filename) exec_wine_binary( argv, envp );
920 else execve( filename, argv, envp );
923 write( fd[1], &err, sizeof(err) );
927 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
932 if (pid == -1) FILE_SetDosError();
934 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
939 /***********************************************************************
942 * Create a new process. If hFile is a valid handle we have an exe
943 * file, otherwise it is a Winelib app.
945 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
946 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
947 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
948 LPPROCESS_INFORMATION info, LPCSTR unixdir )
950 BOOL ret, success = FALSE;
952 startup_info_t startup_info;
954 /* fill the startup info structure */
956 startup_info.size = sizeof(startup_info);
957 /* startup_info.filename_len is set below */
958 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
959 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
960 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
961 startup_info.x = startup->dwX;
962 startup_info.y = startup->dwY;
963 startup_info.cx = startup->dwXSize;
964 startup_info.cy = startup->dwYSize;
965 startup_info.x_chars = startup->dwXCountChars;
966 startup_info.y_chars = startup->dwYCountChars;
967 startup_info.attribute = startup->dwFillAttribute;
968 startup_info.cmd_show = startup->wShowWindow;
969 startup_info.flags = startup->dwFlags;
971 /* create the process on the server side */
973 SERVER_START_REQ( new_process )
978 req->inherit_all = inherit;
979 req->create_flags = flags;
980 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
981 req->exe_file = hFile;
982 if (startup->dwFlags & STARTF_USESTDHANDLES)
984 req->hstdin = startup->hStdInput;
985 req->hstdout = startup->hStdOutput;
986 req->hstderr = startup->hStdError;
990 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
991 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
992 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
995 if (GetLongPathNameA( filename, buf, MAX_PATH ))
1000 startup_info.filename_len = strlen(nameptr);
1001 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
1002 wine_server_add_data( req, nameptr, startup_info.filename_len );
1003 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
1004 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
1005 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
1007 ret = !wine_server_call_err( req );
1008 process_info = reply->info;
1011 if (!ret) return FALSE;
1013 /* fork and execute */
1015 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
1017 CloseHandle( process_info );
1021 /* wait for the new process info to be ready */
1023 WaitForSingleObject( process_info, INFINITE );
1024 SERVER_START_REQ( get_new_process_info )
1026 req->info = process_info;
1027 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1028 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1029 if ((ret = !wine_server_call_err( req )))
1031 info->dwProcessId = (DWORD)reply->pid;
1032 info->dwThreadId = (DWORD)reply->tid;
1033 info->hProcess = reply->phandle;
1034 info->hThread = reply->thandle;
1035 success = reply->success;
1040 if (ret && !success) /* new process failed to start */
1043 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1044 CloseHandle( info->hThread );
1045 CloseHandle( info->hProcess );
1048 CloseHandle( process_info );
1053 /*************************************************************************
1056 * Helper for CreateProcess: retrieve the file name to load from the
1057 * app name and command line. Store the file name in buffer, and
1058 * return a possibly modified command line.
1059 * Also returns a handle to the opened file if it's a Windows binary.
1061 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1062 int buflen, HANDLE *handle )
1064 char *name, *pos, *ret = NULL;
1067 /* if we have an app name, everything is easy */
1071 /* use the unmodified app name as file name */
1072 lstrcpynA( buffer, appname, buflen );
1073 *handle = open_exe_file( buffer );
1074 if (!(ret = cmdline))
1076 /* no command-line, create one */
1077 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1078 sprintf( ret, "\"%s\"", appname );
1085 SetLastError( ERROR_INVALID_PARAMETER );
1089 /* first check for a quoted file name */
1091 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1093 int len = p - cmdline - 1;
1094 /* extract the quoted portion as file name */
1095 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1096 memcpy( name, cmdline + 1, len );
1099 if (find_exe_file( name, buffer, buflen, handle ))
1100 ret = cmdline; /* no change necessary */
1104 /* now try the command-line word by word */
1106 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1112 do *pos++ = *p++; while (*p && *p != ' ');
1114 if (find_exe_file( name, buffer, buflen, handle ))
1121 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1123 /* now build a new command-line with quotes */
1125 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1126 sprintf( ret, "\"%s\"%s", name, p );
1129 HeapFree( GetProcessHeap(), 0, name );
1134 /**********************************************************************
1135 * CreateProcessA (KERNEL32.@)
1137 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1138 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1139 DWORD flags, LPVOID env, LPCSTR cur_dir,
1140 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1144 const char *unixdir = NULL;
1145 DOS_FULL_NAME full_dir;
1146 char name[MAX_PATH];
1150 /* Process the AppName and/or CmdLine to get module name and path */
1152 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1154 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1156 if (hFile == INVALID_HANDLE_VALUE) goto done;
1158 /* Warn if unsupported features are used */
1160 if (flags & NORMAL_PRIORITY_CLASS)
1161 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1162 if (flags & IDLE_PRIORITY_CLASS)
1163 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1164 if (flags & HIGH_PRIORITY_CLASS)
1165 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1166 if (flags & REALTIME_PRIORITY_CLASS)
1167 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1168 if (flags & CREATE_NEW_PROCESS_GROUP)
1169 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1170 if (flags & CREATE_UNICODE_ENVIRONMENT)
1171 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1172 if (flags & CREATE_SEPARATE_WOW_VDM)
1173 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1174 if (flags & CREATE_SHARED_WOW_VDM)
1175 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1176 if (flags & CREATE_DEFAULT_ERROR_MODE)
1177 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1178 if (flags & CREATE_NO_WINDOW)
1179 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1180 if (flags & PROFILE_USER)
1181 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1182 if (flags & PROFILE_KERNEL)
1183 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1184 if (flags & PROFILE_SERVER)
1185 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1186 if (startup_info->lpDesktop)
1187 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1188 name, debugstr_a(startup_info->lpDesktop));
1189 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1190 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1191 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1192 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1193 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1194 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1195 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1196 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1200 UNICODE_STRING cur_dirW;
1201 RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1202 if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1203 unixdir = full_dir.long_name;
1204 RtlFreeUnicodeString(&cur_dirW);
1208 WCHAR buf[MAX_PATH];
1209 if (GetCurrentDirectoryW(MAX_PATH, buf))
1211 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1215 info->hThread = info->hProcess = 0;
1216 info->dwProcessId = info->dwThreadId = 0;
1218 /* Determine executable type */
1220 if (!hFile) /* builtin exe */
1222 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1223 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1224 inherit, flags, startup_info, info, unixdir );
1228 switch( MODULE_GetBinaryType( hFile ))
1233 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1234 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1235 inherit, flags, startup_info, info, unixdir );
1238 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1239 SetLastError( ERROR_BAD_EXE_FORMAT );
1242 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1243 SetLastError( ERROR_BAD_EXE_FORMAT );
1245 case BINARY_UNIX_LIB:
1246 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1247 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1248 inherit, flags, startup_info, info, unixdir );
1250 case BINARY_UNKNOWN:
1251 /* check for .com extension */
1252 if ((p = strrchr( name, '.' )) && !FILE_strcasecmp( p, ".com" ))
1254 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1255 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1256 inherit, flags, startup_info, info, unixdir );
1260 case BINARY_UNIX_EXE:
1262 /* unknown file, try as unix executable */
1263 UNICODE_STRING nameW;
1264 DOS_FULL_NAME full_name;
1265 const char *unixfilename = name;
1267 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1269 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1270 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1271 RtlFreeUnicodeString(&nameW);
1272 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1276 CloseHandle( hFile );
1279 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1284 /**********************************************************************
1285 * CreateProcessW (KERNEL32.@)
1287 * lpReserved is not converted
1289 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1290 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1291 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1292 LPPROCESS_INFORMATION info )
1295 STARTUPINFOA StartupInfoA;
1297 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1298 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1299 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1301 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1302 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1303 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1305 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1307 if (startup_info->lpReserved)
1308 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1309 debugstr_w(startup_info->lpReserved));
1311 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1312 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1314 HeapFree( GetProcessHeap(), 0, cur_dirA );
1315 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1316 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1317 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1323 /***********************************************************************
1324 * ExitProcess (KERNEL32.@)
1326 void WINAPI ExitProcess( DWORD status )
1328 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1329 SERVER_START_REQ( terminate_process )
1331 /* send the exit code to the server */
1332 req->handle = GetCurrentProcess();
1333 req->exit_code = status;
1334 wine_server_call( req );
1340 /***********************************************************************
1341 * ExitProcess (KERNEL.466)
1343 void WINAPI ExitProcess16( WORD status )
1346 ReleaseThunkLock( &count );
1347 ExitProcess( status );
1350 /******************************************************************************
1351 * TerminateProcess (KERNEL32.@)
1353 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1355 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1356 if (status) SetLastError( RtlNtStatusToDosError(status) );
1361 /***********************************************************************
1362 * GetProcessDword (KERNEL.485)
1363 * GetProcessDword (KERNEL32.18)
1364 * 'Of course you cannot directly access Windows internal structures'
1366 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1370 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1372 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1374 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1380 case GPD_APP_COMPAT_FLAGS:
1381 return GetAppCompatFlags16(0);
1383 case GPD_LOAD_DONE_EVENT:
1384 return (DWORD)current_process.load_done_evt;
1386 case GPD_HINSTANCE16:
1387 return GetTaskDS16();
1389 case GPD_WINDOWS_VERSION:
1390 return GetExeVersion16();
1393 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1396 return (DWORD)¤t_process;
1398 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1399 return (DWORD)current_startupinfo.hStdOutput;
1401 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1402 return (DWORD)current_startupinfo.hStdInput;
1404 case GPD_STARTF_SHOWWINDOW:
1405 return current_startupinfo.wShowWindow;
1407 case GPD_STARTF_SIZE:
1408 x = current_startupinfo.dwXSize;
1409 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1410 y = current_startupinfo.dwYSize;
1411 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1412 return MAKELONG( x, y );
1414 case GPD_STARTF_POSITION:
1415 x = current_startupinfo.dwX;
1416 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1417 y = current_startupinfo.dwY;
1418 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1419 return MAKELONG( x, y );
1421 case GPD_STARTF_FLAGS:
1422 return current_startupinfo.dwFlags;
1428 return current_process.flags;
1431 return current_process.process_dword;
1434 ERR_(win32)("Unknown offset %d\n", offset );
1439 /***********************************************************************
1440 * SetProcessDword (KERNEL.484)
1441 * 'Of course you cannot directly access Windows internal structures'
1443 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1445 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1447 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1449 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1455 case GPD_APP_COMPAT_FLAGS:
1456 case GPD_LOAD_DONE_EVENT:
1457 case GPD_HINSTANCE16:
1458 case GPD_WINDOWS_VERSION:
1461 case GPD_STARTF_SHELLDATA:
1462 case GPD_STARTF_HOTKEY:
1463 case GPD_STARTF_SHOWWINDOW:
1464 case GPD_STARTF_SIZE:
1465 case GPD_STARTF_POSITION:
1466 case GPD_STARTF_FLAGS:
1469 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1473 current_process.process_dword = value;
1477 ERR_(win32)("Unknown offset %d\n", offset );
1483 /*********************************************************************
1484 * OpenProcess (KERNEL32.@)
1486 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1489 SERVER_START_REQ( open_process )
1492 req->access = access;
1493 req->inherit = inherit;
1494 if (!wine_server_call_err( req )) ret = reply->handle;
1500 /*********************************************************************
1501 * MapProcessHandle (KERNEL.483)
1503 DWORD WINAPI MapProcessHandle( HANDLE handle )
1506 SERVER_START_REQ( get_process_info )
1508 req->handle = handle;
1509 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1515 /***********************************************************************
1516 * SetPriorityClass (KERNEL32.@)
1518 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1521 SERVER_START_REQ( set_process_info )
1523 req->handle = hprocess;
1524 req->priority = priorityclass;
1525 req->mask = SET_PROCESS_INFO_PRIORITY;
1526 ret = !wine_server_call_err( req );
1533 /***********************************************************************
1534 * GetPriorityClass (KERNEL32.@)
1536 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1539 SERVER_START_REQ( get_process_info )
1541 req->handle = hprocess;
1542 if (!wine_server_call_err( req )) ret = reply->priority;
1549 /***********************************************************************
1550 * SetProcessAffinityMask (KERNEL32.@)
1552 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1555 SERVER_START_REQ( set_process_info )
1557 req->handle = hProcess;
1558 req->affinity = affmask;
1559 req->mask = SET_PROCESS_INFO_AFFINITY;
1560 ret = !wine_server_call_err( req );
1566 /**********************************************************************
1567 * GetProcessAffinityMask (KERNEL32.@)
1569 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1570 LPDWORD lpProcessAffinityMask,
1571 LPDWORD lpSystemAffinityMask )
1574 SERVER_START_REQ( get_process_info )
1576 req->handle = hProcess;
1577 if (!wine_server_call_err( req ))
1579 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1580 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1589 /***********************************************************************
1590 * GetProcessVersion (KERNEL32.@)
1592 DWORD WINAPI GetProcessVersion( DWORD processid )
1594 IMAGE_NT_HEADERS *nt;
1596 if (processid && processid != GetCurrentProcessId())
1598 FIXME("should use ReadProcessMemory\n");
1601 if ((nt = RtlImageNtHeader( current_process.module )))
1602 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1603 nt->OptionalHeader.MinorSubsystemVersion);
1607 /***********************************************************************
1608 * GetProcessFlags (KERNEL32.@)
1610 DWORD WINAPI GetProcessFlags( DWORD processid )
1612 if (processid && processid != GetCurrentProcessId()) return 0;
1613 return current_process.flags;
1617 /***********************************************************************
1618 * SetProcessWorkingSetSize [KERNEL32.@]
1619 * Sets the min/max working set sizes for a specified process.
1622 * hProcess [I] Handle to the process of interest
1623 * minset [I] Specifies minimum working set size
1624 * maxset [I] Specifies maximum working set size
1628 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
1631 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1632 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
1633 /* Trim the working set to zero */
1634 /* Swap the process out of physical RAM */
1639 /***********************************************************************
1640 * GetProcessWorkingSetSize (KERNEL32.@)
1642 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
1645 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1646 /* 32 MB working set size */
1647 if (minset) *minset = 32*1024*1024;
1648 if (maxset) *maxset = 32*1024*1024;
1652 /***********************************************************************
1653 * SetProcessShutdownParameters (KERNEL32.@)
1655 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1656 * Now tracks changes made (but does not act on these changes)
1658 static DWORD shutdown_flags = 0;
1659 static DWORD shutdown_priority = 0x280;
1661 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1663 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1664 shutdown_flags = flags;
1665 shutdown_priority = level;
1670 /***********************************************************************
1671 * GetProcessShutdownParameters (KERNEL32.@)
1674 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1676 *lpdwLevel = shutdown_priority;
1677 *lpdwFlags = shutdown_flags;
1682 /***********************************************************************
1683 * SetProcessPriorityBoost (KERNEL32.@)
1685 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1687 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1688 /* Say we can do it. I doubt the program will notice that we don't. */
1693 /***********************************************************************
1694 * ReadProcessMemory (KERNEL32.@)
1696 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
1697 SIZE_T *bytes_read )
1701 SERVER_START_REQ( read_process_memory )
1703 req->handle = process;
1704 req->addr = (void *)addr;
1705 wine_server_set_reply( req, buffer, size );
1706 if ((res = wine_server_call_err( req ))) size = 0;
1709 if (bytes_read) *bytes_read = size;
1714 /***********************************************************************
1715 * WriteProcessMemory (KERNEL32.@)
1717 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
1718 SIZE_T *bytes_written )
1720 static const int zero;
1721 unsigned int first_offset, last_offset, first_mask, last_mask;
1726 SetLastError( ERROR_INVALID_PARAMETER );
1730 /* compute the mask for the first int */
1732 first_offset = (unsigned int)addr % sizeof(int);
1733 memset( &first_mask, 0, first_offset );
1735 /* compute the mask for the last int */
1736 last_offset = (size + first_offset) % sizeof(int);
1738 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1740 SERVER_START_REQ( write_process_memory )
1742 req->handle = process;
1743 req->addr = (char *)addr - first_offset;
1744 req->first_mask = first_mask;
1745 req->last_mask = last_mask;
1746 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1747 wine_server_add_data( req, buffer, size );
1748 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1750 if ((res = wine_server_call_err( req ))) size = 0;
1753 if (bytes_written) *bytes_written = size;
1757 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1763 /***********************************************************************
1764 * RegisterServiceProcess (KERNEL.491)
1765 * RegisterServiceProcess (KERNEL32.@)
1767 * A service process calls this function to ensure that it continues to run
1768 * even after a user logged off.
1770 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1772 /* I don't think that Wine needs to do anything in that function */
1773 return 1; /* success */
1776 /***********************************************************************
1777 * GetExitCodeProcess [KERNEL32.@]
1779 * Gets termination status of specified process
1785 BOOL WINAPI GetExitCodeProcess(
1786 HANDLE hProcess, /* [in] handle to the process */
1787 LPDWORD lpExitCode) /* [out] address to receive termination status */
1790 SERVER_START_REQ( get_process_info )
1792 req->handle = hProcess;
1793 ret = !wine_server_call_err( req );
1794 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1801 /***********************************************************************
1802 * SetErrorMode (KERNEL32.@)
1804 UINT WINAPI SetErrorMode( UINT mode )
1806 UINT old = current_process.error_mode;
1807 current_process.error_mode = mode;
1812 /**************************************************************************
1813 * SetFileApisToOEM (KERNEL32.@)
1815 VOID WINAPI SetFileApisToOEM(void)
1817 current_process.flags |= PDB32_FILE_APIS_OEM;
1821 /**************************************************************************
1822 * SetFileApisToANSI (KERNEL32.@)
1824 VOID WINAPI SetFileApisToANSI(void)
1826 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1830 /******************************************************************************
1831 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1834 * TRUE: Set of file functions is using ANSI code page
1835 * FALSE: Set of file functions is using OEM code page
1837 BOOL WINAPI AreFileApisANSI(void)
1839 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1843 /***********************************************************************
1844 * GetTickCount (KERNEL32.@)
1846 * Returns the number of milliseconds, modulo 2^32, since the start
1847 * of the wineserver.
1849 DWORD WINAPI GetTickCount(void)
1852 gettimeofday( &t, NULL );
1853 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1857 /**********************************************************************
1858 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1860 * Allocates a thread local storage index
1863 * Success: TLS Index
1864 * Failure: 0xFFFFFFFF
1866 DWORD WINAPI TlsAlloc( void )
1868 DWORD i, mask, ret = 0;
1869 DWORD *bits = current_process.tls_bits;
1870 RtlAcquirePebLock();
1871 if (*bits == 0xffffffff)
1875 if (*bits == 0xffffffff)
1877 RtlReleasePebLock();
1878 SetLastError( ERROR_NO_MORE_ITEMS );
1882 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1884 RtlReleasePebLock();
1885 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1890 /**********************************************************************
1891 * TlsFree [KERNEL32.@] Releases a TLS index.
1893 * Releases a thread local storage index, making it available for reuse
1899 BOOL WINAPI TlsFree(
1900 DWORD index) /* [in] TLS Index to free */
1902 DWORD mask = (1 << (index & 31));
1903 DWORD *bits = current_process.tls_bits;
1906 SetLastError( ERROR_INVALID_PARAMETER );
1909 if (index >= 32) bits++;
1910 RtlAcquirePebLock();
1911 if (!(*bits & mask)) /* already free? */
1913 RtlReleasePebLock();
1914 SetLastError( ERROR_INVALID_PARAMETER );
1918 NtCurrentTeb()->tls_array[index] = 0;
1919 /* FIXME: should zero all other thread values */
1920 RtlReleasePebLock();
1925 /**********************************************************************
1926 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1929 * Success: Value stored in calling thread's TLS slot for index
1930 * Failure: 0 and GetLastError returns NO_ERROR
1932 LPVOID WINAPI TlsGetValue(
1933 DWORD index) /* [in] TLS index to retrieve value for */
1937 SetLastError( ERROR_INVALID_PARAMETER );
1940 SetLastError( ERROR_SUCCESS );
1941 return NtCurrentTeb()->tls_array[index];
1945 /**********************************************************************
1946 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1952 BOOL WINAPI TlsSetValue(
1953 DWORD index, /* [in] TLS index to set value for */
1954 LPVOID value) /* [in] Value to be stored */
1958 SetLastError( ERROR_INVALID_PARAMETER );
1961 NtCurrentTeb()->tls_array[index] = value;
1966 /***********************************************************************
1967 * GetCurrentProcess (KERNEL32.@)
1969 #undef GetCurrentProcess
1970 HANDLE WINAPI GetCurrentProcess(void)
1972 return (HANDLE)0xffffffff;