Fixed some issues found by winapi_check.
[wine/multimedia.git] / scheduler / process.c
blob119cf9edb68f661eddaed99a10552f6c931afcc1
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 <stdlib.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include "wine/winbase16.h"
33 #include "wine/winuser16.h"
34 #include "wine/exception.h"
35 #include "wine/library.h"
36 #include "drive.h"
37 #include "module.h"
38 #include "file.h"
39 #include "heap.h"
40 #include "thread.h"
41 #include "winerror.h"
42 #include "wincon.h"
43 #include "wine/server.h"
44 #include "options.h"
45 #include "wine/debug.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(process);
48 WINE_DECLARE_DEBUG_CHANNEL(relay);
49 WINE_DECLARE_DEBUG_CHANNEL(snoop);
50 WINE_DECLARE_DEBUG_CHANNEL(win32);
52 struct _ENVDB;
54 /* Win32 process database */
55 typedef struct _PDB
57 LONG header[2]; /* 00 Kernel object header */
58 HMODULE module; /* 08 Main exe module (NT) */
59 void *event; /* 0c Pointer to an event object (unused) */
60 DWORD exit_code; /* 10 Process exit code */
61 DWORD unknown2; /* 14 Unknown */
62 HANDLE heap; /* 18 Default process heap */
63 HANDLE mem_context; /* 1c Process memory context */
64 DWORD flags; /* 20 Flags */
65 void *pdb16; /* 24 DOS PSP */
66 WORD PSP_sel; /* 28 Selector to DOS PSP */
67 WORD imte; /* 2a IMTE for the process module */
68 WORD threads; /* 2c Number of threads */
69 WORD running_threads; /* 2e Number of running threads */
70 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
71 WORD ring0_threads; /* 32 Number of ring 0 threads */
72 HANDLE system_heap; /* 34 System heap to allocate handles */
73 HTASK task; /* 38 Win16 task */
74 void *mem_map_files; /* 3c Pointer to mem-mapped files */
75 struct _ENVDB *env_db; /* 40 Environment database */
76 void *handle_table; /* 44 Handle table */
77 struct _PDB *parent; /* 48 Parent process */
78 void *modref_list; /* 4c MODREF list */
79 void *thread_list; /* 50 List of threads */
80 void *debuggee_CB; /* 54 Debuggee context block */
81 void *local_heap_free; /* 58 Head of local heap free list */
82 DWORD unknown4; /* 5c Unknown */
83 CRITICAL_SECTION crit_section; /* 60 Critical section */
84 DWORD unknown5[3]; /* 78 Unknown */
85 void *console; /* 84 Console */
86 DWORD tls_bits[2]; /* 88 TLS in-use bits */
87 DWORD process_dword; /* 90 Unknown */
88 struct _PDB *group; /* 94 Process group */
89 void *exe_modref; /* 98 MODREF for the process EXE */
90 void *top_filter; /* 9c Top exception filter */
91 DWORD priority; /* a0 Priority level */
92 HANDLE heap_list; /* a4 Head of process heap list */
93 void *heap_handles; /* a8 Head of heap handles list */
94 DWORD unknown6; /* ac Unknown */
95 void *console_provider; /* b0 Console provider (??) */
96 WORD env_selector; /* b4 Selector to process environment */
97 WORD error_mode; /* b6 Error mode */
98 HANDLE load_done_evt; /* b8 Event for process loading done */
99 void *UTState; /* bc Head of Univeral Thunk list */
100 DWORD unknown8; /* c0 Unknown (NT) */
101 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
102 } PDB;
104 PDB current_process;
106 /* Process flags */
107 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
108 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
109 #define PDB32_DOS_PROC 0x0010 /* Dos process */
110 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
111 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
112 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
114 static char main_exe_name[MAX_PATH];
115 static char *main_exe_name_ptr = main_exe_name;
116 static HANDLE main_exe_file;
117 static int main_create_flags;
119 static unsigned int server_startticks;
121 /* memory/environ.c */
122 extern struct _ENVDB *ENV_InitStartupInfo( size_t info_size, char *main_exe_name,
123 size_t main_exe_size );
124 extern BOOL ENV_BuildCommandLine( char **argv );
125 extern STARTUPINFOA current_startupinfo;
127 /* scheduler/pthread.c */
128 extern void PTHREAD_init_done(void);
130 extern void RELAY_InitDebugLists(void);
131 extern BOOL MAIN_MainInit(void);
133 typedef WORD (WINAPI *pUserSignalProc)( UINT, DWORD, DWORD, HMODULE16 );
135 /***********************************************************************
136 * PROCESS_CallUserSignalProc
138 * FIXME: Some of the signals aren't sent correctly!
140 * The exact meaning of the USER signals is undocumented, but this
141 * should cover the basic idea:
143 * USIG_DLL_UNLOAD_WIN16
144 * This is sent when a 16-bit module is unloaded.
146 * USIG_DLL_UNLOAD_WIN32
147 * This is sent when a 32-bit module is unloaded.
149 * USIG_DLL_UNLOAD_ORPHANS
150 * This is sent after the last Win3.1 module is unloaded,
151 * to allow removal of orphaned menus.
153 * USIG_FAULT_DIALOG_PUSH
154 * USIG_FAULT_DIALOG_POP
155 * These are called to allow USER to prepare for displaying a
156 * fault dialog, even though the fault might have happened while
157 * inside a USER critical section.
159 * USIG_THREAD_INIT
160 * This is called from the context of a new thread, as soon as it
161 * has started to run.
163 * USIG_THREAD_EXIT
164 * This is called, still in its context, just before a thread is
165 * about to terminate.
167 * USIG_PROCESS_CREATE
168 * This is called, in the parent process context, after a new process
169 * has been created.
171 * USIG_PROCESS_INIT
172 * This is called in the new process context, just after the main thread
173 * has started execution (after the main thread's USIG_THREAD_INIT has
174 * been sent).
176 * USIG_PROCESS_LOADED
177 * This is called after the executable file has been loaded into the
178 * new process context.
180 * USIG_PROCESS_RUNNING
181 * This is called immediately before the main entry point is called.
183 * USIG_PROCESS_EXIT
184 * This is called in the context of a process that is about to
185 * terminate (but before the last thread's USIG_THREAD_EXIT has
186 * been sent).
188 * USIG_PROCESS_DESTROY
189 * This is called after a process has terminated.
192 * The meaning of the dwFlags bits is as follows:
194 * USIG_FLAGS_WIN32
195 * Current process is 32-bit.
197 * USIG_FLAGS_GUI
198 * Current process is a (Win32) GUI process.
200 * USIG_FLAGS_FEEDBACK
201 * Current process needs 'feedback' (determined from the STARTUPINFO
202 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
204 * USIG_FLAGS_FAULT
205 * The signal is being sent due to a fault.
207 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
209 DWORD dwFlags = 0;
210 HMODULE user;
211 pUserSignalProc proc;
213 if (!(user = GetModuleHandleA( "user32.dll" ))) return;
214 if (!(proc = (pUserSignalProc)GetProcAddress( user, "UserSignalProc" ))) return;
216 /* Determine dwFlags */
218 if ( !(current_process.flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
219 if ( !(current_process.flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
221 if ( dwFlags & USIG_FLAGS_GUI )
223 /* Feedback defaults to ON */
224 if ( !(current_startupinfo.dwFlags & STARTF_FORCEOFFFEEDBACK) )
225 dwFlags |= USIG_FLAGS_FEEDBACK;
227 else
229 /* Feedback defaults to OFF */
230 if (current_startupinfo.dwFlags & STARTF_FORCEONFEEDBACK)
231 dwFlags |= USIG_FLAGS_FEEDBACK;
234 /* Call USER signal proc */
236 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
237 proc( uCode, GetCurrentThreadId(), dwFlags, hModule );
238 else
239 proc( uCode, GetCurrentProcessId(), dwFlags, hModule );
243 /***********************************************************************
244 * get_basename
246 inline static const char *get_basename( const char *name )
248 char *p;
250 if ((p = strrchr( name, '/' ))) name = p + 1;
251 if ((p = strrchr( name, '\\' ))) name = p + 1;
252 return name;
256 /***********************************************************************
257 * open_exe_file
259 * Open an exe file, taking load order into account.
260 * Returns the file handle or 0 for a builtin exe.
262 static HANDLE open_exe_file( const char *name )
264 enum loadorder_type loadorder[LOADORDER_NTYPES];
265 HANDLE handle;
266 int i;
268 SetLastError( ERROR_FILE_NOT_FOUND );
269 MODULE_GetLoadOrder( loadorder, name, TRUE );
271 for(i = 0; i < LOADORDER_NTYPES; i++)
273 if (loadorder[i] == LOADORDER_INVALID) break;
274 switch(loadorder[i])
276 case LOADORDER_DLL:
277 TRACE( "Trying native exe %s\n", debugstr_a(name) );
278 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
279 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
280 return handle;
281 if (GetLastError() != ERROR_FILE_NOT_FOUND) return INVALID_HANDLE_VALUE;
282 break;
283 case LOADORDER_BI:
284 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
285 if (wine_dll_load_main_exe( get_basename(name), NULL, 0, 1 )) return 0;
286 break;
287 default:
288 break;
291 return INVALID_HANDLE_VALUE;
295 /***********************************************************************
296 * find_exe_file
298 * Open an exe file, and return the full name and file handle.
299 * Returns FALSE if file could not be found.
300 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
301 * If file is a builtin exe, returns TRUE and sets handle to 0.
303 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
305 enum loadorder_type loadorder[LOADORDER_NTYPES];
306 int i;
308 TRACE("looking for %s\n", debugstr_a(name) );
310 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ))
312 *handle = open_exe_file( buffer );
313 return TRUE;
316 /* no such file in path, try builtin with .exe extension */
318 lstrcpynA( buffer, get_basename(name), buflen );
319 if (!strchr( buffer, '.' ))
321 char *p = buffer + strlen(buffer);
322 lstrcpynA( p, ".exe", buflen - (p - buffer) );
325 MODULE_GetLoadOrder( loadorder, buffer, TRUE );
326 for (i = 0; i < LOADORDER_NTYPES; i++)
328 if (loadorder[i] == LOADORDER_BI)
330 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
331 if (wine_dll_load_main_exe( buffer, NULL, 0, 1 ))
333 *handle = 0;
334 return TRUE;
336 break;
338 if (loadorder[i] == LOADORDER_INVALID) break;
341 /* no builtin found, try native without extension in case it is a Unix app */
343 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
345 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
346 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
347 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
348 return TRUE;
350 return FALSE;
354 /***********************************************************************
355 * process_init
357 * Main process initialisation code
359 static BOOL process_init( char *argv[] )
361 BOOL ret;
362 size_t info_size = 0;
364 /* store the program name */
365 argv0 = argv[0];
367 /* Fill the initial process structure */
368 current_process.exit_code = STILL_ACTIVE;
369 current_process.threads = 1;
370 current_process.running_threads = 1;
371 current_process.ring0_threads = 1;
372 current_process.group = &current_process;
373 current_process.priority = 8; /* Normal */
375 /* Setup the server connection */
376 CLIENT_InitServer();
378 /* Retrieve startup info from the server */
379 SERVER_START_REQ( init_process )
381 req->ldt_copy = &wine_ldt_copy;
382 req->ppid = getppid();
383 if ((ret = !wine_server_call_err( req )))
385 main_exe_file = reply->exe_file;
386 main_create_flags = reply->create_flags;
387 info_size = reply->info_size;
388 server_startticks = reply->server_start;
389 current_startupinfo.hStdInput = reply->hstdin;
390 current_startupinfo.hStdOutput = reply->hstdout;
391 current_startupinfo.hStdError = reply->hstderr;
394 SERVER_END_REQ;
395 if (!ret) return FALSE;
397 /* Create the process heap */
398 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
400 if (main_create_flags == 0 &&
401 current_startupinfo.hStdInput == 0 &&
402 current_startupinfo.hStdOutput == 0 &&
403 current_startupinfo.hStdError == 0)
405 /* no parent, and no new console requested, create a simple console with bare handles to
406 * unix stdio input & output streams (aka simple console)
408 HANDLE handle;
409 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &handle );
410 SetStdHandle( STD_INPUT_HANDLE, handle );
411 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
412 SetStdHandle( STD_OUTPUT_HANDLE, handle );
413 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
414 SetStdHandle( STD_ERROR_HANDLE, handle );
416 else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
418 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
419 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
420 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
423 /* Now we can use the pthreads routines */
424 PTHREAD_init_done();
426 /* Copy the parent environment */
427 if (!(current_process.env_db = ENV_InitStartupInfo( info_size, main_exe_name,
428 sizeof(main_exe_name) )))
429 return FALSE;
431 /* Parse command line arguments */
432 OPTIONS_ParseOptions( !info_size ? argv : NULL );
434 ret = MAIN_MainInit();
435 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
437 return ret;
441 /***********************************************************************
442 * start_process
444 * Startup routine of a new process. Runs on the new process stack.
446 static void start_process(void)
448 int debugged, console_app;
449 LPTHREAD_START_ROUTINE entry;
450 WINE_MODREF *wm;
451 HFILE main_file = main_exe_file;
453 /* use original argv[0] as name for the main module */
454 if (!main_exe_name[0])
456 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
457 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
460 if (main_file)
462 UINT drive_type = GetDriveTypeA( main_exe_name );
463 /* don't keep the file handle open on removable media */
464 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
467 /* Retrieve entry point address */
468 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
469 PE_HEADER(current_process.module)->OptionalHeader.AddressOfEntryPoint);
470 console_app = (PE_HEADER(current_process.module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
471 if (console_app)
473 current_process.flags |= PDB32_CONSOLE_PROC;
474 if (main_create_flags & CREATE_NEW_CONSOLE) AllocConsole();
477 /* Signal the parent process to continue */
478 SERVER_START_REQ( init_process_done )
480 req->module = (void *)current_process.module;
481 req->module_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfImage;
482 req->entry = entry;
483 /* API requires a double indirection */
484 req->name = &main_exe_name_ptr;
485 req->exe_file = main_file;
486 req->gui = !console_app;
487 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
488 wine_server_call( req );
489 debugged = reply->debugged;
491 SERVER_END_REQ;
493 /* Install signal handlers; this cannot be done before, since we cannot
494 * send exceptions to the debugger before the create process event that
495 * is sent by REQ_INIT_PROCESS_DONE */
496 if (!SIGNAL_Init()) goto error;
498 /* create the main modref and load dependencies */
499 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
500 goto error;
501 wm->refCount++;
503 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
505 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
507 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
508 * context of the parent process. Actually, the USER signal proc
509 * doesn't really care about that, but it *does* require that the
510 * startup parameters are correctly set up, so that GetProcessDword
511 * works. Furthermore, before calling the USER signal proc the
512 * 16-bit stack must be set up, which it is only after TASK_Create
513 * in the case of a 16-bit process. Thus, we send the signal here.
515 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
516 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
517 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
518 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
519 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
520 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
522 if (TRACE_ON(relay))
523 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
524 GetCurrentThreadId(), main_exe_name, entry );
525 if (debugged) DbgBreakPoint();
526 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
527 * Dunno about other OSs */
528 SetLastError(0); /* clear error code */
529 ExitThread( entry(NULL) );
531 error:
532 ExitProcess( GetLastError() );
536 /***********************************************************************
537 * PROCESS_InitWine
539 * Wine initialisation: load and start the main exe file.
541 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
543 char error[100];
544 DWORD stack_size = 0;
546 /* Initialize everything */
547 if (!process_init( argv )) exit(1);
549 argv++; /* remove argv[0] (wine itself) */
551 TRACE( "starting process name=%s file=%x argv[0]=%s\n",
552 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
554 if (!main_exe_name[0])
556 if (!argv[0]) OPTIONS_Usage();
558 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
560 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
561 ExitProcess(1);
563 if (main_exe_file == INVALID_HANDLE_VALUE)
565 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
566 ExitProcess(1);
570 if (!main_exe_file) /* no file handle -> Winelib app */
572 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
573 if (wine_dll_load_main_exe( get_basename(main_exe_name), error, sizeof(error), 0 ))
574 goto found;
575 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
576 ExitProcess(1);
579 switch( MODULE_GetBinaryType( main_exe_file ))
581 case BINARY_UNKNOWN:
582 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
583 ExitProcess(1);
584 case BINARY_PE_EXE:
585 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
586 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
587 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
588 ExitProcess(1);
589 case BINARY_PE_DLL:
590 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
591 ExitProcess(1);
592 case BINARY_WIN16:
593 case BINARY_DOS:
594 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
595 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
596 current_process.flags |= PDB32_WIN16_PROC;
597 strcpy( win16_exe_name, main_exe_name );
598 main_exe_name[0] = 0;
599 *win16_exe_file = main_exe_file;
600 main_exe_file = 0;
601 _EnterWin16Lock();
602 goto found;
603 case BINARY_OS216:
604 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
605 ExitProcess(1);
606 case BINARY_UNIX_EXE:
607 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
608 ExitProcess(1);
609 case BINARY_UNIX_LIB:
611 DOS_FULL_NAME full_name;
612 const char *name = main_exe_name;
614 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
615 if (DOSFS_GetFullName( name, TRUE, &full_name )) name = full_name.long_name;
616 CloseHandle( main_exe_file );
617 main_exe_file = 0;
618 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) )) goto found;
619 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
620 ExitProcess(1);
624 found:
625 /* build command line */
626 if (!ENV_BuildCommandLine( argv )) goto error;
628 /* create 32-bit module for main exe */
629 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
630 stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
632 /* allocate main thread stack */
633 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
635 /* switch to the new stack */
636 SYSDEPS_SwitchToThreadStack( start_process );
638 error:
639 ExitProcess( GetLastError() );
643 /***********************************************************************
644 * build_argv
646 * Build an argv array from a command-line.
647 * The command-line is modified to insert nulls.
648 * 'reserved' is the number of args to reserve before the first one.
650 static char **build_argv( char *cmdline, int reserved )
652 int argc;
653 char** argv;
654 char *arg,*s,*d;
655 int in_quotes,bcount;
657 argc=reserved+1;
658 bcount=0;
659 in_quotes=0;
660 s=cmdline;
661 while (1) {
662 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
663 /* space */
664 argc++;
665 /* skip the remaining spaces */
666 while (*s==' ' || *s=='\t') {
667 s++;
669 if (*s=='\0')
670 break;
671 bcount=0;
672 continue;
673 } else if (*s=='\\') {
674 /* '\', count them */
675 bcount++;
676 } else if ((*s=='"') && ((bcount & 1)==0)) {
677 /* unescaped '"' */
678 in_quotes=!in_quotes;
679 bcount=0;
680 } else {
681 /* a regular character */
682 bcount=0;
684 s++;
686 argv=malloc(argc*sizeof(*argv));
687 if (!argv)
688 return NULL;
690 arg=d=s=cmdline;
691 bcount=0;
692 in_quotes=0;
693 argc=reserved;
694 while (*s) {
695 if ((*s==' ' || *s=='\t') && !in_quotes) {
696 /* Close the argument and copy it */
697 *d=0;
698 argv[argc++]=arg;
700 /* skip the remaining spaces */
701 do {
702 s++;
703 } while (*s==' ' || *s=='\t');
705 /* Start with a new argument */
706 arg=d=s;
707 bcount=0;
708 } else if (*s=='\\') {
709 /* '\\' */
710 *d++=*s++;
711 bcount++;
712 } else if (*s=='"') {
713 /* '"' */
714 if ((bcount & 1)==0) {
715 /* Preceeded by an even number of '\', this is half that
716 * number of '\', plus a '"' which we discard.
718 d-=bcount/2;
719 s++;
720 in_quotes=!in_quotes;
721 } else {
722 /* Preceeded by an odd number of '\', this is half that
723 * number of '\' followed by a '"'
725 d=d-bcount/2-1;
726 *d++='"';
727 s++;
729 bcount=0;
730 } else {
731 /* a regular character */
732 *d++=*s++;
733 bcount=0;
736 if (*arg) {
737 *d='\0';
738 argv[argc++]=arg;
740 argv[argc]=NULL;
742 return argv;
746 /***********************************************************************
747 * build_envp
749 * Build the environment of a new child process.
751 static char **build_envp( const char *env, const char *extra_env )
753 const char *p;
754 char **envp;
755 int count = 0;
757 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
758 for (p = env; *p; count++) p += strlen(p) + 1;
759 count += 3;
761 if ((envp = malloc( count * sizeof(*envp) )))
763 extern char **environ;
764 char **envptr = envp;
765 char **unixptr = environ;
766 /* first the extra strings */
767 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
768 /* then put PATH, HOME and WINEPREFIX from the unix env */
769 for (unixptr = environ; unixptr && *unixptr; unixptr++)
770 if (!memcmp( *unixptr, "PATH=", 5 ) ||
771 !memcmp( *unixptr, "HOME=", 5 ) ||
772 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
773 /* now put the Windows environment strings */
774 for (p = env; *p; p += strlen(p) + 1)
776 if (memcmp( p, "PATH=", 5 ) &&
777 memcmp( p, "HOME=", 5 ) &&
778 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
780 *envptr = 0;
782 return envp;
786 /***********************************************************************
787 * exec_wine_binary
789 * Locate the Wine binary to exec for a new Win32 process.
791 static void exec_wine_binary( char **argv, char **envp )
793 const char *path, *pos, *ptr;
795 /* first, try for a WINELOADER environment variable */
796 argv[0] = getenv("WINELOADER");
797 if (argv[0])
798 execve( argv[0], argv, envp );
800 /* next, try bin directory */
801 argv[0] = BINDIR "/wine";
802 execve( argv[0], argv, envp );
804 /* now try the path of argv0 of the current binary */
805 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
806 if ((ptr = strrchr( full_argv0, '/' )))
808 memcpy( argv[0], full_argv0, ptr - full_argv0 );
809 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
810 execve( argv[0], argv, envp );
812 free( argv[0] );
814 /* now search in the Unix path */
815 if ((path = getenv( "PATH" )))
817 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
818 pos = path;
819 for (;;)
821 while (*pos == ':') pos++;
822 if (!*pos) break;
823 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
824 memcpy( argv[0], pos, ptr - pos );
825 strcpy( argv[0] + (ptr - pos), "/wine" );
826 execve( argv[0], argv, envp );
827 pos = ptr;
830 free( argv[0] );
834 /***********************************************************************
835 * fork_and_exec
837 * Fork and exec a new Unix process, checking for errors.
839 static int fork_and_exec( const char *filename, char *cmdline,
840 const char *env, const char *newdir )
842 int fd[2];
843 int pid, err;
844 char *extra_env = NULL;
846 if (!env)
848 env = GetEnvironmentStringsA();
849 extra_env = DRIVE_BuildEnv();
852 if (pipe(fd) == -1)
854 FILE_SetDosError();
855 return -1;
857 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
858 if (!(pid = fork())) /* child */
860 char **argv = build_argv( cmdline, filename ? 0 : 1 );
861 char **envp = build_envp( env, extra_env );
862 close( fd[0] );
864 if (newdir) chdir(newdir);
866 if (argv && envp)
868 if (!filename) exec_wine_binary( argv, envp );
869 else execve( filename, argv, envp );
871 err = errno;
872 write( fd[1], &err, sizeof(err) );
873 _exit(1);
875 close( fd[1] );
876 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
878 errno = err;
879 pid = -1;
881 if (pid == -1) FILE_SetDosError();
882 close( fd[0] );
883 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
884 return pid;
888 /***********************************************************************
889 * create_process
891 * Create a new process. If hFile is a valid handle we have an exe
892 * file, otherwise it is a Winelib app.
894 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
895 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
896 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
897 LPPROCESS_INFORMATION info, LPCSTR unixdir )
899 BOOL ret, success = FALSE;
900 HANDLE process_info;
901 startup_info_t startup_info;
903 /* fill the startup info structure */
905 startup_info.size = sizeof(startup_info);
906 /* startup_info.filename_len is set below */
907 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
908 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
909 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
910 startup_info.x = startup->dwX;
911 startup_info.y = startup->dwY;
912 startup_info.cx = startup->dwXSize;
913 startup_info.cy = startup->dwYSize;
914 startup_info.x_chars = startup->dwXCountChars;
915 startup_info.y_chars = startup->dwYCountChars;
916 startup_info.attribute = startup->dwFillAttribute;
917 startup_info.cmd_show = startup->wShowWindow;
918 startup_info.flags = startup->dwFlags;
920 /* create the process on the server side */
922 SERVER_START_REQ( new_process )
924 char buf[MAX_PATH];
925 LPCSTR nameptr;
927 req->inherit_all = inherit;
928 req->create_flags = flags;
929 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
930 req->exe_file = hFile;
931 if (startup->dwFlags & STARTF_USESTDHANDLES)
933 req->hstdin = startup->hStdInput;
934 req->hstdout = startup->hStdOutput;
935 req->hstderr = startup->hStdError;
937 else
939 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
940 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
941 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
944 if (GetLongPathNameA( filename, buf, MAX_PATH ))
945 nameptr = buf;
946 else
947 nameptr = filename;
949 startup_info.filename_len = strlen(nameptr);
950 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
951 wine_server_add_data( req, nameptr, startup_info.filename_len );
952 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
953 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
954 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
956 ret = !wine_server_call_err( req );
957 process_info = reply->info;
959 SERVER_END_REQ;
960 if (!ret) return FALSE;
962 /* fork and execute */
964 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
966 CloseHandle( process_info );
967 return FALSE;
970 /* wait for the new process info to be ready */
972 WaitForSingleObject( process_info, INFINITE );
973 SERVER_START_REQ( get_new_process_info )
975 req->info = process_info;
976 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
977 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
978 if ((ret = !wine_server_call_err( req )))
980 info->dwProcessId = (DWORD)reply->pid;
981 info->dwThreadId = (DWORD)reply->tid;
982 info->hProcess = reply->phandle;
983 info->hThread = reply->thandle;
984 success = reply->success;
987 SERVER_END_REQ;
989 if (ret && !success) /* new process failed to start */
991 DWORD exitcode;
992 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
993 CloseHandle( info->hThread );
994 CloseHandle( info->hProcess );
995 ret = FALSE;
997 CloseHandle( process_info );
998 return ret;
1002 /*************************************************************************
1003 * get_file_name
1005 * Helper for CreateProcess: retrieve the file name to load from the
1006 * app name and command line. Store the file name in buffer, and
1007 * return a possibly modified command line.
1008 * Also returns a handle to the opened file if it's a Windows binary.
1010 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1011 int buflen, HANDLE *handle )
1013 char *name, *pos, *ret = NULL;
1014 const char *p;
1016 /* if we have an app name, everything is easy */
1018 if (appname)
1020 /* use the unmodified app name as file name */
1021 lstrcpynA( buffer, appname, buflen );
1022 *handle = open_exe_file( buffer );
1023 if (!(ret = cmdline))
1025 /* no command-line, create one */
1026 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1027 sprintf( ret, "\"%s\"", appname );
1029 return ret;
1032 if (!cmdline)
1034 SetLastError( ERROR_INVALID_PARAMETER );
1035 return NULL;
1038 /* first check for a quoted file name */
1040 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1042 int len = p - cmdline - 1;
1043 /* extract the quoted portion as file name */
1044 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1045 memcpy( name, cmdline + 1, len );
1046 name[len] = 0;
1048 if (find_exe_file( name, buffer, buflen, handle ))
1049 ret = cmdline; /* no change necessary */
1050 goto done;
1053 /* now try the command-line word by word */
1055 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1056 pos = name;
1057 p = cmdline;
1059 while (*p)
1061 do *pos++ = *p++; while (*p && *p != ' ');
1062 *pos = 0;
1063 if (find_exe_file( name, buffer, buflen, handle ))
1065 ret = cmdline;
1066 break;
1070 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1072 /* now build a new command-line with quotes */
1074 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1075 sprintf( ret, "\"%s\"%s", name, p );
1077 done:
1078 HeapFree( GetProcessHeap(), 0, name );
1079 return ret;
1083 /**********************************************************************
1084 * CreateProcessA (KERNEL32.@)
1086 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1087 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1088 DWORD flags, LPVOID env, LPCSTR cur_dir,
1089 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1091 BOOL retv = FALSE;
1092 HANDLE hFile = 0;
1093 const char *unixdir = NULL;
1094 DOS_FULL_NAME full_dir;
1095 char name[MAX_PATH];
1096 LPSTR tidy_cmdline;
1098 /* Process the AppName and/or CmdLine to get module name and path */
1100 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1102 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1103 return FALSE;
1104 if (hFile == INVALID_HANDLE_VALUE) goto done;
1106 /* Warn if unsupported features are used */
1108 if (flags & NORMAL_PRIORITY_CLASS)
1109 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1110 if (flags & IDLE_PRIORITY_CLASS)
1111 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1112 if (flags & HIGH_PRIORITY_CLASS)
1113 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1114 if (flags & REALTIME_PRIORITY_CLASS)
1115 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1116 if (flags & CREATE_NEW_PROCESS_GROUP)
1117 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1118 if (flags & CREATE_UNICODE_ENVIRONMENT)
1119 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1120 if (flags & CREATE_SEPARATE_WOW_VDM)
1121 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1122 if (flags & CREATE_SHARED_WOW_VDM)
1123 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1124 if (flags & CREATE_DEFAULT_ERROR_MODE)
1125 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1126 if (flags & CREATE_NO_WINDOW)
1127 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1128 if (flags & PROFILE_USER)
1129 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1130 if (flags & PROFILE_KERNEL)
1131 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1132 if (flags & PROFILE_SERVER)
1133 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1134 if (startup_info->lpDesktop)
1135 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1136 name, debugstr_a(startup_info->lpDesktop));
1137 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1138 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1139 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1140 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1141 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1142 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1143 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1144 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1146 if (cur_dir)
1148 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir ))
1149 unixdir = full_dir.long_name;
1151 else
1153 char buf[MAX_PATH];
1154 if (GetCurrentDirectoryA(sizeof(buf),buf))
1156 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1160 info->hThread = info->hProcess = 0;
1161 info->dwProcessId = info->dwThreadId = 0;
1163 /* Determine executable type */
1165 if (!hFile) /* builtin exe */
1167 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1168 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1169 inherit, flags, startup_info, info, unixdir );
1170 goto done;
1173 switch( MODULE_GetBinaryType( hFile ))
1175 case BINARY_PE_EXE:
1176 case BINARY_WIN16:
1177 case BINARY_DOS:
1178 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1179 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1180 inherit, flags, startup_info, info, unixdir );
1181 break;
1182 case BINARY_OS216:
1183 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1184 SetLastError( ERROR_BAD_EXE_FORMAT );
1185 break;
1186 case BINARY_PE_DLL:
1187 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1188 SetLastError( ERROR_BAD_EXE_FORMAT );
1189 break;
1190 case BINARY_UNIX_LIB:
1191 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1192 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1193 inherit, flags, startup_info, info, unixdir );
1194 break;
1195 case BINARY_UNIX_EXE:
1196 case BINARY_UNKNOWN:
1198 /* unknown file, try as unix executable */
1200 DOS_FULL_NAME full_name;
1201 const char *unixfilename = name;
1203 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1204 if (DOSFS_GetFullName( name, TRUE, &full_name )) unixfilename = full_name.long_name;
1205 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1207 break;
1209 CloseHandle( hFile );
1211 done:
1212 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1213 return retv;
1217 /**********************************************************************
1218 * CreateProcessW (KERNEL32.@)
1219 * NOTES
1220 * lpReserved is not converted
1222 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1223 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1224 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1225 LPPROCESS_INFORMATION info )
1227 BOOL ret;
1228 STARTUPINFOA StartupInfoA;
1230 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1231 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1232 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1234 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1235 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1236 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1238 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1240 if (startup_info->lpReserved)
1241 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1242 debugstr_w(startup_info->lpReserved));
1244 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1245 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1247 HeapFree( GetProcessHeap(), 0, cur_dirA );
1248 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1249 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1250 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1252 return ret;
1256 /***********************************************************************
1257 * ExitProcess (KERNEL32.@)
1259 void WINAPI ExitProcess( DWORD status )
1261 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1262 SERVER_START_REQ( terminate_process )
1264 /* send the exit code to the server */
1265 req->handle = GetCurrentProcess();
1266 req->exit_code = status;
1267 wine_server_call( req );
1269 SERVER_END_REQ;
1270 exit( status );
1273 /***********************************************************************
1274 * ExitProcess (KERNEL.466)
1276 void WINAPI ExitProcess16( WORD status )
1278 DWORD count;
1279 ReleaseThunkLock( &count );
1280 ExitProcess( status );
1283 /******************************************************************************
1284 * TerminateProcess (KERNEL32.@)
1286 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1288 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1289 if (status) SetLastError( RtlNtStatusToDosError(status) );
1290 return !status;
1294 /***********************************************************************
1295 * GetProcessDword (KERNEL.485)
1296 * GetProcessDword (KERNEL32.18)
1297 * 'Of course you cannot directly access Windows internal structures'
1299 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1301 DWORD x, y;
1303 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1305 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1307 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1308 return 0;
1311 switch ( offset )
1313 case GPD_APP_COMPAT_FLAGS:
1314 return GetAppCompatFlags16(0);
1316 case GPD_LOAD_DONE_EVENT:
1317 return current_process.load_done_evt;
1319 case GPD_HINSTANCE16:
1320 return GetTaskDS16();
1322 case GPD_WINDOWS_VERSION:
1323 return GetExeVersion16();
1325 case GPD_THDB:
1326 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1328 case GPD_PDB:
1329 return (DWORD)&current_process;
1331 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1332 return current_startupinfo.hStdOutput;
1334 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1335 return current_startupinfo.hStdInput;
1337 case GPD_STARTF_SHOWWINDOW:
1338 return current_startupinfo.wShowWindow;
1340 case GPD_STARTF_SIZE:
1341 x = current_startupinfo.dwXSize;
1342 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1343 y = current_startupinfo.dwYSize;
1344 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1345 return MAKELONG( x, y );
1347 case GPD_STARTF_POSITION:
1348 x = current_startupinfo.dwX;
1349 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1350 y = current_startupinfo.dwY;
1351 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1352 return MAKELONG( x, y );
1354 case GPD_STARTF_FLAGS:
1355 return current_startupinfo.dwFlags;
1357 case GPD_PARENT:
1358 return 0;
1360 case GPD_FLAGS:
1361 return current_process.flags;
1363 case GPD_USERDATA:
1364 return current_process.process_dword;
1366 default:
1367 ERR_(win32)("Unknown offset %d\n", offset );
1368 return 0;
1372 /***********************************************************************
1373 * SetProcessDword (KERNEL.484)
1374 * 'Of course you cannot directly access Windows internal structures'
1376 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1378 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1380 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1382 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1383 return;
1386 switch ( offset )
1388 case GPD_APP_COMPAT_FLAGS:
1389 case GPD_LOAD_DONE_EVENT:
1390 case GPD_HINSTANCE16:
1391 case GPD_WINDOWS_VERSION:
1392 case GPD_THDB:
1393 case GPD_PDB:
1394 case GPD_STARTF_SHELLDATA:
1395 case GPD_STARTF_HOTKEY:
1396 case GPD_STARTF_SHOWWINDOW:
1397 case GPD_STARTF_SIZE:
1398 case GPD_STARTF_POSITION:
1399 case GPD_STARTF_FLAGS:
1400 case GPD_PARENT:
1401 case GPD_FLAGS:
1402 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1403 break;
1405 case GPD_USERDATA:
1406 current_process.process_dword = value;
1407 break;
1409 default:
1410 ERR_(win32)("Unknown offset %d\n", offset );
1411 break;
1416 /*********************************************************************
1417 * OpenProcess (KERNEL32.@)
1419 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1421 HANDLE ret = 0;
1422 SERVER_START_REQ( open_process )
1424 req->pid = (void *)id;
1425 req->access = access;
1426 req->inherit = inherit;
1427 if (!wine_server_call_err( req )) ret = reply->handle;
1429 SERVER_END_REQ;
1430 return ret;
1433 /*********************************************************************
1434 * MapProcessHandle (KERNEL.483)
1436 DWORD WINAPI MapProcessHandle( HANDLE handle )
1438 DWORD ret = 0;
1439 SERVER_START_REQ( get_process_info )
1441 req->handle = handle;
1442 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1444 SERVER_END_REQ;
1445 return ret;
1448 /***********************************************************************
1449 * SetPriorityClass (KERNEL32.@)
1451 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1453 BOOL ret;
1454 SERVER_START_REQ( set_process_info )
1456 req->handle = hprocess;
1457 req->priority = priorityclass;
1458 req->mask = SET_PROCESS_INFO_PRIORITY;
1459 ret = !wine_server_call_err( req );
1461 SERVER_END_REQ;
1462 return ret;
1466 /***********************************************************************
1467 * GetPriorityClass (KERNEL32.@)
1469 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1471 DWORD ret = 0;
1472 SERVER_START_REQ( get_process_info )
1474 req->handle = hprocess;
1475 if (!wine_server_call_err( req )) ret = reply->priority;
1477 SERVER_END_REQ;
1478 return ret;
1482 /***********************************************************************
1483 * SetProcessAffinityMask (KERNEL32.@)
1485 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1487 BOOL ret;
1488 SERVER_START_REQ( set_process_info )
1490 req->handle = hProcess;
1491 req->affinity = affmask;
1492 req->mask = SET_PROCESS_INFO_AFFINITY;
1493 ret = !wine_server_call_err( req );
1495 SERVER_END_REQ;
1496 return ret;
1499 /**********************************************************************
1500 * GetProcessAffinityMask (KERNEL32.@)
1502 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1503 LPDWORD lpProcessAffinityMask,
1504 LPDWORD lpSystemAffinityMask )
1506 BOOL ret = FALSE;
1507 SERVER_START_REQ( get_process_info )
1509 req->handle = hProcess;
1510 if (!wine_server_call_err( req ))
1512 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1513 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1514 ret = TRUE;
1517 SERVER_END_REQ;
1518 return ret;
1522 /***********************************************************************
1523 * GetProcessVersion (KERNEL32.@)
1525 DWORD WINAPI GetProcessVersion( DWORD processid )
1527 IMAGE_NT_HEADERS *nt;
1529 if (processid && processid != GetCurrentProcessId())
1531 FIXME("should use ReadProcessMemory\n");
1532 return 0;
1534 if ((nt = RtlImageNtHeader( current_process.module )))
1535 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1536 nt->OptionalHeader.MinorSubsystemVersion);
1537 return 0;
1540 /***********************************************************************
1541 * GetProcessFlags (KERNEL32.@)
1543 DWORD WINAPI GetProcessFlags( DWORD processid )
1545 if (processid && processid != GetCurrentProcessId()) return 0;
1546 return current_process.flags;
1550 /***********************************************************************
1551 * SetProcessWorkingSetSize [KERNEL32.@]
1552 * Sets the min/max working set sizes for a specified process.
1554 * PARAMS
1555 * hProcess [I] Handle to the process of interest
1556 * minset [I] Specifies minimum working set size
1557 * maxset [I] Specifies maximum working set size
1559 * RETURNS STD
1561 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1562 DWORD maxset)
1564 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1565 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1566 /* Trim the working set to zero */
1567 /* Swap the process out of physical RAM */
1569 return TRUE;
1572 /***********************************************************************
1573 * GetProcessWorkingSetSize (KERNEL32.@)
1575 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1576 LPDWORD maxset)
1578 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1579 /* 32 MB working set size */
1580 if (minset) *minset = 32*1024*1024;
1581 if (maxset) *maxset = 32*1024*1024;
1582 return TRUE;
1585 /***********************************************************************
1586 * SetProcessShutdownParameters (KERNEL32.@)
1588 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1589 * Now tracks changes made (but does not act on these changes)
1591 static DWORD shutdown_flags = 0;
1592 static DWORD shutdown_priority = 0x280;
1594 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1596 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1597 shutdown_flags = flags;
1598 shutdown_priority = level;
1599 return TRUE;
1603 /***********************************************************************
1604 * GetProcessShutdownParameters (KERNEL32.@)
1607 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1609 *lpdwLevel = shutdown_priority;
1610 *lpdwFlags = shutdown_flags;
1611 return TRUE;
1615 /***********************************************************************
1616 * SetProcessPriorityBoost (KERNEL32.@)
1618 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1620 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1621 /* Say we can do it. I doubt the program will notice that we don't. */
1622 return TRUE;
1626 /***********************************************************************
1627 * ReadProcessMemory (KERNEL32.@)
1629 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1630 LPDWORD bytes_read )
1632 DWORD res;
1634 SERVER_START_REQ( read_process_memory )
1636 req->handle = process;
1637 req->addr = (void *)addr;
1638 wine_server_set_reply( req, buffer, size );
1639 if ((res = wine_server_call_err( req ))) size = 0;
1641 SERVER_END_REQ;
1642 if (bytes_read) *bytes_read = size;
1643 return !res;
1647 /***********************************************************************
1648 * WriteProcessMemory (KERNEL32.@)
1650 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1651 LPDWORD bytes_written )
1653 static const int zero;
1654 unsigned int first_offset, last_offset, first_mask, last_mask;
1655 DWORD res;
1657 if (!size)
1659 SetLastError( ERROR_INVALID_PARAMETER );
1660 return FALSE;
1663 /* compute the mask for the first int */
1664 first_mask = ~0;
1665 first_offset = (unsigned int)addr % sizeof(int);
1666 memset( &first_mask, 0, first_offset );
1668 /* compute the mask for the last int */
1669 last_offset = (size + first_offset) % sizeof(int);
1670 last_mask = 0;
1671 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1673 SERVER_START_REQ( write_process_memory )
1675 req->handle = process;
1676 req->addr = (char *)addr - first_offset;
1677 req->first_mask = first_mask;
1678 req->last_mask = last_mask;
1679 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1680 wine_server_add_data( req, buffer, size );
1681 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1683 if ((res = wine_server_call_err( req ))) size = 0;
1685 SERVER_END_REQ;
1686 if (bytes_written) *bytes_written = size;
1688 char dummy[32];
1689 DWORD read;
1690 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1692 return !res;
1696 /***********************************************************************
1697 * RegisterServiceProcess (KERNEL.491)
1698 * RegisterServiceProcess (KERNEL32.@)
1700 * A service process calls this function to ensure that it continues to run
1701 * even after a user logged off.
1703 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1705 /* I don't think that Wine needs to do anything in that function */
1706 return 1; /* success */
1709 /***********************************************************************
1710 * GetExitCodeProcess [KERNEL32.@]
1712 * Gets termination status of specified process
1714 * RETURNS
1715 * Success: TRUE
1716 * Failure: FALSE
1718 BOOL WINAPI GetExitCodeProcess(
1719 HANDLE hProcess, /* [in] handle to the process */
1720 LPDWORD lpExitCode) /* [out] address to receive termination status */
1722 BOOL ret;
1723 SERVER_START_REQ( get_process_info )
1725 req->handle = hProcess;
1726 ret = !wine_server_call_err( req );
1727 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1729 SERVER_END_REQ;
1730 return ret;
1734 /***********************************************************************
1735 * SetErrorMode (KERNEL32.@)
1737 UINT WINAPI SetErrorMode( UINT mode )
1739 UINT old = current_process.error_mode;
1740 current_process.error_mode = mode;
1741 return old;
1745 /**************************************************************************
1746 * SetFileApisToOEM (KERNEL32.@)
1748 VOID WINAPI SetFileApisToOEM(void)
1750 current_process.flags |= PDB32_FILE_APIS_OEM;
1754 /**************************************************************************
1755 * SetFileApisToANSI (KERNEL32.@)
1757 VOID WINAPI SetFileApisToANSI(void)
1759 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1763 /******************************************************************************
1764 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1766 * RETURNS
1767 * TRUE: Set of file functions is using ANSI code page
1768 * FALSE: Set of file functions is using OEM code page
1770 BOOL WINAPI AreFileApisANSI(void)
1772 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1776 /***********************************************************************
1777 * GetTickCount (KERNEL32.@)
1779 * Returns the number of milliseconds, modulo 2^32, since the start
1780 * of the wineserver.
1782 DWORD WINAPI GetTickCount(void)
1784 struct timeval t;
1785 gettimeofday( &t, NULL );
1786 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1790 /**********************************************************************
1791 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1793 * Allocates a thread local storage index
1795 * RETURNS
1796 * Success: TLS Index
1797 * Failure: 0xFFFFFFFF
1799 DWORD WINAPI TlsAlloc( void )
1801 DWORD i, mask, ret = 0;
1802 DWORD *bits = current_process.tls_bits;
1803 RtlAcquirePebLock();
1804 if (*bits == 0xffffffff)
1806 bits++;
1807 ret = 32;
1808 if (*bits == 0xffffffff)
1810 RtlReleasePebLock();
1811 SetLastError( ERROR_NO_MORE_ITEMS );
1812 return 0xffffffff;
1815 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1816 *bits |= mask;
1817 RtlReleasePebLock();
1818 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1819 return ret + i;
1823 /**********************************************************************
1824 * TlsFree [KERNEL32.@] Releases a TLS index.
1826 * Releases a thread local storage index, making it available for reuse
1828 * RETURNS
1829 * Success: TRUE
1830 * Failure: FALSE
1832 BOOL WINAPI TlsFree(
1833 DWORD index) /* [in] TLS Index to free */
1835 DWORD mask = (1 << (index & 31));
1836 DWORD *bits = current_process.tls_bits;
1837 if (index >= 64)
1839 SetLastError( ERROR_INVALID_PARAMETER );
1840 return FALSE;
1842 if (index >= 32) bits++;
1843 RtlAcquirePebLock();
1844 if (!(*bits & mask)) /* already free? */
1846 RtlReleasePebLock();
1847 SetLastError( ERROR_INVALID_PARAMETER );
1848 return FALSE;
1850 *bits &= ~mask;
1851 NtCurrentTeb()->tls_array[index] = 0;
1852 /* FIXME: should zero all other thread values */
1853 RtlReleasePebLock();
1854 return TRUE;
1858 /**********************************************************************
1859 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1861 * RETURNS
1862 * Success: Value stored in calling thread's TLS slot for index
1863 * Failure: 0 and GetLastError returns NO_ERROR
1865 LPVOID WINAPI TlsGetValue(
1866 DWORD index) /* [in] TLS index to retrieve value for */
1868 if (index >= 64)
1870 SetLastError( ERROR_INVALID_PARAMETER );
1871 return NULL;
1873 SetLastError( ERROR_SUCCESS );
1874 return NtCurrentTeb()->tls_array[index];
1878 /**********************************************************************
1879 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1881 * RETURNS
1882 * Success: TRUE
1883 * Failure: FALSE
1885 BOOL WINAPI TlsSetValue(
1886 DWORD index, /* [in] TLS index to set value for */
1887 LPVOID value) /* [in] Value to be stored */
1889 if (index >= 64)
1891 SetLastError( ERROR_INVALID_PARAMETER );
1892 return FALSE;
1894 NtCurrentTeb()->tls_array[index] = value;
1895 return TRUE;
1899 /***********************************************************************
1900 * GetCurrentProcess (KERNEL32.@)
1902 #undef GetCurrentProcess
1903 HANDLE WINAPI GetCurrentProcess(void)
1905 return 0xffffffff;