Remove .so extension from main module file name after loading it so
[wine/multimedia.git] / scheduler / process.c
blob5fc5f495455296d6de927589b8902d51314bdb21
1 /*
2 * Win32 processes
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include "wine/winbase16.h"
34 #include "wine/winuser16.h"
35 #include "wine/exception.h"
36 #include "wine/library.h"
37 #include "drive.h"
38 #include "module.h"
39 #include "file.h"
40 #include "heap.h"
41 #include "thread.h"
42 #include "winerror.h"
43 #include "wincon.h"
44 #include "wine/server.h"
45 #include "options.h"
46 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(process);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
50 WINE_DECLARE_DEBUG_CHANNEL(snoop);
51 WINE_DECLARE_DEBUG_CHANNEL(win32);
53 struct _ENVDB;
55 /* Win32 process database */
56 typedef struct _PDB
58 LONG header[2]; /* 00 Kernel object header */
59 HMODULE module; /* 08 Main exe module (NT) */
60 void *event; /* 0c Pointer to an event object (unused) */
61 DWORD exit_code; /* 10 Process exit code */
62 DWORD unknown2; /* 14 Unknown */
63 HANDLE heap; /* 18 Default process heap */
64 HANDLE mem_context; /* 1c Process memory context */
65 DWORD flags; /* 20 Flags */
66 void *pdb16; /* 24 DOS PSP */
67 WORD PSP_sel; /* 28 Selector to DOS PSP */
68 WORD imte; /* 2a IMTE for the process module */
69 WORD threads; /* 2c Number of threads */
70 WORD running_threads; /* 2e Number of running threads */
71 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
72 WORD ring0_threads; /* 32 Number of ring 0 threads */
73 HANDLE system_heap; /* 34 System heap to allocate handles */
74 HTASK task; /* 38 Win16 task */
75 void *mem_map_files; /* 3c Pointer to mem-mapped files */
76 struct _ENVDB *env_db; /* 40 Environment database */
77 void *handle_table; /* 44 Handle table */
78 struct _PDB *parent; /* 48 Parent process */
79 void *modref_list; /* 4c MODREF list */
80 void *thread_list; /* 50 List of threads */
81 void *debuggee_CB; /* 54 Debuggee context block */
82 void *local_heap_free; /* 58 Head of local heap free list */
83 DWORD unknown4; /* 5c Unknown */
84 CRITICAL_SECTION crit_section; /* 60 Critical section */
85 DWORD unknown5[3]; /* 78 Unknown */
86 void *console; /* 84 Console */
87 DWORD tls_bits[2]; /* 88 TLS in-use bits */
88 DWORD process_dword; /* 90 Unknown */
89 struct _PDB *group; /* 94 Process group */
90 void *exe_modref; /* 98 MODREF for the process EXE */
91 void *top_filter; /* 9c Top exception filter */
92 DWORD priority; /* a0 Priority level */
93 HANDLE heap_list; /* a4 Head of process heap list */
94 void *heap_handles; /* a8 Head of heap handles list */
95 DWORD unknown6; /* ac Unknown */
96 void *console_provider; /* b0 Console provider (??) */
97 WORD env_selector; /* b4 Selector to process environment */
98 WORD error_mode; /* b6 Error mode */
99 HANDLE load_done_evt; /* b8 Event for process loading done */
100 void *UTState; /* bc Head of Univeral Thunk list */
101 DWORD unknown8; /* c0 Unknown (NT) */
102 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
103 } PDB;
105 PDB current_process;
107 /* Process flags */
108 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
109 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
110 #define PDB32_DOS_PROC 0x0010 /* Dos process */
111 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
112 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
113 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
115 static char main_exe_name[MAX_PATH];
116 static char *main_exe_name_ptr = main_exe_name;
117 static HANDLE main_exe_file;
118 static int main_create_flags;
120 static unsigned int server_startticks;
122 /* memory/environ.c */
123 extern struct _ENVDB *ENV_InitStartupInfo( size_t info_size, char *main_exe_name,
124 size_t main_exe_size );
125 extern BOOL ENV_BuildCommandLine( char **argv );
126 extern STARTUPINFOA current_startupinfo;
128 /* scheduler/pthread.c */
129 extern void PTHREAD_init_done(void);
131 extern void RELAY_InitDebugLists(void);
132 extern BOOL MAIN_MainInit(void);
134 typedef WORD (WINAPI *pUserSignalProc)( UINT, DWORD, DWORD, HMODULE16 );
136 /***********************************************************************
137 * PROCESS_CallUserSignalProc
139 * FIXME: Some of the signals aren't sent correctly!
141 * The exact meaning of the USER signals is undocumented, but this
142 * should cover the basic idea:
144 * USIG_DLL_UNLOAD_WIN16
145 * This is sent when a 16-bit module is unloaded.
147 * USIG_DLL_UNLOAD_WIN32
148 * This is sent when a 32-bit module is unloaded.
150 * USIG_DLL_UNLOAD_ORPHANS
151 * This is sent after the last Win3.1 module is unloaded,
152 * to allow removal of orphaned menus.
154 * USIG_FAULT_DIALOG_PUSH
155 * USIG_FAULT_DIALOG_POP
156 * These are called to allow USER to prepare for displaying a
157 * fault dialog, even though the fault might have happened while
158 * inside a USER critical section.
160 * USIG_THREAD_INIT
161 * This is called from the context of a new thread, as soon as it
162 * has started to run.
164 * USIG_THREAD_EXIT
165 * This is called, still in its context, just before a thread is
166 * about to terminate.
168 * USIG_PROCESS_CREATE
169 * This is called, in the parent process context, after a new process
170 * has been created.
172 * USIG_PROCESS_INIT
173 * This is called in the new process context, just after the main thread
174 * has started execution (after the main thread's USIG_THREAD_INIT has
175 * been sent).
177 * USIG_PROCESS_LOADED
178 * This is called after the executable file has been loaded into the
179 * new process context.
181 * USIG_PROCESS_RUNNING
182 * This is called immediately before the main entry point is called.
184 * USIG_PROCESS_EXIT
185 * This is called in the context of a process that is about to
186 * terminate (but before the last thread's USIG_THREAD_EXIT has
187 * been sent).
189 * USIG_PROCESS_DESTROY
190 * This is called after a process has terminated.
193 * The meaning of the dwFlags bits is as follows:
195 * USIG_FLAGS_WIN32
196 * Current process is 32-bit.
198 * USIG_FLAGS_GUI
199 * Current process is a (Win32) GUI process.
201 * USIG_FLAGS_FEEDBACK
202 * Current process needs 'feedback' (determined from the STARTUPINFO
203 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
205 * USIG_FLAGS_FAULT
206 * The signal is being sent due to a fault.
208 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
210 DWORD dwFlags = 0;
211 HMODULE user;
212 pUserSignalProc proc;
214 if (!(user = GetModuleHandleA( "user32.dll" ))) return;
215 if (!(proc = (pUserSignalProc)GetProcAddress( user, "UserSignalProc" ))) return;
217 /* Determine dwFlags */
219 if ( !(current_process.flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
220 if ( !(current_process.flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
222 if ( dwFlags & USIG_FLAGS_GUI )
224 /* Feedback defaults to ON */
225 if ( !(current_startupinfo.dwFlags & STARTF_FORCEOFFFEEDBACK) )
226 dwFlags |= USIG_FLAGS_FEEDBACK;
228 else
230 /* Feedback defaults to OFF */
231 if (current_startupinfo.dwFlags & STARTF_FORCEONFEEDBACK)
232 dwFlags |= USIG_FLAGS_FEEDBACK;
235 /* Call USER signal proc */
237 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
238 proc( uCode, GetCurrentThreadId(), dwFlags, hModule );
239 else
240 proc( uCode, GetCurrentProcessId(), dwFlags, hModule );
244 /***********************************************************************
245 * get_basename
247 inline static const char *get_basename( const char *name )
249 char *p;
251 if ((p = strrchr( name, '/' ))) name = p + 1;
252 if ((p = strrchr( name, '\\' ))) name = p + 1;
253 return name;
257 /***********************************************************************
258 * open_exe_file
260 * Open an exe file, taking load order into account.
261 * Returns the file handle or 0 for a builtin exe.
263 static HANDLE open_exe_file( const char *name )
265 enum loadorder_type loadorder[LOADORDER_NTYPES];
266 HANDLE handle;
267 int i;
269 SetLastError( ERROR_FILE_NOT_FOUND );
270 MODULE_GetLoadOrder( loadorder, name, TRUE );
272 for(i = 0; i < LOADORDER_NTYPES; i++)
274 if (loadorder[i] == LOADORDER_INVALID) break;
275 switch(loadorder[i])
277 case LOADORDER_DLL:
278 TRACE( "Trying native exe %s\n", debugstr_a(name) );
279 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
280 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
281 return handle;
282 if (GetLastError() != ERROR_FILE_NOT_FOUND) return INVALID_HANDLE_VALUE;
283 break;
284 case LOADORDER_BI:
285 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
286 if (wine_dll_load_main_exe( get_basename(name), NULL, 0, 1 )) return 0;
287 break;
288 default:
289 break;
292 return INVALID_HANDLE_VALUE;
296 /***********************************************************************
297 * find_exe_file
299 * Open an exe file, and return the full name and file handle.
300 * Returns FALSE if file could not be found.
301 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
302 * If file is a builtin exe, returns TRUE and sets handle to 0.
304 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
306 enum loadorder_type loadorder[LOADORDER_NTYPES];
307 int i;
309 TRACE("looking for %s\n", debugstr_a(name) );
311 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ))
313 *handle = open_exe_file( buffer );
314 return TRUE;
317 /* no such file in path, try builtin with .exe extension */
319 lstrcpynA( buffer, get_basename(name), buflen );
320 if (!strchr( buffer, '.' ))
322 char *p = buffer + strlen(buffer);
323 lstrcpynA( p, ".exe", buflen - (p - buffer) );
326 MODULE_GetLoadOrder( loadorder, buffer, TRUE );
327 for (i = 0; i < LOADORDER_NTYPES; i++)
329 if (loadorder[i] == LOADORDER_BI)
331 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
332 if (wine_dll_load_main_exe( buffer, NULL, 0, 1 ))
334 *handle = 0;
335 return TRUE;
337 break;
339 if (loadorder[i] == LOADORDER_INVALID) break;
342 /* no builtin found, try native without extension in case it is a Unix app */
344 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
346 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
347 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
348 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
349 return TRUE;
351 return FALSE;
355 /***********************************************************************
356 * process_init
358 * Main process initialisation code
360 static BOOL process_init( char *argv[] )
362 BOOL ret;
363 size_t info_size = 0;
365 /* store the program name */
366 argv0 = argv[0];
368 /* Fill the initial process structure */
369 current_process.exit_code = STILL_ACTIVE;
370 current_process.threads = 1;
371 current_process.running_threads = 1;
372 current_process.ring0_threads = 1;
373 current_process.group = &current_process;
374 current_process.priority = 8; /* Normal */
376 /* Setup the server connection */
377 CLIENT_InitServer();
379 /* Retrieve startup info from the server */
380 SERVER_START_REQ( init_process )
382 req->ldt_copy = &wine_ldt_copy;
383 req->ppid = getppid();
384 if ((ret = !wine_server_call_err( req )))
386 main_exe_file = reply->exe_file;
387 main_create_flags = reply->create_flags;
388 info_size = reply->info_size;
389 server_startticks = reply->server_start;
390 current_startupinfo.hStdInput = reply->hstdin;
391 current_startupinfo.hStdOutput = reply->hstdout;
392 current_startupinfo.hStdError = reply->hstderr;
395 SERVER_END_REQ;
396 if (!ret) return FALSE;
398 /* Create the process heap */
399 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
401 if (main_create_flags == 0 &&
402 current_startupinfo.hStdInput == 0 &&
403 current_startupinfo.hStdOutput == 0 &&
404 current_startupinfo.hStdError == 0)
406 /* no parent, and no new console requested, create a simple console with bare handles to
407 * unix stdio input & output streams (aka simple console)
409 HANDLE handle;
410 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &handle );
411 SetStdHandle( STD_INPUT_HANDLE, handle );
412 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
413 SetStdHandle( STD_OUTPUT_HANDLE, handle );
414 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
415 SetStdHandle( STD_ERROR_HANDLE, handle );
417 else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
419 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
420 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
421 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
424 /* Now we can use the pthreads routines */
425 PTHREAD_init_done();
427 /* Copy the parent environment */
428 if (!(current_process.env_db = ENV_InitStartupInfo( info_size, main_exe_name,
429 sizeof(main_exe_name) )))
430 return FALSE;
432 /* Parse command line arguments */
433 OPTIONS_ParseOptions( !info_size ? argv : NULL );
435 ret = MAIN_MainInit();
436 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
438 return ret;
442 /***********************************************************************
443 * start_process
445 * Startup routine of a new process. Runs on the new process stack.
447 static void start_process(void)
449 int debugged, console_app;
450 LPTHREAD_START_ROUTINE entry;
451 WINE_MODREF *wm;
452 HANDLE main_file = main_exe_file;
454 /* use original argv[0] as name for the main module */
455 if (!main_exe_name[0])
457 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
458 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
461 if (main_file)
463 UINT drive_type = GetDriveTypeA( main_exe_name );
464 /* don't keep the file handle open on removable media */
465 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
468 /* Retrieve entry point address */
469 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
470 PE_HEADER(current_process.module)->OptionalHeader.AddressOfEntryPoint);
471 console_app = (PE_HEADER(current_process.module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
472 if (console_app)
474 current_process.flags |= PDB32_CONSOLE_PROC;
475 if (main_create_flags & CREATE_NEW_CONSOLE) AllocConsole();
478 /* Signal the parent process to continue */
479 SERVER_START_REQ( init_process_done )
481 req->module = (void *)current_process.module;
482 req->module_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfImage;
483 req->entry = entry;
484 /* API requires a double indirection */
485 req->name = &main_exe_name_ptr;
486 req->exe_file = main_file;
487 req->gui = !console_app;
488 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
489 wine_server_call( req );
490 debugged = reply->debugged;
492 SERVER_END_REQ;
494 /* Install signal handlers; this cannot be done before, since we cannot
495 * send exceptions to the debugger before the create process event that
496 * is sent by REQ_INIT_PROCESS_DONE */
497 if (!SIGNAL_Init()) goto error;
499 /* create the main modref and load dependencies */
500 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
501 goto error;
502 wm->refCount++;
504 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
506 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
508 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
509 * context of the parent process. Actually, the USER signal proc
510 * doesn't really care about that, but it *does* require that the
511 * startup parameters are correctly set up, so that GetProcessDword
512 * works. Furthermore, before calling the USER signal proc the
513 * 16-bit stack must be set up, which it is only after TASK_Create
514 * in the case of a 16-bit process. Thus, we send the signal here.
516 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
517 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
518 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
519 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
520 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
521 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
523 if (TRACE_ON(relay))
524 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
525 GetCurrentThreadId(), main_exe_name, entry );
526 if (debugged) DbgBreakPoint();
527 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
528 * Dunno about other OSs */
529 SetLastError(0); /* clear error code */
530 ExitThread( entry(NULL) );
532 error:
533 ExitProcess( GetLastError() );
537 /***********************************************************************
538 * PROCESS_InitWine
540 * Wine initialisation: load and start the main exe file.
542 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
544 char error[100], *p;
545 DWORD stack_size = 0;
547 /* Initialize everything */
548 if (!process_init( argv )) exit(1);
550 argv++; /* remove argv[0] (wine itself) */
552 TRACE( "starting process name=%s file=%x argv[0]=%s\n",
553 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
555 if (!main_exe_name[0])
557 if (!argv[0]) OPTIONS_Usage();
559 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
561 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
562 ExitProcess(1);
564 if (main_exe_file == INVALID_HANDLE_VALUE)
566 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
567 ExitProcess(1);
571 if (!main_exe_file) /* no file handle -> Winelib app */
573 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
574 if (wine_dll_load_main_exe( get_basename(main_exe_name), error, sizeof(error), 0 ))
575 goto found;
576 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
577 ExitProcess(1);
580 switch( MODULE_GetBinaryType( main_exe_file ))
582 case BINARY_PE_EXE:
583 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
584 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
585 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
586 ExitProcess(1);
587 case BINARY_PE_DLL:
588 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
589 ExitProcess(1);
590 case BINARY_UNKNOWN:
591 /* check for .com extension */
592 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
594 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
595 ExitProcess(1);
597 /* fall through */
598 case BINARY_WIN16:
599 case BINARY_DOS:
600 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
601 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
602 current_process.flags |= PDB32_WIN16_PROC;
603 strcpy( win16_exe_name, main_exe_name );
604 main_exe_name[0] = 0;
605 *win16_exe_file = main_exe_file;
606 main_exe_file = 0;
607 _EnterWin16Lock();
608 goto found;
609 case BINARY_OS216:
610 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
611 ExitProcess(1);
612 case BINARY_UNIX_EXE:
613 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
614 ExitProcess(1);
615 case BINARY_UNIX_LIB:
617 DOS_FULL_NAME full_name;
618 const char *name = main_exe_name;
620 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
621 if (DOSFS_GetFullName( name, TRUE, &full_name )) name = full_name.long_name;
622 CloseHandle( main_exe_file );
623 main_exe_file = 0;
624 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
626 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
627 goto found;
629 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
630 ExitProcess(1);
634 found:
635 /* build command line */
636 if (!ENV_BuildCommandLine( argv )) goto error;
638 /* create 32-bit module for main exe */
639 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
640 stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
642 /* allocate main thread stack */
643 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
645 /* switch to the new stack */
646 SYSDEPS_SwitchToThreadStack( start_process );
648 error:
649 ExitProcess( GetLastError() );
653 /***********************************************************************
654 * build_argv
656 * Build an argv array from a command-line.
657 * The command-line is modified to insert nulls.
658 * 'reserved' is the number of args to reserve before the first one.
660 static char **build_argv( char *cmdline, int reserved )
662 int argc;
663 char** argv;
664 char *arg,*s,*d;
665 int in_quotes,bcount;
667 argc=reserved+1;
668 bcount=0;
669 in_quotes=0;
670 s=cmdline;
671 while (1) {
672 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
673 /* space */
674 argc++;
675 /* skip the remaining spaces */
676 while (*s==' ' || *s=='\t') {
677 s++;
679 if (*s=='\0')
680 break;
681 bcount=0;
682 continue;
683 } else if (*s=='\\') {
684 /* '\', count them */
685 bcount++;
686 } else if ((*s=='"') && ((bcount & 1)==0)) {
687 /* unescaped '"' */
688 in_quotes=!in_quotes;
689 bcount=0;
690 } else {
691 /* a regular character */
692 bcount=0;
694 s++;
696 argv=malloc(argc*sizeof(*argv));
697 if (!argv)
698 return NULL;
700 arg=d=s=cmdline;
701 bcount=0;
702 in_quotes=0;
703 argc=reserved;
704 while (*s) {
705 if ((*s==' ' || *s=='\t') && !in_quotes) {
706 /* Close the argument and copy it */
707 *d=0;
708 argv[argc++]=arg;
710 /* skip the remaining spaces */
711 do {
712 s++;
713 } while (*s==' ' || *s=='\t');
715 /* Start with a new argument */
716 arg=d=s;
717 bcount=0;
718 } else if (*s=='\\') {
719 /* '\\' */
720 *d++=*s++;
721 bcount++;
722 } else if (*s=='"') {
723 /* '"' */
724 if ((bcount & 1)==0) {
725 /* Preceeded by an even number of '\', this is half that
726 * number of '\', plus a '"' which we discard.
728 d-=bcount/2;
729 s++;
730 in_quotes=!in_quotes;
731 } else {
732 /* Preceeded by an odd number of '\', this is half that
733 * number of '\' followed by a '"'
735 d=d-bcount/2-1;
736 *d++='"';
737 s++;
739 bcount=0;
740 } else {
741 /* a regular character */
742 *d++=*s++;
743 bcount=0;
746 if (*arg) {
747 *d='\0';
748 argv[argc++]=arg;
750 argv[argc]=NULL;
752 return argv;
756 /***********************************************************************
757 * build_envp
759 * Build the environment of a new child process.
761 static char **build_envp( const char *env, const char *extra_env )
763 const char *p;
764 char **envp;
765 int count = 0;
767 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
768 for (p = env; *p; count++) p += strlen(p) + 1;
769 count += 3;
771 if ((envp = malloc( count * sizeof(*envp) )))
773 extern char **environ;
774 char **envptr = envp;
775 char **unixptr = environ;
776 /* first the extra strings */
777 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
778 /* then put PATH, HOME and WINEPREFIX from the unix env */
779 for (unixptr = environ; unixptr && *unixptr; unixptr++)
780 if (!memcmp( *unixptr, "PATH=", 5 ) ||
781 !memcmp( *unixptr, "HOME=", 5 ) ||
782 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
783 /* now put the Windows environment strings */
784 for (p = env; *p; p += strlen(p) + 1)
786 if (memcmp( p, "PATH=", 5 ) &&
787 memcmp( p, "HOME=", 5 ) &&
788 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
790 *envptr = 0;
792 return envp;
796 /***********************************************************************
797 * exec_wine_binary
799 * Locate the Wine binary to exec for a new Win32 process.
801 static void exec_wine_binary( char **argv, char **envp )
803 const char *path, *pos, *ptr;
805 /* first, try for a WINELOADER environment variable */
806 argv[0] = getenv("WINELOADER");
807 if (argv[0])
808 execve( argv[0], argv, envp );
810 /* next, try bin directory */
811 argv[0] = BINDIR "/wine";
812 execve( argv[0], argv, envp );
814 /* now try the path of argv0 of the current binary */
815 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
816 if ((ptr = strrchr( full_argv0, '/' )))
818 memcpy( argv[0], full_argv0, ptr - full_argv0 );
819 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
820 execve( argv[0], argv, envp );
822 free( argv[0] );
824 /* now search in the Unix path */
825 if ((path = getenv( "PATH" )))
827 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
828 pos = path;
829 for (;;)
831 while (*pos == ':') pos++;
832 if (!*pos) break;
833 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
834 memcpy( argv[0], pos, ptr - pos );
835 strcpy( argv[0] + (ptr - pos), "/wine" );
836 execve( argv[0], argv, envp );
837 pos = ptr;
840 free( argv[0] );
844 /***********************************************************************
845 * fork_and_exec
847 * Fork and exec a new Unix process, checking for errors.
849 static int fork_and_exec( const char *filename, char *cmdline,
850 const char *env, const char *newdir )
852 int fd[2];
853 int pid, err;
854 char *extra_env = NULL;
856 if (!env)
858 env = GetEnvironmentStringsA();
859 extra_env = DRIVE_BuildEnv();
862 if (pipe(fd) == -1)
864 FILE_SetDosError();
865 return -1;
867 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
868 if (!(pid = fork())) /* child */
870 char **argv = build_argv( cmdline, filename ? 0 : 1 );
871 char **envp = build_envp( env, extra_env );
872 close( fd[0] );
874 /* Reset signals that we previously set to SIG_IGN */
875 signal( SIGPIPE, SIG_DFL );
876 signal( SIGCHLD, SIG_DFL );
878 if (newdir) chdir(newdir);
880 if (argv && envp)
882 if (!filename) exec_wine_binary( argv, envp );
883 else execve( filename, argv, envp );
885 err = errno;
886 write( fd[1], &err, sizeof(err) );
887 _exit(1);
889 close( fd[1] );
890 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
892 errno = err;
893 pid = -1;
895 if (pid == -1) FILE_SetDosError();
896 close( fd[0] );
897 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
898 return pid;
902 /***********************************************************************
903 * create_process
905 * Create a new process. If hFile is a valid handle we have an exe
906 * file, otherwise it is a Winelib app.
908 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
909 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
910 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
911 LPPROCESS_INFORMATION info, LPCSTR unixdir )
913 BOOL ret, success = FALSE;
914 HANDLE process_info;
915 startup_info_t startup_info;
917 /* fill the startup info structure */
919 startup_info.size = sizeof(startup_info);
920 /* startup_info.filename_len is set below */
921 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
922 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
923 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
924 startup_info.x = startup->dwX;
925 startup_info.y = startup->dwY;
926 startup_info.cx = startup->dwXSize;
927 startup_info.cy = startup->dwYSize;
928 startup_info.x_chars = startup->dwXCountChars;
929 startup_info.y_chars = startup->dwYCountChars;
930 startup_info.attribute = startup->dwFillAttribute;
931 startup_info.cmd_show = startup->wShowWindow;
932 startup_info.flags = startup->dwFlags;
934 /* create the process on the server side */
936 SERVER_START_REQ( new_process )
938 char buf[MAX_PATH];
939 LPCSTR nameptr;
941 req->inherit_all = inherit;
942 req->create_flags = flags;
943 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
944 req->exe_file = hFile;
945 if (startup->dwFlags & STARTF_USESTDHANDLES)
947 req->hstdin = startup->hStdInput;
948 req->hstdout = startup->hStdOutput;
949 req->hstderr = startup->hStdError;
951 else
953 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
954 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
955 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
958 if (GetLongPathNameA( filename, buf, MAX_PATH ))
959 nameptr = buf;
960 else
961 nameptr = filename;
963 startup_info.filename_len = strlen(nameptr);
964 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
965 wine_server_add_data( req, nameptr, startup_info.filename_len );
966 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
967 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
968 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
970 ret = !wine_server_call_err( req );
971 process_info = reply->info;
973 SERVER_END_REQ;
974 if (!ret) return FALSE;
976 /* fork and execute */
978 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
980 CloseHandle( process_info );
981 return FALSE;
984 /* wait for the new process info to be ready */
986 WaitForSingleObject( process_info, INFINITE );
987 SERVER_START_REQ( get_new_process_info )
989 req->info = process_info;
990 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
991 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
992 if ((ret = !wine_server_call_err( req )))
994 info->dwProcessId = (DWORD)reply->pid;
995 info->dwThreadId = (DWORD)reply->tid;
996 info->hProcess = reply->phandle;
997 info->hThread = reply->thandle;
998 success = reply->success;
1001 SERVER_END_REQ;
1003 if (ret && !success) /* new process failed to start */
1005 DWORD exitcode;
1006 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1007 CloseHandle( info->hThread );
1008 CloseHandle( info->hProcess );
1009 ret = FALSE;
1011 CloseHandle( process_info );
1012 return ret;
1016 /*************************************************************************
1017 * get_file_name
1019 * Helper for CreateProcess: retrieve the file name to load from the
1020 * app name and command line. Store the file name in buffer, and
1021 * return a possibly modified command line.
1022 * Also returns a handle to the opened file if it's a Windows binary.
1024 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1025 int buflen, HANDLE *handle )
1027 char *name, *pos, *ret = NULL;
1028 const char *p;
1030 /* if we have an app name, everything is easy */
1032 if (appname)
1034 /* use the unmodified app name as file name */
1035 lstrcpynA( buffer, appname, buflen );
1036 *handle = open_exe_file( buffer );
1037 if (!(ret = cmdline))
1039 /* no command-line, create one */
1040 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1041 sprintf( ret, "\"%s\"", appname );
1043 return ret;
1046 if (!cmdline)
1048 SetLastError( ERROR_INVALID_PARAMETER );
1049 return NULL;
1052 /* first check for a quoted file name */
1054 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1056 int len = p - cmdline - 1;
1057 /* extract the quoted portion as file name */
1058 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1059 memcpy( name, cmdline + 1, len );
1060 name[len] = 0;
1062 if (find_exe_file( name, buffer, buflen, handle ))
1063 ret = cmdline; /* no change necessary */
1064 goto done;
1067 /* now try the command-line word by word */
1069 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1070 pos = name;
1071 p = cmdline;
1073 while (*p)
1075 do *pos++ = *p++; while (*p && *p != ' ');
1076 *pos = 0;
1077 if (find_exe_file( name, buffer, buflen, handle ))
1079 ret = cmdline;
1080 break;
1084 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1086 /* now build a new command-line with quotes */
1088 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1089 sprintf( ret, "\"%s\"%s", name, p );
1091 done:
1092 HeapFree( GetProcessHeap(), 0, name );
1093 return ret;
1097 /**********************************************************************
1098 * CreateProcessA (KERNEL32.@)
1100 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1101 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1102 DWORD flags, LPVOID env, LPCSTR cur_dir,
1103 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1105 BOOL retv = FALSE;
1106 HANDLE hFile = 0;
1107 const char *unixdir = NULL;
1108 DOS_FULL_NAME full_dir;
1109 char name[MAX_PATH];
1110 LPSTR tidy_cmdline;
1111 char *p;
1113 /* Process the AppName and/or CmdLine to get module name and path */
1115 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1117 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1118 return FALSE;
1119 if (hFile == INVALID_HANDLE_VALUE) goto done;
1121 /* Warn if unsupported features are used */
1123 if (flags & NORMAL_PRIORITY_CLASS)
1124 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1125 if (flags & IDLE_PRIORITY_CLASS)
1126 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1127 if (flags & HIGH_PRIORITY_CLASS)
1128 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1129 if (flags & REALTIME_PRIORITY_CLASS)
1130 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1131 if (flags & CREATE_NEW_PROCESS_GROUP)
1132 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1133 if (flags & CREATE_UNICODE_ENVIRONMENT)
1134 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1135 if (flags & CREATE_SEPARATE_WOW_VDM)
1136 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1137 if (flags & CREATE_SHARED_WOW_VDM)
1138 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1139 if (flags & CREATE_DEFAULT_ERROR_MODE)
1140 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1141 if (flags & CREATE_NO_WINDOW)
1142 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1143 if (flags & PROFILE_USER)
1144 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1145 if (flags & PROFILE_KERNEL)
1146 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1147 if (flags & PROFILE_SERVER)
1148 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1149 if (startup_info->lpDesktop)
1150 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1151 name, debugstr_a(startup_info->lpDesktop));
1152 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1153 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1154 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1155 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1156 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1157 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1158 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1159 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1161 if (cur_dir)
1163 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir ))
1164 unixdir = full_dir.long_name;
1166 else
1168 char buf[MAX_PATH];
1169 if (GetCurrentDirectoryA(sizeof(buf),buf))
1171 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1175 info->hThread = info->hProcess = 0;
1176 info->dwProcessId = info->dwThreadId = 0;
1178 /* Determine executable type */
1180 if (!hFile) /* builtin exe */
1182 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1183 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1184 inherit, flags, startup_info, info, unixdir );
1185 goto done;
1188 switch( MODULE_GetBinaryType( hFile ))
1190 case BINARY_PE_EXE:
1191 case BINARY_WIN16:
1192 case BINARY_DOS:
1193 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1194 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1195 inherit, flags, startup_info, info, unixdir );
1196 break;
1197 case BINARY_OS216:
1198 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1199 SetLastError( ERROR_BAD_EXE_FORMAT );
1200 break;
1201 case BINARY_PE_DLL:
1202 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1203 SetLastError( ERROR_BAD_EXE_FORMAT );
1204 break;
1205 case BINARY_UNIX_LIB:
1206 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1207 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1208 inherit, flags, startup_info, info, unixdir );
1209 break;
1210 case BINARY_UNKNOWN:
1211 /* check for .com extension */
1212 if ((p = strrchr( name, '.' )) && !FILE_strcasecmp( p, ".com" ))
1214 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1215 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1216 inherit, flags, startup_info, info, unixdir );
1217 break;
1219 /* fall through */
1220 case BINARY_UNIX_EXE:
1222 DOS_FULL_NAME full_name;
1223 const char *unixfilename = name;
1225 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1226 if (DOSFS_GetFullName( name, TRUE, &full_name )) unixfilename = full_name.long_name;
1227 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1229 break;
1231 CloseHandle( hFile );
1233 done:
1234 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1235 return retv;
1239 /**********************************************************************
1240 * CreateProcessW (KERNEL32.@)
1241 * NOTES
1242 * lpReserved is not converted
1244 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1245 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1246 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1247 LPPROCESS_INFORMATION info )
1249 BOOL ret;
1250 STARTUPINFOA StartupInfoA;
1252 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1253 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1254 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1256 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1257 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1258 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1260 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1262 if (startup_info->lpReserved)
1263 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1264 debugstr_w(startup_info->lpReserved));
1266 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1267 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1269 HeapFree( GetProcessHeap(), 0, cur_dirA );
1270 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1271 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1272 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1274 return ret;
1278 /***********************************************************************
1279 * ExitProcess (KERNEL32.@)
1281 void WINAPI ExitProcess( DWORD status )
1283 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1284 SERVER_START_REQ( terminate_process )
1286 /* send the exit code to the server */
1287 req->handle = GetCurrentProcess();
1288 req->exit_code = status;
1289 wine_server_call( req );
1291 SERVER_END_REQ;
1292 exit( status );
1295 /***********************************************************************
1296 * ExitProcess (KERNEL.466)
1298 void WINAPI ExitProcess16( WORD status )
1300 DWORD count;
1301 ReleaseThunkLock( &count );
1302 ExitProcess( status );
1305 /******************************************************************************
1306 * TerminateProcess (KERNEL32.@)
1308 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1310 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1311 if (status) SetLastError( RtlNtStatusToDosError(status) );
1312 return !status;
1316 /***********************************************************************
1317 * GetProcessDword (KERNEL.485)
1318 * GetProcessDword (KERNEL32.18)
1319 * 'Of course you cannot directly access Windows internal structures'
1321 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1323 DWORD x, y;
1325 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1327 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1329 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1330 return 0;
1333 switch ( offset )
1335 case GPD_APP_COMPAT_FLAGS:
1336 return GetAppCompatFlags16(0);
1338 case GPD_LOAD_DONE_EVENT:
1339 return (DWORD)current_process.load_done_evt;
1341 case GPD_HINSTANCE16:
1342 return GetTaskDS16();
1344 case GPD_WINDOWS_VERSION:
1345 return GetExeVersion16();
1347 case GPD_THDB:
1348 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1350 case GPD_PDB:
1351 return (DWORD)&current_process;
1353 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1354 return (DWORD)current_startupinfo.hStdOutput;
1356 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1357 return (DWORD)current_startupinfo.hStdInput;
1359 case GPD_STARTF_SHOWWINDOW:
1360 return current_startupinfo.wShowWindow;
1362 case GPD_STARTF_SIZE:
1363 x = current_startupinfo.dwXSize;
1364 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1365 y = current_startupinfo.dwYSize;
1366 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1367 return MAKELONG( x, y );
1369 case GPD_STARTF_POSITION:
1370 x = current_startupinfo.dwX;
1371 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1372 y = current_startupinfo.dwY;
1373 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1374 return MAKELONG( x, y );
1376 case GPD_STARTF_FLAGS:
1377 return current_startupinfo.dwFlags;
1379 case GPD_PARENT:
1380 return 0;
1382 case GPD_FLAGS:
1383 return current_process.flags;
1385 case GPD_USERDATA:
1386 return current_process.process_dword;
1388 default:
1389 ERR_(win32)("Unknown offset %d\n", offset );
1390 return 0;
1394 /***********************************************************************
1395 * SetProcessDword (KERNEL.484)
1396 * 'Of course you cannot directly access Windows internal structures'
1398 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1400 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1402 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1404 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1405 return;
1408 switch ( offset )
1410 case GPD_APP_COMPAT_FLAGS:
1411 case GPD_LOAD_DONE_EVENT:
1412 case GPD_HINSTANCE16:
1413 case GPD_WINDOWS_VERSION:
1414 case GPD_THDB:
1415 case GPD_PDB:
1416 case GPD_STARTF_SHELLDATA:
1417 case GPD_STARTF_HOTKEY:
1418 case GPD_STARTF_SHOWWINDOW:
1419 case GPD_STARTF_SIZE:
1420 case GPD_STARTF_POSITION:
1421 case GPD_STARTF_FLAGS:
1422 case GPD_PARENT:
1423 case GPD_FLAGS:
1424 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1425 break;
1427 case GPD_USERDATA:
1428 current_process.process_dword = value;
1429 break;
1431 default:
1432 ERR_(win32)("Unknown offset %d\n", offset );
1433 break;
1438 /*********************************************************************
1439 * OpenProcess (KERNEL32.@)
1441 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1443 HANDLE ret = 0;
1444 SERVER_START_REQ( open_process )
1446 req->pid = (void *)id;
1447 req->access = access;
1448 req->inherit = inherit;
1449 if (!wine_server_call_err( req )) ret = reply->handle;
1451 SERVER_END_REQ;
1452 return ret;
1455 /*********************************************************************
1456 * MapProcessHandle (KERNEL.483)
1458 DWORD WINAPI MapProcessHandle( HANDLE handle )
1460 DWORD ret = 0;
1461 SERVER_START_REQ( get_process_info )
1463 req->handle = handle;
1464 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1466 SERVER_END_REQ;
1467 return ret;
1470 /***********************************************************************
1471 * SetPriorityClass (KERNEL32.@)
1473 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1475 BOOL ret;
1476 SERVER_START_REQ( set_process_info )
1478 req->handle = hprocess;
1479 req->priority = priorityclass;
1480 req->mask = SET_PROCESS_INFO_PRIORITY;
1481 ret = !wine_server_call_err( req );
1483 SERVER_END_REQ;
1484 return ret;
1488 /***********************************************************************
1489 * GetPriorityClass (KERNEL32.@)
1491 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1493 DWORD ret = 0;
1494 SERVER_START_REQ( get_process_info )
1496 req->handle = hprocess;
1497 if (!wine_server_call_err( req )) ret = reply->priority;
1499 SERVER_END_REQ;
1500 return ret;
1504 /***********************************************************************
1505 * SetProcessAffinityMask (KERNEL32.@)
1507 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1509 BOOL ret;
1510 SERVER_START_REQ( set_process_info )
1512 req->handle = hProcess;
1513 req->affinity = affmask;
1514 req->mask = SET_PROCESS_INFO_AFFINITY;
1515 ret = !wine_server_call_err( req );
1517 SERVER_END_REQ;
1518 return ret;
1521 /**********************************************************************
1522 * GetProcessAffinityMask (KERNEL32.@)
1524 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1525 LPDWORD lpProcessAffinityMask,
1526 LPDWORD lpSystemAffinityMask )
1528 BOOL ret = FALSE;
1529 SERVER_START_REQ( get_process_info )
1531 req->handle = hProcess;
1532 if (!wine_server_call_err( req ))
1534 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1535 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1536 ret = TRUE;
1539 SERVER_END_REQ;
1540 return ret;
1544 /***********************************************************************
1545 * GetProcessVersion (KERNEL32.@)
1547 DWORD WINAPI GetProcessVersion( DWORD processid )
1549 IMAGE_NT_HEADERS *nt;
1551 if (processid && processid != GetCurrentProcessId())
1553 FIXME("should use ReadProcessMemory\n");
1554 return 0;
1556 if ((nt = RtlImageNtHeader( current_process.module )))
1557 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1558 nt->OptionalHeader.MinorSubsystemVersion);
1559 return 0;
1562 /***********************************************************************
1563 * GetProcessFlags (KERNEL32.@)
1565 DWORD WINAPI GetProcessFlags( DWORD processid )
1567 if (processid && processid != GetCurrentProcessId()) return 0;
1568 return current_process.flags;
1572 /***********************************************************************
1573 * SetProcessWorkingSetSize [KERNEL32.@]
1574 * Sets the min/max working set sizes for a specified process.
1576 * PARAMS
1577 * hProcess [I] Handle to the process of interest
1578 * minset [I] Specifies minimum working set size
1579 * maxset [I] Specifies maximum working set size
1581 * RETURNS STD
1583 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1584 DWORD maxset)
1586 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1587 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1588 /* Trim the working set to zero */
1589 /* Swap the process out of physical RAM */
1591 return TRUE;
1594 /***********************************************************************
1595 * GetProcessWorkingSetSize (KERNEL32.@)
1597 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1598 LPDWORD maxset)
1600 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1601 /* 32 MB working set size */
1602 if (minset) *minset = 32*1024*1024;
1603 if (maxset) *maxset = 32*1024*1024;
1604 return TRUE;
1607 /***********************************************************************
1608 * SetProcessShutdownParameters (KERNEL32.@)
1610 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1611 * Now tracks changes made (but does not act on these changes)
1613 static DWORD shutdown_flags = 0;
1614 static DWORD shutdown_priority = 0x280;
1616 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1618 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1619 shutdown_flags = flags;
1620 shutdown_priority = level;
1621 return TRUE;
1625 /***********************************************************************
1626 * GetProcessShutdownParameters (KERNEL32.@)
1629 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1631 *lpdwLevel = shutdown_priority;
1632 *lpdwFlags = shutdown_flags;
1633 return TRUE;
1637 /***********************************************************************
1638 * SetProcessPriorityBoost (KERNEL32.@)
1640 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1642 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1643 /* Say we can do it. I doubt the program will notice that we don't. */
1644 return TRUE;
1648 /***********************************************************************
1649 * ReadProcessMemory (KERNEL32.@)
1651 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1652 LPDWORD bytes_read )
1654 DWORD res;
1656 SERVER_START_REQ( read_process_memory )
1658 req->handle = process;
1659 req->addr = (void *)addr;
1660 wine_server_set_reply( req, buffer, size );
1661 if ((res = wine_server_call_err( req ))) size = 0;
1663 SERVER_END_REQ;
1664 if (bytes_read) *bytes_read = size;
1665 return !res;
1669 /***********************************************************************
1670 * WriteProcessMemory (KERNEL32.@)
1672 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1673 LPDWORD bytes_written )
1675 static const int zero;
1676 unsigned int first_offset, last_offset, first_mask, last_mask;
1677 DWORD res;
1679 if (!size)
1681 SetLastError( ERROR_INVALID_PARAMETER );
1682 return FALSE;
1685 /* compute the mask for the first int */
1686 first_mask = ~0;
1687 first_offset = (unsigned int)addr % sizeof(int);
1688 memset( &first_mask, 0, first_offset );
1690 /* compute the mask for the last int */
1691 last_offset = (size + first_offset) % sizeof(int);
1692 last_mask = 0;
1693 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1695 SERVER_START_REQ( write_process_memory )
1697 req->handle = process;
1698 req->addr = (char *)addr - first_offset;
1699 req->first_mask = first_mask;
1700 req->last_mask = last_mask;
1701 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1702 wine_server_add_data( req, buffer, size );
1703 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1705 if ((res = wine_server_call_err( req ))) size = 0;
1707 SERVER_END_REQ;
1708 if (bytes_written) *bytes_written = size;
1710 char dummy[32];
1711 DWORD read;
1712 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1714 return !res;
1718 /***********************************************************************
1719 * RegisterServiceProcess (KERNEL.491)
1720 * RegisterServiceProcess (KERNEL32.@)
1722 * A service process calls this function to ensure that it continues to run
1723 * even after a user logged off.
1725 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1727 /* I don't think that Wine needs to do anything in that function */
1728 return 1; /* success */
1731 /***********************************************************************
1732 * GetExitCodeProcess [KERNEL32.@]
1734 * Gets termination status of specified process
1736 * RETURNS
1737 * Success: TRUE
1738 * Failure: FALSE
1740 BOOL WINAPI GetExitCodeProcess(
1741 HANDLE hProcess, /* [in] handle to the process */
1742 LPDWORD lpExitCode) /* [out] address to receive termination status */
1744 BOOL ret;
1745 SERVER_START_REQ( get_process_info )
1747 req->handle = hProcess;
1748 ret = !wine_server_call_err( req );
1749 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1751 SERVER_END_REQ;
1752 return ret;
1756 /***********************************************************************
1757 * SetErrorMode (KERNEL32.@)
1759 UINT WINAPI SetErrorMode( UINT mode )
1761 UINT old = current_process.error_mode;
1762 current_process.error_mode = mode;
1763 return old;
1767 /**************************************************************************
1768 * SetFileApisToOEM (KERNEL32.@)
1770 VOID WINAPI SetFileApisToOEM(void)
1772 current_process.flags |= PDB32_FILE_APIS_OEM;
1776 /**************************************************************************
1777 * SetFileApisToANSI (KERNEL32.@)
1779 VOID WINAPI SetFileApisToANSI(void)
1781 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1785 /******************************************************************************
1786 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1788 * RETURNS
1789 * TRUE: Set of file functions is using ANSI code page
1790 * FALSE: Set of file functions is using OEM code page
1792 BOOL WINAPI AreFileApisANSI(void)
1794 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1798 /***********************************************************************
1799 * GetTickCount (KERNEL32.@)
1801 * Returns the number of milliseconds, modulo 2^32, since the start
1802 * of the wineserver.
1804 DWORD WINAPI GetTickCount(void)
1806 struct timeval t;
1807 gettimeofday( &t, NULL );
1808 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1812 /**********************************************************************
1813 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1815 * Allocates a thread local storage index
1817 * RETURNS
1818 * Success: TLS Index
1819 * Failure: 0xFFFFFFFF
1821 DWORD WINAPI TlsAlloc( void )
1823 DWORD i, mask, ret = 0;
1824 DWORD *bits = current_process.tls_bits;
1825 RtlAcquirePebLock();
1826 if (*bits == 0xffffffff)
1828 bits++;
1829 ret = 32;
1830 if (*bits == 0xffffffff)
1832 RtlReleasePebLock();
1833 SetLastError( ERROR_NO_MORE_ITEMS );
1834 return 0xffffffff;
1837 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1838 *bits |= mask;
1839 RtlReleasePebLock();
1840 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1841 return ret + i;
1845 /**********************************************************************
1846 * TlsFree [KERNEL32.@] Releases a TLS index.
1848 * Releases a thread local storage index, making it available for reuse
1850 * RETURNS
1851 * Success: TRUE
1852 * Failure: FALSE
1854 BOOL WINAPI TlsFree(
1855 DWORD index) /* [in] TLS Index to free */
1857 DWORD mask = (1 << (index & 31));
1858 DWORD *bits = current_process.tls_bits;
1859 if (index >= 64)
1861 SetLastError( ERROR_INVALID_PARAMETER );
1862 return FALSE;
1864 if (index >= 32) bits++;
1865 RtlAcquirePebLock();
1866 if (!(*bits & mask)) /* already free? */
1868 RtlReleasePebLock();
1869 SetLastError( ERROR_INVALID_PARAMETER );
1870 return FALSE;
1872 *bits &= ~mask;
1873 NtCurrentTeb()->tls_array[index] = 0;
1874 /* FIXME: should zero all other thread values */
1875 RtlReleasePebLock();
1876 return TRUE;
1880 /**********************************************************************
1881 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1883 * RETURNS
1884 * Success: Value stored in calling thread's TLS slot for index
1885 * Failure: 0 and GetLastError returns NO_ERROR
1887 LPVOID WINAPI TlsGetValue(
1888 DWORD index) /* [in] TLS index to retrieve value for */
1890 if (index >= 64)
1892 SetLastError( ERROR_INVALID_PARAMETER );
1893 return NULL;
1895 SetLastError( ERROR_SUCCESS );
1896 return NtCurrentTeb()->tls_array[index];
1900 /**********************************************************************
1901 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1903 * RETURNS
1904 * Success: TRUE
1905 * Failure: FALSE
1907 BOOL WINAPI TlsSetValue(
1908 DWORD index, /* [in] TLS index to set value for */
1909 LPVOID value) /* [in] Value to be stored */
1911 if (index >= 64)
1913 SetLastError( ERROR_INVALID_PARAMETER );
1914 return FALSE;
1916 NtCurrentTeb()->tls_array[index] = value;
1917 return TRUE;
1921 /***********************************************************************
1922 * GetCurrentProcess (KERNEL32.@)
1924 #undef GetCurrentProcess
1925 HANDLE WINAPI GetCurrentProcess(void)
1927 return (HANDLE)0xffffffff;