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_BuildEnvironment(void);
120 extern BOOL
ENV_BuildCommandLine( char **argv
);
121 extern STARTUPINFOA current_startupinfo
;
123 /* scheduler/pthread.c */
124 extern void PTHREAD_init_done(void);
126 extern BOOL
MAIN_MainInit(void);
128 typedef WORD (WINAPI
*pUserSignalProc
)( UINT
, DWORD
, DWORD
, HMODULE16
);
130 /***********************************************************************
131 * PROCESS_CallUserSignalProc
133 * FIXME: Some of the signals aren't sent correctly!
135 * The exact meaning of the USER signals is undocumented, but this
136 * should cover the basic idea:
138 * USIG_DLL_UNLOAD_WIN16
139 * This is sent when a 16-bit module is unloaded.
141 * USIG_DLL_UNLOAD_WIN32
142 * This is sent when a 32-bit module is unloaded.
144 * USIG_DLL_UNLOAD_ORPHANS
145 * This is sent after the last Win3.1 module is unloaded,
146 * to allow removal of orphaned menus.
148 * USIG_FAULT_DIALOG_PUSH
149 * USIG_FAULT_DIALOG_POP
150 * These are called to allow USER to prepare for displaying a
151 * fault dialog, even though the fault might have happened while
152 * inside a USER critical section.
155 * This is called from the context of a new thread, as soon as it
156 * has started to run.
159 * This is called, still in its context, just before a thread is
160 * about to terminate.
162 * USIG_PROCESS_CREATE
163 * This is called, in the parent process context, after a new process
167 * This is called in the new process context, just after the main thread
168 * has started execution (after the main thread's USIG_THREAD_INIT has
171 * USIG_PROCESS_LOADED
172 * This is called after the executable file has been loaded into the
173 * new process context.
175 * USIG_PROCESS_RUNNING
176 * This is called immediately before the main entry point is called.
179 * This is called in the context of a process that is about to
180 * terminate (but before the last thread's USIG_THREAD_EXIT has
183 * USIG_PROCESS_DESTROY
184 * This is called after a process has terminated.
187 * The meaning of the dwFlags bits is as follows:
190 * Current process is 32-bit.
193 * Current process is a (Win32) GUI process.
195 * USIG_FLAGS_FEEDBACK
196 * Current process needs 'feedback' (determined from the STARTUPINFO
197 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
200 * The signal is being sent due to a fault.
202 void PROCESS_CallUserSignalProc( UINT uCode
, HMODULE16 hModule
)
206 pUserSignalProc proc
;
208 if (!(user
= GetModuleHandleA( "user32.dll" ))) return;
209 if (!(proc
= (pUserSignalProc
)GetProcAddress( user
, "UserSignalProc" ))) return;
211 /* Determine dwFlags */
213 if ( !(current_process
.flags
& PDB32_WIN16_PROC
) ) dwFlags
|= USIG_FLAGS_WIN32
;
214 if ( !(current_process
.flags
& PDB32_CONSOLE_PROC
) ) dwFlags
|= USIG_FLAGS_GUI
;
216 if ( dwFlags
& USIG_FLAGS_GUI
)
218 /* Feedback defaults to ON */
219 if ( !(current_startupinfo
.dwFlags
& STARTF_FORCEOFFFEEDBACK
) )
220 dwFlags
|= USIG_FLAGS_FEEDBACK
;
224 /* Feedback defaults to OFF */
225 if (current_startupinfo
.dwFlags
& STARTF_FORCEONFEEDBACK
)
226 dwFlags
|= USIG_FLAGS_FEEDBACK
;
229 /* Call USER signal proc */
231 if ( uCode
== USIG_THREAD_INIT
|| uCode
== USIG_THREAD_EXIT
)
232 proc( uCode
, GetCurrentThreadId(), dwFlags
, hModule
);
234 proc( uCode
, GetCurrentProcessId(), dwFlags
, hModule
);
237 /***********************************************************************
240 * Main process initialisation code
242 static BOOL
process_init( char *argv
[] )
245 int create_flags
= 0;
247 /* store the program name */
251 /* Fill the initial process structure */
252 current_process
.exit_code
= STILL_ACTIVE
;
253 current_process
.threads
= 1;
254 current_process
.running_threads
= 1;
255 current_process
.ring0_threads
= 1;
256 current_process
.group
= ¤t_process
;
257 current_process
.priority
= 8; /* Normal */
259 /* Setup the server connection */
262 /* Retrieve startup info from the server */
263 SERVER_START_REQ( init_process
)
265 req
->ldt_copy
= &wine_ldt_copy
;
266 req
->ppid
= getppid();
267 wine_server_set_reply( req
, main_exe_name
, sizeof(main_exe_name
)-1 );
268 if ((ret
= !wine_server_call_err( req
)))
270 size_t len
= wine_server_reply_size( reply
);
271 main_exe_name
[len
] = 0;
272 main_exe_file
= reply
->exe_file
;
273 create_flags
= reply
->create_flags
;
274 current_startupinfo
.dwFlags
= reply
->start_flags
;
275 server_startticks
= reply
->server_start
;
276 current_startupinfo
.wShowWindow
= reply
->cmd_show
;
277 current_startupinfo
.hStdInput
= reply
->hstdin
;
278 current_startupinfo
.hStdOutput
= reply
->hstdout
;
279 current_startupinfo
.hStdError
= reply
->hstderr
;
283 if (!ret
) return FALSE
;
285 /* Create the process heap */
286 current_process
.heap
= HeapCreate( HEAP_GROWABLE
, 0, 0 );
288 if (create_flags
== 0 &&
289 current_startupinfo
.hStdInput
== 0 &&
290 current_startupinfo
.hStdOutput
== 0 &&
291 current_startupinfo
.hStdError
== 0)
293 /* no parent, and no new console requested, create a simple console with bare handles to
294 * unix stdio input & output streams (aka simple console)
296 SetStdHandle( STD_INPUT_HANDLE
, FILE_DupUnixHandle( 0, GENERIC_READ
|SYNCHRONIZE
, TRUE
));
297 SetStdHandle( STD_OUTPUT_HANDLE
, FILE_DupUnixHandle( 1, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
));
298 SetStdHandle( STD_ERROR_HANDLE
, FILE_DupUnixHandle( 1, GENERIC_WRITE
|SYNCHRONIZE
, TRUE
));
300 else if (!(create_flags
& (DETACHED_PROCESS
|CREATE_NEW_CONSOLE
)))
302 SetStdHandle( STD_INPUT_HANDLE
, current_startupinfo
.hStdInput
);
303 SetStdHandle( STD_OUTPUT_HANDLE
, current_startupinfo
.hStdOutput
);
304 SetStdHandle( STD_ERROR_HANDLE
, current_startupinfo
.hStdError
);
307 /* Now we can use the pthreads routines */
310 /* Copy the parent environment */
311 if (!(current_process
.env_db
= ENV_BuildEnvironment())) return FALSE
;
313 /* Parse command line arguments */
314 OPTIONS_ParseOptions( argv
);
316 while (argv
[app_argc
]) app_argc
++;
318 ret
= MAIN_MainInit();
320 if (create_flags
& CREATE_NEW_CONSOLE
)
326 /***********************************************************************
329 * Startup routine of a new process. Runs on the new process stack.
331 static void start_process(void)
333 int debugged
, console_app
;
334 LPTHREAD_START_ROUTINE entry
;
336 HFILE main_file
= main_exe_file
;
338 /* use original argv[0] as name for the main module */
339 if (!main_exe_name
[0])
341 if (!GetLongPathNameA( full_argv0
, main_exe_name
, sizeof(main_exe_name
) ))
342 lstrcpynA( main_exe_name
, full_argv0
, sizeof(main_exe_name
) );
347 UINT drive_type
= GetDriveTypeA( main_exe_name
);
348 /* don't keep the file handle open on removable media */
349 if (drive_type
== DRIVE_REMOVABLE
|| drive_type
== DRIVE_CDROM
) main_file
= 0;
352 /* Retrieve entry point address */
353 entry
= (LPTHREAD_START_ROUTINE
)((char*)current_process
.module
+
354 PE_HEADER(current_process
.module
)->OptionalHeader
.AddressOfEntryPoint
);
355 console_app
= (PE_HEADER(current_process
.module
)->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_CUI
);
356 if (console_app
) current_process
.flags
|= PDB32_CONSOLE_PROC
;
358 /* Signal the parent process to continue */
359 SERVER_START_REQ( init_process_done
)
361 req
->module
= (void *)current_process
.module
;
362 req
->module_size
= PE_HEADER(current_process
.module
)->OptionalHeader
.SizeOfImage
;
364 /* API requires a double indirection */
365 req
->name
= &main_exe_name_ptr
;
366 req
->exe_file
= main_file
;
367 req
->gui
= !console_app
;
368 wine_server_add_data( req
, main_exe_name
, strlen(main_exe_name
) );
369 wine_server_call( req
);
370 debugged
= reply
->debugged
;
374 /* Install signal handlers; this cannot be done before, since we cannot
375 * send exceptions to the debugger before the create process event that
376 * is sent by REQ_INIT_PROCESS_DONE */
377 if (!SIGNAL_Init()) goto error
;
379 /* create the main modref and load dependencies */
380 if (!(wm
= PE_CreateModule( current_process
.module
, main_exe_name
, 0, 0, FALSE
)))
384 if (main_exe_file
) CloseHandle( main_exe_file
); /* we no longer need it */
386 MODULE_DllProcessAttach( NULL
, (LPVOID
)1 );
388 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
389 * context of the parent process. Actually, the USER signal proc
390 * doesn't really care about that, but it *does* require that the
391 * startup parameters are correctly set up, so that GetProcessDword
392 * works. Furthermore, before calling the USER signal proc the
393 * 16-bit stack must be set up, which it is only after TASK_Create
394 * in the case of a 16-bit process. Thus, we send the signal here.
396 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE
, 0 );
397 PROCESS_CallUserSignalProc( USIG_THREAD_INIT
, 0 );
398 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT
, 0 );
399 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED
, 0 );
400 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
401 if (console_app
) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING
, 0 );
404 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
405 GetCurrentThreadId(), main_exe_name
, entry
);
406 if (debugged
) DbgBreakPoint();
407 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
408 * Dunno about other OSs */
409 SetLastError(0); /* clear error code */
410 ExitThread( entry(NULL
) );
413 ExitProcess( GetLastError() );
417 /***********************************************************************
420 * Try to open the Winelib app .so file based on argv[0] or WINEPRELOAD.
422 void *open_winelib_app( char *argv
[] )
429 if ((name
= getenv( "WINEPRELOAD" )))
431 if (!(ret
= wine_dll_load_main_exe( name
, 0, errStr
, sizeof(errStr
) )))
433 MESSAGE( "%s: could not load '%s' as specified in the WINEPRELOAD environment variable: %s\n",
434 argv
[0], name
, errStr
);
440 const char *argv0
= main_exe_name
;
443 /* if argv[0] is "wine", don't try to load anything */
445 if (!(name
= strrchr( argv0
, '/' ))) name
= argv0
;
447 if (!strcmp( name
, "wine" )) return NULL
;
450 /* now try argv[0] with ".so" appended */
451 if ((tmp
= HeapAlloc( GetProcessHeap(), 0, strlen(argv0
) + 4 )))
453 strcpy( tmp
, argv0
);
454 strcat( tmp
, ".so" );
455 /* search in PATH only if there was no '/' in argv[0] */
456 ret
= wine_dll_load_main_exe( tmp
, (name
== argv0
), errStr
, sizeof(errStr
) );
457 if (!ret
&& !argv
[1])
459 /* if no argv[1], this will be better than displaying usage */
460 MESSAGE( "%s: could not load library '%s' as Winelib application: %s\n",
461 argv
[0], tmp
, errStr
);
464 HeapFree( GetProcessHeap(), 0, tmp
);
470 /***********************************************************************
473 * Wine initialisation: load and start the main exe file.
475 void PROCESS_InitWine( int argc
, char *argv
[], LPSTR win16_exe_name
, HANDLE
*win16_exe_file
)
477 DWORD stack_size
= 0;
479 /* Initialize everything */
480 if (!process_init( argv
)) exit(1);
482 if (open_winelib_app( app_argv
)) goto found
; /* try to open argv[0] as a winelib app */
484 app_argv
++; /* remove argv[0] (wine itself) */
487 if (!main_exe_name
[0])
489 if (!app_argv
[0]) OPTIONS_Usage();
491 /* open the exe file */
492 if (!SearchPathA( NULL
, app_argv
[0], ".exe", sizeof(main_exe_name
), main_exe_name
, NULL
) &&
493 !SearchPathA( NULL
, app_argv
[0], NULL
, sizeof(main_exe_name
), main_exe_name
, NULL
))
495 MESSAGE( "%s: cannot find '%s'\n", argv0
, app_argv
[0] );
502 if ((main_exe_file
= CreateFileA( main_exe_name
, GENERIC_READ
, FILE_SHARE_READ
,
503 NULL
, OPEN_EXISTING
, 0, 0)) == INVALID_HANDLE_VALUE
)
505 MESSAGE( "%s: cannot open '%s'\n", argv0
, main_exe_name
);
510 /* first try Win32 format; this will fail if the file is not a PE binary */
511 if ((current_process
.module
= PE_LoadImage( main_exe_file
, main_exe_name
, 0 )))
513 if (PE_HEADER(current_process
.module
)->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
514 ExitProcess( ERROR_BAD_EXE_FORMAT
);
518 /* it must be 16-bit or DOS format */
519 NtCurrentTeb()->tibflags
&= ~TEBF_WIN32
;
520 current_process
.flags
|= PDB32_WIN16_PROC
;
521 strcpy( win16_exe_name
, main_exe_name
);
522 main_exe_name
[0] = 0;
523 *win16_exe_file
= main_exe_file
;
528 /* build command line */
529 if (!ENV_BuildCommandLine( app_argv
)) goto error
;
531 /* create 32-bit module for main exe */
532 if (!(current_process
.module
= BUILTIN32_LoadExeModule( current_process
.module
))) goto error
;
533 stack_size
= PE_HEADER(current_process
.module
)->OptionalHeader
.SizeOfStackReserve
;
535 /* allocate main thread stack */
536 if (!THREAD_InitStack( NtCurrentTeb(), stack_size
)) goto error
;
538 /* switch to the new stack */
539 SYSDEPS_SwitchToThreadStack( start_process
);
542 ExitProcess( GetLastError() );
546 /***********************************************************************
547 * __wine_get_main_args (NTDLL.@)
549 * Return the argc/argv that the application should see.
550 * Used by the startup code generated in the .spec.c file.
552 int __wine_get_main_args( char ***argv
)
559 /***********************************************************************
560 * __wine_get_wmain_args (NTDLL.@)
562 * Same as __wine_get_main_args but for Unicode.
564 int __wine_get_wmain_args( WCHAR
***argv
)
572 for (i
= 0; i
< app_argc
; i
++)
573 total
+= MultiByteToWideChar( CP_ACP
, 0, app_argv
[i
], -1, NULL
, 0 );
575 app_wargv
= HeapAlloc( GetProcessHeap(), 0,
576 total
* sizeof(WCHAR
) + (app_argc
+ 1) * sizeof(*app_wargv
) );
577 p
= (WCHAR
*)(app_wargv
+ app_argc
+ 1);
578 for (i
= 0; i
< app_argc
; i
++)
580 DWORD len
= MultiByteToWideChar( CP_ACP
, 0, app_argv
[i
], -1, p
, total
);
585 app_wargv
[app_argc
] = NULL
;
592 /***********************************************************************
595 * Build an argv array from a command-line.
596 * The command-line is modified to insert nulls.
597 * 'reserved' is the number of args to reserve before the first one.
599 static char **build_argv( char *cmdline
, int reserved
)
604 int in_quotes
,bcount
;
611 if (*s
=='\0' || ((*s
==' ' || *s
=='\t') && !in_quotes
)) {
614 /* skip the remaining spaces */
615 while (*s
==' ' || *s
=='\t') {
622 } else if (*s
=='\\') {
623 /* '\', count them */
625 } else if ((*s
=='"') && ((bcount
& 1)==0)) {
627 in_quotes
=!in_quotes
;
630 /* a regular character */
635 argv
=malloc(argc
*sizeof(*argv
));
644 if ((*s
==' ' || *s
=='\t') && !in_quotes
) {
645 /* Close the argument and copy it */
649 /* skip the remaining spaces */
652 } while (*s
==' ' || *s
=='\t');
654 /* Start with a new argument */
657 } else if (*s
=='\\') {
661 } else if (*s
=='"') {
663 if ((bcount
& 1)==0) {
664 /* Preceeded by an even number of '\', this is half that
665 * number of '\', plus a '"' which we discard.
669 in_quotes
=!in_quotes
;
671 /* Preceeded by an odd number of '\', this is half that
672 * number of '\' followed by a '"'
680 /* a regular character */
695 /***********************************************************************
698 * Build the environment of a new child process.
700 static char **build_envp( const char *env
, const char *extra_env
)
706 if (extra_env
) for (p
= extra_env
; *p
; count
++) p
+= strlen(p
) + 1;
707 for (p
= env
; *p
; count
++) p
+= strlen(p
) + 1;
710 if ((envp
= malloc( count
* sizeof(*envp
) )))
712 extern char **environ
;
713 char **envptr
= envp
;
714 char **unixptr
= environ
;
715 /* first the extra strings */
716 if (extra_env
) for (p
= extra_env
; *p
; p
+= strlen(p
) + 1) *envptr
++ = (char *)p
;
717 /* then put PATH, HOME and WINEPREFIX from the unix env */
718 for (unixptr
= environ
; unixptr
&& *unixptr
; unixptr
++)
719 if (!memcmp( *unixptr
, "PATH=", 5 ) ||
720 !memcmp( *unixptr
, "HOME=", 5 ) ||
721 !memcmp( *unixptr
, "WINEPREFIX=", 11 )) *envptr
++ = *unixptr
;
722 /* now put the Windows environment strings */
723 for (p
= env
; *p
; p
+= strlen(p
) + 1)
725 if (memcmp( p
, "PATH=", 5 ) &&
726 memcmp( p
, "HOME=", 5 ) &&
727 memcmp( p
, "WINEPRELOAD=", 12 ) &&
728 memcmp( p
, "WINEPREFIX=", 11 )) *envptr
++ = (char *)p
;
736 /***********************************************************************
739 * Locate the Wine binary to exec for a new Win32 process.
741 static void exec_wine_binary( char **argv
, char **envp
)
743 const char *path
, *pos
, *ptr
;
745 /* first, try for a WINELOADER environment variable */
746 argv
[0] = getenv("WINELOADER");
748 execve( argv
[0], argv
, envp
);
750 /* next, try bin directory */
751 argv
[0] = BINDIR
"/wine";
752 execve( argv
[0], argv
, envp
);
754 /* now try the path of argv0 of the current binary */
755 if (!(argv
[0] = malloc( strlen(full_argv0
) + 6 ))) return;
756 if ((ptr
= strrchr( full_argv0
, '/' )))
758 memcpy( argv
[0], full_argv0
, ptr
- full_argv0
);
759 strcpy( argv
[0] + (ptr
- full_argv0
), "/wine" );
760 execve( argv
[0], argv
, envp
);
764 /* now search in the Unix path */
765 if ((path
= getenv( "PATH" )))
767 if (!(argv
[0] = malloc( strlen(path
) + 6 ))) return;
771 while (*pos
== ':') pos
++;
773 if (!(ptr
= strchr( pos
, ':' ))) ptr
= pos
+ strlen(pos
);
774 memcpy( argv
[0], pos
, ptr
- pos
);
775 strcpy( argv
[0] + (ptr
- pos
), "/wine" );
776 execve( argv
[0], argv
, envp
);
782 /* finally try the current directory */
784 execve( argv
[0], argv
, envp
);
788 /***********************************************************************
791 * Fork and exec a new Unix process, checking for errors.
793 static int fork_and_exec( const char *filename
, char *cmdline
,
794 const char *env
, const char *newdir
)
798 char *extra_env
= NULL
;
802 env
= GetEnvironmentStringsA();
803 extra_env
= DRIVE_BuildEnv();
811 fcntl( fd
[1], F_SETFD
, 1 ); /* set close on exec */
812 if (!(pid
= fork())) /* child */
814 char **argv
= build_argv( cmdline
, filename
? 0 : 2 );
815 char **envp
= build_envp( env
, extra_env
);
818 if (newdir
) chdir(newdir
);
825 exec_wine_binary( argv
, envp
);
827 else execve( filename
, argv
, envp
);
830 write( fd
[1], &err
, sizeof(err
) );
834 if ((pid
!= -1) && (read( fd
[0], &err
, sizeof(err
) ) > 0)) /* exec failed */
839 if (pid
== -1) FILE_SetDosError();
841 if (extra_env
) HeapFree( GetProcessHeap(), 0, extra_env
);
846 /***********************************************************************
849 * Create a new process. If hFile is a valid handle we have an exe
850 * file, and we exec a new copy of wine to load it; otherwise we
851 * simply exec the specified filename as a Unix process.
853 BOOL
PROCESS_Create( HANDLE hFile
, LPCSTR filename
, LPSTR cmd_line
, LPCSTR env
,
854 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
855 BOOL inherit
, DWORD flags
, LPSTARTUPINFOA startup
,
856 LPPROCESS_INFORMATION info
, LPCSTR lpCurrentDirectory
)
859 const char *unixfilename
= NULL
;
860 const char *unixdir
= NULL
;
861 DOS_FULL_NAME full_dir
, full_name
;
862 HANDLE load_done_evt
= 0;
865 info
->hThread
= info
->hProcess
= 0;
866 info
->dwProcessId
= info
->dwThreadId
= 0;
868 if (lpCurrentDirectory
)
870 if (DOSFS_GetFullName( lpCurrentDirectory
, TRUE
, &full_dir
))
871 unixdir
= full_dir
.long_name
;
876 if (GetCurrentDirectoryA(sizeof(buf
),buf
))
878 if (DOSFS_GetFullName( buf
, TRUE
, &full_dir
))
879 unixdir
= full_dir
.long_name
;
883 /* create the process on the server side */
885 SERVER_START_REQ( new_process
)
889 req
->inherit_all
= inherit
;
890 req
->create_flags
= flags
;
891 req
->start_flags
= startup
->dwFlags
;
892 req
->exe_file
= hFile
;
893 if (startup
->dwFlags
& STARTF_USESTDHANDLES
)
895 req
->hstdin
= startup
->hStdInput
;
896 req
->hstdout
= startup
->hStdOutput
;
897 req
->hstderr
= startup
->hStdError
;
901 req
->hstdin
= GetStdHandle( STD_INPUT_HANDLE
);
902 req
->hstdout
= GetStdHandle( STD_OUTPUT_HANDLE
);
903 req
->hstderr
= GetStdHandle( STD_ERROR_HANDLE
);
905 req
->cmd_show
= startup
->wShowWindow
;
907 if (!hFile
) /* unix process */
909 unixfilename
= filename
;
910 if (DOSFS_GetFullName( filename
, TRUE
, &full_name
))
911 unixfilename
= full_name
.long_name
;
912 wine_server_add_data( req
, unixfilename
, strlen(unixfilename
) );
914 else /* new wine process */
916 if (GetLongPathNameA( filename
, buf
, MAX_PATH
))
917 wine_server_add_data( req
, buf
, strlen(buf
) );
919 wine_server_add_data( req
, filename
, strlen(filename
) );
921 ret
= !wine_server_call_err( req
);
922 process_info
= reply
->info
;
925 if (!ret
) return FALSE
;
927 /* fork and execute */
929 if (fork_and_exec( unixfilename
, cmd_line
, env
, unixdir
) == -1)
931 CloseHandle( process_info
);
935 /* wait for the new process info to be ready */
937 ret
= TRUE
; /* pretend success even if we don't get the new process info */
938 if (WaitForSingleObject( process_info
, 2000 ) == STATUS_WAIT_0
)
940 SERVER_START_REQ( get_new_process_info
)
942 req
->info
= process_info
;
943 req
->pinherit
= (psa
&& (psa
->nLength
>= sizeof(*psa
)) && psa
->bInheritHandle
);
944 req
->tinherit
= (tsa
&& (tsa
->nLength
>= sizeof(*tsa
)) && tsa
->bInheritHandle
);
945 if ((ret
= !wine_server_call_err( req
)))
947 info
->dwProcessId
= (DWORD
)reply
->pid
;
948 info
->dwThreadId
= (DWORD
)reply
->tid
;
949 info
->hProcess
= reply
->phandle
;
950 info
->hThread
= reply
->thandle
;
951 load_done_evt
= reply
->event
;
956 CloseHandle( process_info
);
957 if (!ret
) return FALSE
;
959 /* Wait until process is initialized (or initialization failed) */
965 handles
[0] = info
->hProcess
;
966 handles
[1] = load_done_evt
;
967 res
= WaitForMultipleObjects( 2, handles
, FALSE
, INFINITE
);
968 CloseHandle( load_done_evt
);
969 if (res
== STATUS_WAIT_0
) /* the process died */
972 if (GetExitCodeProcess( info
->hProcess
, &exitcode
)) SetLastError( exitcode
);
973 CloseHandle( info
->hThread
);
974 CloseHandle( info
->hProcess
);
982 /***********************************************************************
983 * ExitProcess (KERNEL32.@)
985 void WINAPI
ExitProcess( DWORD status
)
987 MODULE_DllProcessDetach( TRUE
, (LPVOID
)1 );
988 SERVER_START_REQ( terminate_process
)
990 /* send the exit code to the server */
991 req
->handle
= GetCurrentProcess();
992 req
->exit_code
= status
;
993 wine_server_call( req
);
999 /***********************************************************************
1000 * ExitProcess (KERNEL.466)
1002 void WINAPI
ExitProcess16( WORD status
)
1005 ReleaseThunkLock( &count
);
1006 ExitProcess( status
);
1009 /******************************************************************************
1010 * TerminateProcess (KERNEL32.@)
1012 BOOL WINAPI
TerminateProcess( HANDLE handle
, DWORD exit_code
)
1014 NTSTATUS status
= NtTerminateProcess( handle
, exit_code
);
1015 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
1020 /***********************************************************************
1021 * GetProcessDword (KERNEL.485)
1022 * GetProcessDword (KERNEL32.18)
1023 * 'Of course you cannot directly access Windows internal structures'
1025 DWORD WINAPI
GetProcessDword( DWORD dwProcessID
, INT offset
)
1029 TRACE_(win32
)("(%ld, %d)\n", dwProcessID
, offset
);
1031 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
1033 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
1039 case GPD_APP_COMPAT_FLAGS
:
1040 return GetAppCompatFlags16(0);
1042 case GPD_LOAD_DONE_EVENT
:
1043 return current_process
.load_done_evt
;
1045 case GPD_HINSTANCE16
:
1046 return GetTaskDS16();
1048 case GPD_WINDOWS_VERSION
:
1049 return GetExeVersion16();
1052 return (DWORD
)NtCurrentTeb() - 0x10 /* FIXME */;
1055 return (DWORD
)¤t_process
;
1057 case GPD_STARTF_SHELLDATA
: /* return stdoutput handle from startupinfo ??? */
1058 return current_startupinfo
.hStdOutput
;
1060 case GPD_STARTF_HOTKEY
: /* return stdinput handle from startupinfo ??? */
1061 return current_startupinfo
.hStdInput
;
1063 case GPD_STARTF_SHOWWINDOW
:
1064 return current_startupinfo
.wShowWindow
;
1066 case GPD_STARTF_SIZE
:
1067 x
= current_startupinfo
.dwXSize
;
1068 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
1069 y
= current_startupinfo
.dwYSize
;
1070 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
1071 return MAKELONG( x
, y
);
1073 case GPD_STARTF_POSITION
:
1074 x
= current_startupinfo
.dwX
;
1075 if ( (INT
)x
== CW_USEDEFAULT
) x
= CW_USEDEFAULT16
;
1076 y
= current_startupinfo
.dwY
;
1077 if ( (INT
)y
== CW_USEDEFAULT
) y
= CW_USEDEFAULT16
;
1078 return MAKELONG( x
, y
);
1080 case GPD_STARTF_FLAGS
:
1081 return current_startupinfo
.dwFlags
;
1087 return current_process
.flags
;
1090 return current_process
.process_dword
;
1093 ERR_(win32
)("Unknown offset %d\n", offset
);
1098 /***********************************************************************
1099 * SetProcessDword (KERNEL.484)
1100 * 'Of course you cannot directly access Windows internal structures'
1102 void WINAPI
SetProcessDword( DWORD dwProcessID
, INT offset
, DWORD value
)
1104 TRACE_(win32
)("(%ld, %d)\n", dwProcessID
, offset
);
1106 if (dwProcessID
&& dwProcessID
!= GetCurrentProcessId())
1108 ERR("%d: process %lx not accessible\n", offset
, dwProcessID
);
1114 case GPD_APP_COMPAT_FLAGS
:
1115 case GPD_LOAD_DONE_EVENT
:
1116 case GPD_HINSTANCE16
:
1117 case GPD_WINDOWS_VERSION
:
1120 case GPD_STARTF_SHELLDATA
:
1121 case GPD_STARTF_HOTKEY
:
1122 case GPD_STARTF_SHOWWINDOW
:
1123 case GPD_STARTF_SIZE
:
1124 case GPD_STARTF_POSITION
:
1125 case GPD_STARTF_FLAGS
:
1128 ERR_(win32
)("Not allowed to modify offset %d\n", offset
);
1132 current_process
.process_dword
= value
;
1136 ERR_(win32
)("Unknown offset %d\n", offset
);
1142 /*********************************************************************
1143 * OpenProcess (KERNEL32.@)
1145 HANDLE WINAPI
OpenProcess( DWORD access
, BOOL inherit
, DWORD id
)
1148 SERVER_START_REQ( open_process
)
1150 req
->pid
= (void *)id
;
1151 req
->access
= access
;
1152 req
->inherit
= inherit
;
1153 if (!wine_server_call_err( req
)) ret
= reply
->handle
;
1159 /*********************************************************************
1160 * MapProcessHandle (KERNEL.483)
1162 DWORD WINAPI
MapProcessHandle( HANDLE handle
)
1165 SERVER_START_REQ( get_process_info
)
1167 req
->handle
= handle
;
1168 if (!wine_server_call_err( req
)) ret
= (DWORD
)reply
->pid
;
1174 /***********************************************************************
1175 * SetPriorityClass (KERNEL32.@)
1177 BOOL WINAPI
SetPriorityClass( HANDLE hprocess
, DWORD priorityclass
)
1180 SERVER_START_REQ( set_process_info
)
1182 req
->handle
= hprocess
;
1183 req
->priority
= priorityclass
;
1184 req
->mask
= SET_PROCESS_INFO_PRIORITY
;
1185 ret
= !wine_server_call_err( req
);
1192 /***********************************************************************
1193 * GetPriorityClass (KERNEL32.@)
1195 DWORD WINAPI
GetPriorityClass(HANDLE hprocess
)
1198 SERVER_START_REQ( get_process_info
)
1200 req
->handle
= hprocess
;
1201 if (!wine_server_call_err( req
)) ret
= reply
->priority
;
1208 /***********************************************************************
1209 * SetProcessAffinityMask (KERNEL32.@)
1211 BOOL WINAPI
SetProcessAffinityMask( HANDLE hProcess
, DWORD affmask
)
1214 SERVER_START_REQ( set_process_info
)
1216 req
->handle
= hProcess
;
1217 req
->affinity
= affmask
;
1218 req
->mask
= SET_PROCESS_INFO_AFFINITY
;
1219 ret
= !wine_server_call_err( req
);
1225 /**********************************************************************
1226 * GetProcessAffinityMask (KERNEL32.@)
1228 BOOL WINAPI
GetProcessAffinityMask( HANDLE hProcess
,
1229 LPDWORD lpProcessAffinityMask
,
1230 LPDWORD lpSystemAffinityMask
)
1233 SERVER_START_REQ( get_process_info
)
1235 req
->handle
= hProcess
;
1236 if (!wine_server_call_err( req
))
1238 if (lpProcessAffinityMask
) *lpProcessAffinityMask
= reply
->process_affinity
;
1239 if (lpSystemAffinityMask
) *lpSystemAffinityMask
= reply
->system_affinity
;
1248 /***********************************************************************
1249 * GetProcessVersion (KERNEL32.@)
1251 DWORD WINAPI
GetProcessVersion( DWORD processid
)
1253 IMAGE_NT_HEADERS
*nt
;
1255 if (processid
&& processid
!= GetCurrentProcessId())
1257 FIXME("should use ReadProcessMemory\n");
1260 if ((nt
= RtlImageNtHeader( current_process
.module
)))
1261 return ((nt
->OptionalHeader
.MajorSubsystemVersion
<< 16) |
1262 nt
->OptionalHeader
.MinorSubsystemVersion
);
1266 /***********************************************************************
1267 * GetProcessFlags (KERNEL32.@)
1269 DWORD WINAPI
GetProcessFlags( DWORD processid
)
1271 if (processid
&& processid
!= GetCurrentProcessId()) return 0;
1272 return current_process
.flags
;
1276 /***********************************************************************
1277 * SetProcessWorkingSetSize [KERNEL32.@]
1278 * Sets the min/max working set sizes for a specified process.
1281 * hProcess [I] Handle to the process of interest
1282 * minset [I] Specifies minimum working set size
1283 * maxset [I] Specifies maximum working set size
1287 BOOL WINAPI
SetProcessWorkingSetSize(HANDLE hProcess
,DWORD minset
,
1290 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess
,minset
,maxset
);
1291 if(( minset
== (DWORD
)-1) && (maxset
== (DWORD
)-1)) {
1292 /* Trim the working set to zero */
1293 /* Swap the process out of physical RAM */
1298 /***********************************************************************
1299 * GetProcessWorkingSetSize (KERNEL32.@)
1301 BOOL WINAPI
GetProcessWorkingSetSize(HANDLE hProcess
,LPDWORD minset
,
1304 FIXME("(0x%08x,%p,%p): stub\n",hProcess
,minset
,maxset
);
1305 /* 32 MB working set size */
1306 if (minset
) *minset
= 32*1024*1024;
1307 if (maxset
) *maxset
= 32*1024*1024;
1311 /***********************************************************************
1312 * SetProcessShutdownParameters (KERNEL32.@)
1314 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1315 * Now tracks changes made (but does not act on these changes)
1317 static DWORD shutdown_flags
= 0;
1318 static DWORD shutdown_priority
= 0x280;
1320 BOOL WINAPI
SetProcessShutdownParameters(DWORD level
, DWORD flags
)
1322 FIXME("(%08lx, %08lx): partial stub.\n", level
, flags
);
1323 shutdown_flags
= flags
;
1324 shutdown_priority
= level
;
1329 /***********************************************************************
1330 * GetProcessShutdownParameters (KERNEL32.@)
1333 BOOL WINAPI
GetProcessShutdownParameters( LPDWORD lpdwLevel
, LPDWORD lpdwFlags
)
1335 *lpdwLevel
= shutdown_priority
;
1336 *lpdwFlags
= shutdown_flags
;
1341 /***********************************************************************
1342 * SetProcessPriorityBoost (KERNEL32.@)
1344 BOOL WINAPI
SetProcessPriorityBoost(HANDLE hprocess
,BOOL disableboost
)
1346 FIXME("(%d,%d): stub\n",hprocess
,disableboost
);
1347 /* Say we can do it. I doubt the program will notice that we don't. */
1352 /***********************************************************************
1353 * ReadProcessMemory (KERNEL32.@)
1355 BOOL WINAPI
ReadProcessMemory( HANDLE process
, LPCVOID addr
, LPVOID buffer
, DWORD size
,
1356 LPDWORD bytes_read
)
1360 SERVER_START_REQ( read_process_memory
)
1362 req
->handle
= process
;
1363 req
->addr
= (void *)addr
;
1364 wine_server_set_reply( req
, buffer
, size
);
1365 if ((res
= wine_server_call_err( req
))) size
= 0;
1368 if (bytes_read
) *bytes_read
= size
;
1373 /***********************************************************************
1374 * WriteProcessMemory (KERNEL32.@)
1376 BOOL WINAPI
WriteProcessMemory( HANDLE process
, LPVOID addr
, LPCVOID buffer
, DWORD size
,
1377 LPDWORD bytes_written
)
1379 static const int zero
;
1380 unsigned int first_offset
, last_offset
, first_mask
, last_mask
;
1385 SetLastError( ERROR_INVALID_PARAMETER
);
1389 /* compute the mask for the first int */
1391 first_offset
= (unsigned int)addr
% sizeof(int);
1392 memset( &first_mask
, 0, first_offset
);
1394 /* compute the mask for the last int */
1395 last_offset
= (size
+ first_offset
) % sizeof(int);
1397 memset( &last_mask
, 0xff, last_offset
? last_offset
: sizeof(int) );
1399 SERVER_START_REQ( write_process_memory
)
1401 req
->handle
= process
;
1402 req
->addr
= (char *)addr
- first_offset
;
1403 req
->first_mask
= first_mask
;
1404 req
->last_mask
= last_mask
;
1405 if (first_offset
) wine_server_add_data( req
, &zero
, first_offset
);
1406 wine_server_add_data( req
, buffer
, size
);
1407 if (last_offset
) wine_server_add_data( req
, &zero
, sizeof(int) - last_offset
);
1409 if ((res
= wine_server_call_err( req
))) size
= 0;
1412 if (bytes_written
) *bytes_written
= size
;
1416 ReadProcessMemory( process
, addr
, dummy
, sizeof(dummy
), &read
);
1422 /***********************************************************************
1423 * RegisterServiceProcess (KERNEL.491)
1424 * RegisterServiceProcess (KERNEL32.@)
1426 * A service process calls this function to ensure that it continues to run
1427 * even after a user logged off.
1429 DWORD WINAPI
RegisterServiceProcess(DWORD dwProcessId
, DWORD dwType
)
1431 /* I don't think that Wine needs to do anything in that function */
1432 return 1; /* success */
1435 /***********************************************************************
1436 * GetExitCodeProcess [KERNEL32.@]
1438 * Gets termination status of specified process
1444 BOOL WINAPI
GetExitCodeProcess(
1445 HANDLE hProcess
, /* [in] handle to the process */
1446 LPDWORD lpExitCode
) /* [out] address to receive termination status */
1449 SERVER_START_REQ( get_process_info
)
1451 req
->handle
= hProcess
;
1452 ret
= !wine_server_call_err( req
);
1453 if (ret
&& lpExitCode
) *lpExitCode
= reply
->exit_code
;
1460 /***********************************************************************
1461 * SetErrorMode (KERNEL32.@)
1463 UINT WINAPI
SetErrorMode( UINT mode
)
1465 UINT old
= current_process
.error_mode
;
1466 current_process
.error_mode
= mode
;
1471 /**************************************************************************
1472 * SetFileApisToOEM (KERNEL32.@)
1474 VOID WINAPI
SetFileApisToOEM(void)
1476 current_process
.flags
|= PDB32_FILE_APIS_OEM
;
1480 /**************************************************************************
1481 * SetFileApisToANSI (KERNEL32.@)
1483 VOID WINAPI
SetFileApisToANSI(void)
1485 current_process
.flags
&= ~PDB32_FILE_APIS_OEM
;
1489 /******************************************************************************
1490 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1493 * TRUE: Set of file functions is using ANSI code page
1494 * FALSE: Set of file functions is using OEM code page
1496 BOOL WINAPI
AreFileApisANSI(void)
1498 return !(current_process
.flags
& PDB32_FILE_APIS_OEM
);
1502 /**********************************************************************
1503 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1505 * Allocates a thread local storage index
1508 * Success: TLS Index
1509 * Failure: 0xFFFFFFFF
1511 DWORD WINAPI
TlsAlloc( void )
1513 DWORD i
, mask
, ret
= 0;
1514 DWORD
*bits
= current_process
.tls_bits
;
1515 RtlAcquirePebLock();
1516 if (*bits
== 0xffffffff)
1520 if (*bits
== 0xffffffff)
1522 RtlReleasePebLock();
1523 SetLastError( ERROR_NO_MORE_ITEMS
);
1527 for (i
= 0, mask
= 1; i
< 32; i
++, mask
<<= 1) if (!(*bits
& mask
)) break;
1529 RtlReleasePebLock();
1530 NtCurrentTeb()->tls_array
[ret
+i
] = 0; /* clear the value */
1535 /**********************************************************************
1536 * TlsFree [KERNEL32.@] Releases a TLS index.
1538 * Releases a thread local storage index, making it available for reuse
1544 BOOL WINAPI
TlsFree(
1545 DWORD index
) /* [in] TLS Index to free */
1547 DWORD mask
= (1 << (index
& 31));
1548 DWORD
*bits
= current_process
.tls_bits
;
1551 SetLastError( ERROR_INVALID_PARAMETER
);
1554 if (index
>= 32) bits
++;
1555 RtlAcquirePebLock();
1556 if (!(*bits
& mask
)) /* already free? */
1558 RtlReleasePebLock();
1559 SetLastError( ERROR_INVALID_PARAMETER
);
1563 NtCurrentTeb()->tls_array
[index
] = 0;
1564 /* FIXME: should zero all other thread values */
1565 RtlReleasePebLock();
1570 /**********************************************************************
1571 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1574 * Success: Value stored in calling thread's TLS slot for index
1575 * Failure: 0 and GetLastError returns NO_ERROR
1577 LPVOID WINAPI
TlsGetValue(
1578 DWORD index
) /* [in] TLS index to retrieve value for */
1582 SetLastError( ERROR_INVALID_PARAMETER
);
1585 SetLastError( ERROR_SUCCESS
);
1586 return NtCurrentTeb()->tls_array
[index
];
1590 /**********************************************************************
1591 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1597 BOOL WINAPI
TlsSetValue(
1598 DWORD index
, /* [in] TLS index to set value for */
1599 LPVOID value
) /* [in] Value to be stored */
1603 SetLastError( ERROR_INVALID_PARAMETER
);
1606 NtCurrentTeb()->tls_array
[index
] = value
;
1611 /***********************************************************************
1612 * GetCurrentProcess (KERNEL32.@)
1614 #undef GetCurrentProcess
1615 HANDLE WINAPI
GetCurrentProcess(void)