Fixed another PlaySound bug (when SND_LOOP is requested).
[wine/wine-kai.git] / scheduler / process.c
blobffc3606ec74568456bd0963f4dee8f7f82a3dbe8
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 HFILE 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];
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_UNKNOWN:
583 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
584 ExitProcess(1);
585 case BINARY_PE_EXE:
586 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
587 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
588 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
589 ExitProcess(1);
590 case BINARY_PE_DLL:
591 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
592 ExitProcess(1);
593 case BINARY_WIN16:
594 case BINARY_DOS:
595 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
596 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
597 current_process.flags |= PDB32_WIN16_PROC;
598 strcpy( win16_exe_name, main_exe_name );
599 main_exe_name[0] = 0;
600 *win16_exe_file = main_exe_file;
601 main_exe_file = 0;
602 _EnterWin16Lock();
603 goto found;
604 case BINARY_OS216:
605 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
606 ExitProcess(1);
607 case BINARY_UNIX_EXE:
608 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
609 ExitProcess(1);
610 case BINARY_UNIX_LIB:
612 DOS_FULL_NAME full_name;
613 const char *name = main_exe_name;
615 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
616 if (DOSFS_GetFullName( name, TRUE, &full_name )) name = full_name.long_name;
617 CloseHandle( main_exe_file );
618 main_exe_file = 0;
619 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) )) goto found;
620 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
621 ExitProcess(1);
625 found:
626 /* build command line */
627 if (!ENV_BuildCommandLine( argv )) goto error;
629 /* create 32-bit module for main exe */
630 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
631 stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
633 /* allocate main thread stack */
634 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
636 /* switch to the new stack */
637 SYSDEPS_SwitchToThreadStack( start_process );
639 error:
640 ExitProcess( GetLastError() );
644 /***********************************************************************
645 * build_argv
647 * Build an argv array from a command-line.
648 * The command-line is modified to insert nulls.
649 * 'reserved' is the number of args to reserve before the first one.
651 static char **build_argv( char *cmdline, int reserved )
653 int argc;
654 char** argv;
655 char *arg,*s,*d;
656 int in_quotes,bcount;
658 argc=reserved+1;
659 bcount=0;
660 in_quotes=0;
661 s=cmdline;
662 while (1) {
663 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
664 /* space */
665 argc++;
666 /* skip the remaining spaces */
667 while (*s==' ' || *s=='\t') {
668 s++;
670 if (*s=='\0')
671 break;
672 bcount=0;
673 continue;
674 } else if (*s=='\\') {
675 /* '\', count them */
676 bcount++;
677 } else if ((*s=='"') && ((bcount & 1)==0)) {
678 /* unescaped '"' */
679 in_quotes=!in_quotes;
680 bcount=0;
681 } else {
682 /* a regular character */
683 bcount=0;
685 s++;
687 argv=malloc(argc*sizeof(*argv));
688 if (!argv)
689 return NULL;
691 arg=d=s=cmdline;
692 bcount=0;
693 in_quotes=0;
694 argc=reserved;
695 while (*s) {
696 if ((*s==' ' || *s=='\t') && !in_quotes) {
697 /* Close the argument and copy it */
698 *d=0;
699 argv[argc++]=arg;
701 /* skip the remaining spaces */
702 do {
703 s++;
704 } while (*s==' ' || *s=='\t');
706 /* Start with a new argument */
707 arg=d=s;
708 bcount=0;
709 } else if (*s=='\\') {
710 /* '\\' */
711 *d++=*s++;
712 bcount++;
713 } else if (*s=='"') {
714 /* '"' */
715 if ((bcount & 1)==0) {
716 /* Preceeded by an even number of '\', this is half that
717 * number of '\', plus a '"' which we discard.
719 d-=bcount/2;
720 s++;
721 in_quotes=!in_quotes;
722 } else {
723 /* Preceeded by an odd number of '\', this is half that
724 * number of '\' followed by a '"'
726 d=d-bcount/2-1;
727 *d++='"';
728 s++;
730 bcount=0;
731 } else {
732 /* a regular character */
733 *d++=*s++;
734 bcount=0;
737 if (*arg) {
738 *d='\0';
739 argv[argc++]=arg;
741 argv[argc]=NULL;
743 return argv;
747 /***********************************************************************
748 * build_envp
750 * Build the environment of a new child process.
752 static char **build_envp( const char *env, const char *extra_env )
754 const char *p;
755 char **envp;
756 int count = 0;
758 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
759 for (p = env; *p; count++) p += strlen(p) + 1;
760 count += 3;
762 if ((envp = malloc( count * sizeof(*envp) )))
764 extern char **environ;
765 char **envptr = envp;
766 char **unixptr = environ;
767 /* first the extra strings */
768 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
769 /* then put PATH, HOME and WINEPREFIX from the unix env */
770 for (unixptr = environ; unixptr && *unixptr; unixptr++)
771 if (!memcmp( *unixptr, "PATH=", 5 ) ||
772 !memcmp( *unixptr, "HOME=", 5 ) ||
773 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
774 /* now put the Windows environment strings */
775 for (p = env; *p; p += strlen(p) + 1)
777 if (memcmp( p, "PATH=", 5 ) &&
778 memcmp( p, "HOME=", 5 ) &&
779 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
781 *envptr = 0;
783 return envp;
787 /***********************************************************************
788 * exec_wine_binary
790 * Locate the Wine binary to exec for a new Win32 process.
792 static void exec_wine_binary( char **argv, char **envp )
794 const char *path, *pos, *ptr;
796 /* first, try for a WINELOADER environment variable */
797 argv[0] = getenv("WINELOADER");
798 if (argv[0])
799 execve( argv[0], argv, envp );
801 /* next, try bin directory */
802 argv[0] = BINDIR "/wine";
803 execve( argv[0], argv, envp );
805 /* now try the path of argv0 of the current binary */
806 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
807 if ((ptr = strrchr( full_argv0, '/' )))
809 memcpy( argv[0], full_argv0, ptr - full_argv0 );
810 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
811 execve( argv[0], argv, envp );
813 free( argv[0] );
815 /* now search in the Unix path */
816 if ((path = getenv( "PATH" )))
818 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
819 pos = path;
820 for (;;)
822 while (*pos == ':') pos++;
823 if (!*pos) break;
824 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
825 memcpy( argv[0], pos, ptr - pos );
826 strcpy( argv[0] + (ptr - pos), "/wine" );
827 execve( argv[0], argv, envp );
828 pos = ptr;
831 free( argv[0] );
835 /***********************************************************************
836 * fork_and_exec
838 * Fork and exec a new Unix process, checking for errors.
840 static int fork_and_exec( const char *filename, char *cmdline,
841 const char *env, const char *newdir )
843 int fd[2];
844 int pid, err;
845 char *extra_env = NULL;
847 if (!env)
849 env = GetEnvironmentStringsA();
850 extra_env = DRIVE_BuildEnv();
853 if (pipe(fd) == -1)
855 FILE_SetDosError();
856 return -1;
858 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
859 if (!(pid = fork())) /* child */
861 char **argv = build_argv( cmdline, filename ? 0 : 1 );
862 char **envp = build_envp( env, extra_env );
863 close( fd[0] );
865 /* Reset signals that we previously set to SIG_IGN */
866 signal( SIGPIPE, SIG_DFL );
867 signal( SIGCHLD, SIG_DFL );
869 if (newdir) chdir(newdir);
871 if (argv && envp)
873 if (!filename) exec_wine_binary( argv, envp );
874 else execve( filename, argv, envp );
876 err = errno;
877 write( fd[1], &err, sizeof(err) );
878 _exit(1);
880 close( fd[1] );
881 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
883 errno = err;
884 pid = -1;
886 if (pid == -1) FILE_SetDosError();
887 close( fd[0] );
888 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
889 return pid;
893 /***********************************************************************
894 * create_process
896 * Create a new process. If hFile is a valid handle we have an exe
897 * file, otherwise it is a Winelib app.
899 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
900 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
901 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
902 LPPROCESS_INFORMATION info, LPCSTR unixdir )
904 BOOL ret, success = FALSE;
905 HANDLE process_info;
906 startup_info_t startup_info;
908 /* fill the startup info structure */
910 startup_info.size = sizeof(startup_info);
911 /* startup_info.filename_len is set below */
912 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
913 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
914 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
915 startup_info.x = startup->dwX;
916 startup_info.y = startup->dwY;
917 startup_info.cx = startup->dwXSize;
918 startup_info.cy = startup->dwYSize;
919 startup_info.x_chars = startup->dwXCountChars;
920 startup_info.y_chars = startup->dwYCountChars;
921 startup_info.attribute = startup->dwFillAttribute;
922 startup_info.cmd_show = startup->wShowWindow;
923 startup_info.flags = startup->dwFlags;
925 /* create the process on the server side */
927 SERVER_START_REQ( new_process )
929 char buf[MAX_PATH];
930 LPCSTR nameptr;
932 req->inherit_all = inherit;
933 req->create_flags = flags;
934 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
935 req->exe_file = hFile;
936 if (startup->dwFlags & STARTF_USESTDHANDLES)
938 req->hstdin = startup->hStdInput;
939 req->hstdout = startup->hStdOutput;
940 req->hstderr = startup->hStdError;
942 else
944 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
945 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
946 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
949 if (GetLongPathNameA( filename, buf, MAX_PATH ))
950 nameptr = buf;
951 else
952 nameptr = filename;
954 startup_info.filename_len = strlen(nameptr);
955 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
956 wine_server_add_data( req, nameptr, startup_info.filename_len );
957 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
958 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
959 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
961 ret = !wine_server_call_err( req );
962 process_info = reply->info;
964 SERVER_END_REQ;
965 if (!ret) return FALSE;
967 /* fork and execute */
969 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
971 CloseHandle( process_info );
972 return FALSE;
975 /* wait for the new process info to be ready */
977 WaitForSingleObject( process_info, INFINITE );
978 SERVER_START_REQ( get_new_process_info )
980 req->info = process_info;
981 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
982 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
983 if ((ret = !wine_server_call_err( req )))
985 info->dwProcessId = (DWORD)reply->pid;
986 info->dwThreadId = (DWORD)reply->tid;
987 info->hProcess = reply->phandle;
988 info->hThread = reply->thandle;
989 success = reply->success;
992 SERVER_END_REQ;
994 if (ret && !success) /* new process failed to start */
996 DWORD exitcode;
997 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
998 CloseHandle( info->hThread );
999 CloseHandle( info->hProcess );
1000 ret = FALSE;
1002 CloseHandle( process_info );
1003 return ret;
1007 /*************************************************************************
1008 * get_file_name
1010 * Helper for CreateProcess: retrieve the file name to load from the
1011 * app name and command line. Store the file name in buffer, and
1012 * return a possibly modified command line.
1013 * Also returns a handle to the opened file if it's a Windows binary.
1015 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1016 int buflen, HANDLE *handle )
1018 char *name, *pos, *ret = NULL;
1019 const char *p;
1021 /* if we have an app name, everything is easy */
1023 if (appname)
1025 /* use the unmodified app name as file name */
1026 lstrcpynA( buffer, appname, buflen );
1027 *handle = open_exe_file( buffer );
1028 if (!(ret = cmdline))
1030 /* no command-line, create one */
1031 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1032 sprintf( ret, "\"%s\"", appname );
1034 return ret;
1037 if (!cmdline)
1039 SetLastError( ERROR_INVALID_PARAMETER );
1040 return NULL;
1043 /* first check for a quoted file name */
1045 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1047 int len = p - cmdline - 1;
1048 /* extract the quoted portion as file name */
1049 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1050 memcpy( name, cmdline + 1, len );
1051 name[len] = 0;
1053 if (find_exe_file( name, buffer, buflen, handle ))
1054 ret = cmdline; /* no change necessary */
1055 goto done;
1058 /* now try the command-line word by word */
1060 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1061 pos = name;
1062 p = cmdline;
1064 while (*p)
1066 do *pos++ = *p++; while (*p && *p != ' ');
1067 *pos = 0;
1068 if (find_exe_file( name, buffer, buflen, handle ))
1070 ret = cmdline;
1071 break;
1075 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1077 /* now build a new command-line with quotes */
1079 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1080 sprintf( ret, "\"%s\"%s", name, p );
1082 done:
1083 HeapFree( GetProcessHeap(), 0, name );
1084 return ret;
1088 /**********************************************************************
1089 * CreateProcessA (KERNEL32.@)
1091 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1092 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1093 DWORD flags, LPVOID env, LPCSTR cur_dir,
1094 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1096 BOOL retv = FALSE;
1097 HANDLE hFile = 0;
1098 const char *unixdir = NULL;
1099 DOS_FULL_NAME full_dir;
1100 char name[MAX_PATH];
1101 LPSTR tidy_cmdline;
1103 /* Process the AppName and/or CmdLine to get module name and path */
1105 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1107 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1108 return FALSE;
1109 if (hFile == INVALID_HANDLE_VALUE) goto done;
1111 /* Warn if unsupported features are used */
1113 if (flags & NORMAL_PRIORITY_CLASS)
1114 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1115 if (flags & IDLE_PRIORITY_CLASS)
1116 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1117 if (flags & HIGH_PRIORITY_CLASS)
1118 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1119 if (flags & REALTIME_PRIORITY_CLASS)
1120 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1121 if (flags & CREATE_NEW_PROCESS_GROUP)
1122 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1123 if (flags & CREATE_UNICODE_ENVIRONMENT)
1124 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1125 if (flags & CREATE_SEPARATE_WOW_VDM)
1126 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1127 if (flags & CREATE_SHARED_WOW_VDM)
1128 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1129 if (flags & CREATE_DEFAULT_ERROR_MODE)
1130 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1131 if (flags & CREATE_NO_WINDOW)
1132 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1133 if (flags & PROFILE_USER)
1134 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1135 if (flags & PROFILE_KERNEL)
1136 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1137 if (flags & PROFILE_SERVER)
1138 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1139 if (startup_info->lpDesktop)
1140 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1141 name, debugstr_a(startup_info->lpDesktop));
1142 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1143 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1144 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1145 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1146 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1147 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1148 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1149 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1151 if (cur_dir)
1153 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir ))
1154 unixdir = full_dir.long_name;
1156 else
1158 char buf[MAX_PATH];
1159 if (GetCurrentDirectoryA(sizeof(buf),buf))
1161 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1165 info->hThread = info->hProcess = 0;
1166 info->dwProcessId = info->dwThreadId = 0;
1168 /* Determine executable type */
1170 if (!hFile) /* builtin exe */
1172 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1173 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1174 inherit, flags, startup_info, info, unixdir );
1175 goto done;
1178 switch( MODULE_GetBinaryType( hFile ))
1180 case BINARY_PE_EXE:
1181 case BINARY_WIN16:
1182 case BINARY_DOS:
1183 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1184 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1185 inherit, flags, startup_info, info, unixdir );
1186 break;
1187 case BINARY_OS216:
1188 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1189 SetLastError( ERROR_BAD_EXE_FORMAT );
1190 break;
1191 case BINARY_PE_DLL:
1192 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1193 SetLastError( ERROR_BAD_EXE_FORMAT );
1194 break;
1195 case BINARY_UNIX_LIB:
1196 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1197 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1198 inherit, flags, startup_info, info, unixdir );
1199 break;
1200 case BINARY_UNIX_EXE:
1201 case BINARY_UNKNOWN:
1203 /* unknown file, try as unix executable */
1205 DOS_FULL_NAME full_name;
1206 const char *unixfilename = name;
1208 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1209 if (DOSFS_GetFullName( name, TRUE, &full_name )) unixfilename = full_name.long_name;
1210 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1212 break;
1214 CloseHandle( hFile );
1216 done:
1217 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1218 return retv;
1222 /**********************************************************************
1223 * CreateProcessW (KERNEL32.@)
1224 * NOTES
1225 * lpReserved is not converted
1227 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1228 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1229 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1230 LPPROCESS_INFORMATION info )
1232 BOOL ret;
1233 STARTUPINFOA StartupInfoA;
1235 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1236 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1237 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1239 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1240 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1241 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1243 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1245 if (startup_info->lpReserved)
1246 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1247 debugstr_w(startup_info->lpReserved));
1249 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1250 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1252 HeapFree( GetProcessHeap(), 0, cur_dirA );
1253 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1254 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1255 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1257 return ret;
1261 /***********************************************************************
1262 * ExitProcess (KERNEL32.@)
1264 void WINAPI ExitProcess( DWORD status )
1266 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1267 SERVER_START_REQ( terminate_process )
1269 /* send the exit code to the server */
1270 req->handle = GetCurrentProcess();
1271 req->exit_code = status;
1272 wine_server_call( req );
1274 SERVER_END_REQ;
1275 exit( status );
1278 /***********************************************************************
1279 * ExitProcess (KERNEL.466)
1281 void WINAPI ExitProcess16( WORD status )
1283 DWORD count;
1284 ReleaseThunkLock( &count );
1285 ExitProcess( status );
1288 /******************************************************************************
1289 * TerminateProcess (KERNEL32.@)
1291 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1293 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1294 if (status) SetLastError( RtlNtStatusToDosError(status) );
1295 return !status;
1299 /***********************************************************************
1300 * GetProcessDword (KERNEL.485)
1301 * GetProcessDword (KERNEL32.18)
1302 * 'Of course you cannot directly access Windows internal structures'
1304 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1306 DWORD x, y;
1308 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1310 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1312 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1313 return 0;
1316 switch ( offset )
1318 case GPD_APP_COMPAT_FLAGS:
1319 return GetAppCompatFlags16(0);
1321 case GPD_LOAD_DONE_EVENT:
1322 return current_process.load_done_evt;
1324 case GPD_HINSTANCE16:
1325 return GetTaskDS16();
1327 case GPD_WINDOWS_VERSION:
1328 return GetExeVersion16();
1330 case GPD_THDB:
1331 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1333 case GPD_PDB:
1334 return (DWORD)&current_process;
1336 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1337 return current_startupinfo.hStdOutput;
1339 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1340 return current_startupinfo.hStdInput;
1342 case GPD_STARTF_SHOWWINDOW:
1343 return current_startupinfo.wShowWindow;
1345 case GPD_STARTF_SIZE:
1346 x = current_startupinfo.dwXSize;
1347 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1348 y = current_startupinfo.dwYSize;
1349 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1350 return MAKELONG( x, y );
1352 case GPD_STARTF_POSITION:
1353 x = current_startupinfo.dwX;
1354 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1355 y = current_startupinfo.dwY;
1356 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1357 return MAKELONG( x, y );
1359 case GPD_STARTF_FLAGS:
1360 return current_startupinfo.dwFlags;
1362 case GPD_PARENT:
1363 return 0;
1365 case GPD_FLAGS:
1366 return current_process.flags;
1368 case GPD_USERDATA:
1369 return current_process.process_dword;
1371 default:
1372 ERR_(win32)("Unknown offset %d\n", offset );
1373 return 0;
1377 /***********************************************************************
1378 * SetProcessDword (KERNEL.484)
1379 * 'Of course you cannot directly access Windows internal structures'
1381 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1383 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1385 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1387 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1388 return;
1391 switch ( offset )
1393 case GPD_APP_COMPAT_FLAGS:
1394 case GPD_LOAD_DONE_EVENT:
1395 case GPD_HINSTANCE16:
1396 case GPD_WINDOWS_VERSION:
1397 case GPD_THDB:
1398 case GPD_PDB:
1399 case GPD_STARTF_SHELLDATA:
1400 case GPD_STARTF_HOTKEY:
1401 case GPD_STARTF_SHOWWINDOW:
1402 case GPD_STARTF_SIZE:
1403 case GPD_STARTF_POSITION:
1404 case GPD_STARTF_FLAGS:
1405 case GPD_PARENT:
1406 case GPD_FLAGS:
1407 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1408 break;
1410 case GPD_USERDATA:
1411 current_process.process_dword = value;
1412 break;
1414 default:
1415 ERR_(win32)("Unknown offset %d\n", offset );
1416 break;
1421 /*********************************************************************
1422 * OpenProcess (KERNEL32.@)
1424 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1426 HANDLE ret = 0;
1427 SERVER_START_REQ( open_process )
1429 req->pid = (void *)id;
1430 req->access = access;
1431 req->inherit = inherit;
1432 if (!wine_server_call_err( req )) ret = reply->handle;
1434 SERVER_END_REQ;
1435 return ret;
1438 /*********************************************************************
1439 * MapProcessHandle (KERNEL.483)
1441 DWORD WINAPI MapProcessHandle( HANDLE handle )
1443 DWORD ret = 0;
1444 SERVER_START_REQ( get_process_info )
1446 req->handle = handle;
1447 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1449 SERVER_END_REQ;
1450 return ret;
1453 /***********************************************************************
1454 * SetPriorityClass (KERNEL32.@)
1456 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1458 BOOL ret;
1459 SERVER_START_REQ( set_process_info )
1461 req->handle = hprocess;
1462 req->priority = priorityclass;
1463 req->mask = SET_PROCESS_INFO_PRIORITY;
1464 ret = !wine_server_call_err( req );
1466 SERVER_END_REQ;
1467 return ret;
1471 /***********************************************************************
1472 * GetPriorityClass (KERNEL32.@)
1474 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1476 DWORD ret = 0;
1477 SERVER_START_REQ( get_process_info )
1479 req->handle = hprocess;
1480 if (!wine_server_call_err( req )) ret = reply->priority;
1482 SERVER_END_REQ;
1483 return ret;
1487 /***********************************************************************
1488 * SetProcessAffinityMask (KERNEL32.@)
1490 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1492 BOOL ret;
1493 SERVER_START_REQ( set_process_info )
1495 req->handle = hProcess;
1496 req->affinity = affmask;
1497 req->mask = SET_PROCESS_INFO_AFFINITY;
1498 ret = !wine_server_call_err( req );
1500 SERVER_END_REQ;
1501 return ret;
1504 /**********************************************************************
1505 * GetProcessAffinityMask (KERNEL32.@)
1507 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1508 LPDWORD lpProcessAffinityMask,
1509 LPDWORD lpSystemAffinityMask )
1511 BOOL ret = FALSE;
1512 SERVER_START_REQ( get_process_info )
1514 req->handle = hProcess;
1515 if (!wine_server_call_err( req ))
1517 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1518 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1519 ret = TRUE;
1522 SERVER_END_REQ;
1523 return ret;
1527 /***********************************************************************
1528 * GetProcessVersion (KERNEL32.@)
1530 DWORD WINAPI GetProcessVersion( DWORD processid )
1532 IMAGE_NT_HEADERS *nt;
1534 if (processid && processid != GetCurrentProcessId())
1536 FIXME("should use ReadProcessMemory\n");
1537 return 0;
1539 if ((nt = RtlImageNtHeader( current_process.module )))
1540 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1541 nt->OptionalHeader.MinorSubsystemVersion);
1542 return 0;
1545 /***********************************************************************
1546 * GetProcessFlags (KERNEL32.@)
1548 DWORD WINAPI GetProcessFlags( DWORD processid )
1550 if (processid && processid != GetCurrentProcessId()) return 0;
1551 return current_process.flags;
1555 /***********************************************************************
1556 * SetProcessWorkingSetSize [KERNEL32.@]
1557 * Sets the min/max working set sizes for a specified process.
1559 * PARAMS
1560 * hProcess [I] Handle to the process of interest
1561 * minset [I] Specifies minimum working set size
1562 * maxset [I] Specifies maximum working set size
1564 * RETURNS STD
1566 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1567 DWORD maxset)
1569 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1570 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1571 /* Trim the working set to zero */
1572 /* Swap the process out of physical RAM */
1574 return TRUE;
1577 /***********************************************************************
1578 * GetProcessWorkingSetSize (KERNEL32.@)
1580 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1581 LPDWORD maxset)
1583 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1584 /* 32 MB working set size */
1585 if (minset) *minset = 32*1024*1024;
1586 if (maxset) *maxset = 32*1024*1024;
1587 return TRUE;
1590 /***********************************************************************
1591 * SetProcessShutdownParameters (KERNEL32.@)
1593 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1594 * Now tracks changes made (but does not act on these changes)
1596 static DWORD shutdown_flags = 0;
1597 static DWORD shutdown_priority = 0x280;
1599 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1601 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1602 shutdown_flags = flags;
1603 shutdown_priority = level;
1604 return TRUE;
1608 /***********************************************************************
1609 * GetProcessShutdownParameters (KERNEL32.@)
1612 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1614 *lpdwLevel = shutdown_priority;
1615 *lpdwFlags = shutdown_flags;
1616 return TRUE;
1620 /***********************************************************************
1621 * SetProcessPriorityBoost (KERNEL32.@)
1623 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1625 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1626 /* Say we can do it. I doubt the program will notice that we don't. */
1627 return TRUE;
1631 /***********************************************************************
1632 * ReadProcessMemory (KERNEL32.@)
1634 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1635 LPDWORD bytes_read )
1637 DWORD res;
1639 SERVER_START_REQ( read_process_memory )
1641 req->handle = process;
1642 req->addr = (void *)addr;
1643 wine_server_set_reply( req, buffer, size );
1644 if ((res = wine_server_call_err( req ))) size = 0;
1646 SERVER_END_REQ;
1647 if (bytes_read) *bytes_read = size;
1648 return !res;
1652 /***********************************************************************
1653 * WriteProcessMemory (KERNEL32.@)
1655 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1656 LPDWORD bytes_written )
1658 static const int zero;
1659 unsigned int first_offset, last_offset, first_mask, last_mask;
1660 DWORD res;
1662 if (!size)
1664 SetLastError( ERROR_INVALID_PARAMETER );
1665 return FALSE;
1668 /* compute the mask for the first int */
1669 first_mask = ~0;
1670 first_offset = (unsigned int)addr % sizeof(int);
1671 memset( &first_mask, 0, first_offset );
1673 /* compute the mask for the last int */
1674 last_offset = (size + first_offset) % sizeof(int);
1675 last_mask = 0;
1676 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1678 SERVER_START_REQ( write_process_memory )
1680 req->handle = process;
1681 req->addr = (char *)addr - first_offset;
1682 req->first_mask = first_mask;
1683 req->last_mask = last_mask;
1684 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1685 wine_server_add_data( req, buffer, size );
1686 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1688 if ((res = wine_server_call_err( req ))) size = 0;
1690 SERVER_END_REQ;
1691 if (bytes_written) *bytes_written = size;
1693 char dummy[32];
1694 DWORD read;
1695 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1697 return !res;
1701 /***********************************************************************
1702 * RegisterServiceProcess (KERNEL.491)
1703 * RegisterServiceProcess (KERNEL32.@)
1705 * A service process calls this function to ensure that it continues to run
1706 * even after a user logged off.
1708 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1710 /* I don't think that Wine needs to do anything in that function */
1711 return 1; /* success */
1714 /***********************************************************************
1715 * GetExitCodeProcess [KERNEL32.@]
1717 * Gets termination status of specified process
1719 * RETURNS
1720 * Success: TRUE
1721 * Failure: FALSE
1723 BOOL WINAPI GetExitCodeProcess(
1724 HANDLE hProcess, /* [in] handle to the process */
1725 LPDWORD lpExitCode) /* [out] address to receive termination status */
1727 BOOL ret;
1728 SERVER_START_REQ( get_process_info )
1730 req->handle = hProcess;
1731 ret = !wine_server_call_err( req );
1732 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1734 SERVER_END_REQ;
1735 return ret;
1739 /***********************************************************************
1740 * SetErrorMode (KERNEL32.@)
1742 UINT WINAPI SetErrorMode( UINT mode )
1744 UINT old = current_process.error_mode;
1745 current_process.error_mode = mode;
1746 return old;
1750 /**************************************************************************
1751 * SetFileApisToOEM (KERNEL32.@)
1753 VOID WINAPI SetFileApisToOEM(void)
1755 current_process.flags |= PDB32_FILE_APIS_OEM;
1759 /**************************************************************************
1760 * SetFileApisToANSI (KERNEL32.@)
1762 VOID WINAPI SetFileApisToANSI(void)
1764 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1768 /******************************************************************************
1769 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1771 * RETURNS
1772 * TRUE: Set of file functions is using ANSI code page
1773 * FALSE: Set of file functions is using OEM code page
1775 BOOL WINAPI AreFileApisANSI(void)
1777 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1781 /***********************************************************************
1782 * GetTickCount (KERNEL32.@)
1784 * Returns the number of milliseconds, modulo 2^32, since the start
1785 * of the wineserver.
1787 DWORD WINAPI GetTickCount(void)
1789 struct timeval t;
1790 gettimeofday( &t, NULL );
1791 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1795 /**********************************************************************
1796 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1798 * Allocates a thread local storage index
1800 * RETURNS
1801 * Success: TLS Index
1802 * Failure: 0xFFFFFFFF
1804 DWORD WINAPI TlsAlloc( void )
1806 DWORD i, mask, ret = 0;
1807 DWORD *bits = current_process.tls_bits;
1808 RtlAcquirePebLock();
1809 if (*bits == 0xffffffff)
1811 bits++;
1812 ret = 32;
1813 if (*bits == 0xffffffff)
1815 RtlReleasePebLock();
1816 SetLastError( ERROR_NO_MORE_ITEMS );
1817 return 0xffffffff;
1820 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1821 *bits |= mask;
1822 RtlReleasePebLock();
1823 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1824 return ret + i;
1828 /**********************************************************************
1829 * TlsFree [KERNEL32.@] Releases a TLS index.
1831 * Releases a thread local storage index, making it available for reuse
1833 * RETURNS
1834 * Success: TRUE
1835 * Failure: FALSE
1837 BOOL WINAPI TlsFree(
1838 DWORD index) /* [in] TLS Index to free */
1840 DWORD mask = (1 << (index & 31));
1841 DWORD *bits = current_process.tls_bits;
1842 if (index >= 64)
1844 SetLastError( ERROR_INVALID_PARAMETER );
1845 return FALSE;
1847 if (index >= 32) bits++;
1848 RtlAcquirePebLock();
1849 if (!(*bits & mask)) /* already free? */
1851 RtlReleasePebLock();
1852 SetLastError( ERROR_INVALID_PARAMETER );
1853 return FALSE;
1855 *bits &= ~mask;
1856 NtCurrentTeb()->tls_array[index] = 0;
1857 /* FIXME: should zero all other thread values */
1858 RtlReleasePebLock();
1859 return TRUE;
1863 /**********************************************************************
1864 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1866 * RETURNS
1867 * Success: Value stored in calling thread's TLS slot for index
1868 * Failure: 0 and GetLastError returns NO_ERROR
1870 LPVOID WINAPI TlsGetValue(
1871 DWORD index) /* [in] TLS index to retrieve value for */
1873 if (index >= 64)
1875 SetLastError( ERROR_INVALID_PARAMETER );
1876 return NULL;
1878 SetLastError( ERROR_SUCCESS );
1879 return NtCurrentTeb()->tls_array[index];
1883 /**********************************************************************
1884 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1886 * RETURNS
1887 * Success: TRUE
1888 * Failure: FALSE
1890 BOOL WINAPI TlsSetValue(
1891 DWORD index, /* [in] TLS index to set value for */
1892 LPVOID value) /* [in] Value to be stored */
1894 if (index >= 64)
1896 SetLastError( ERROR_INVALID_PARAMETER );
1897 return FALSE;
1899 NtCurrentTeb()->tls_array[index] = value;
1900 return TRUE;
1904 /***********************************************************************
1905 * GetCurrentProcess (KERNEL32.@)
1907 #undef GetCurrentProcess
1908 HANDLE WINAPI GetCurrentProcess(void)
1910 return 0xffffffff;