Support querying of number of visuals without reporting an error or
[wine/hacks.git] / scheduler / process.c
blobe611b55b9b8f8d2201374a21750606d84b3059e2
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(win32);
51 struct _ENVDB;
53 /* Win32 process database */
54 typedef struct _PDB
56 LONG header[2]; /* 00 Kernel object header */
57 HMODULE module; /* 08 Main exe module (NT) */
58 void *event; /* 0c Pointer to an event object (unused) */
59 DWORD exit_code; /* 10 Process exit code */
60 DWORD unknown2; /* 14 Unknown */
61 HANDLE heap; /* 18 Default process heap */
62 HANDLE mem_context; /* 1c Process memory context */
63 DWORD flags; /* 20 Flags */
64 void *pdb16; /* 24 DOS PSP */
65 WORD PSP_sel; /* 28 Selector to DOS PSP */
66 WORD imte; /* 2a IMTE for the process module */
67 WORD threads; /* 2c Number of threads */
68 WORD running_threads; /* 2e Number of running threads */
69 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
70 WORD ring0_threads; /* 32 Number of ring 0 threads */
71 HANDLE system_heap; /* 34 System heap to allocate handles */
72 HTASK task; /* 38 Win16 task */
73 void *mem_map_files; /* 3c Pointer to mem-mapped files */
74 struct _ENVDB *env_db; /* 40 Environment database */
75 void *handle_table; /* 44 Handle table */
76 struct _PDB *parent; /* 48 Parent process */
77 void *modref_list; /* 4c MODREF list */
78 void *thread_list; /* 50 List of threads */
79 void *debuggee_CB; /* 54 Debuggee context block */
80 void *local_heap_free; /* 58 Head of local heap free list */
81 DWORD unknown4; /* 5c Unknown */
82 CRITICAL_SECTION crit_section; /* 60 Critical section */
83 DWORD unknown5[3]; /* 78 Unknown */
84 void *console; /* 84 Console */
85 DWORD tls_bits[2]; /* 88 TLS in-use bits */
86 DWORD process_dword; /* 90 Unknown */
87 struct _PDB *group; /* 94 Process group */
88 void *exe_modref; /* 98 MODREF for the process EXE */
89 void *top_filter; /* 9c Top exception filter */
90 DWORD priority; /* a0 Priority level */
91 HANDLE heap_list; /* a4 Head of process heap list */
92 void *heap_handles; /* a8 Head of heap handles list */
93 DWORD unknown6; /* ac Unknown */
94 void *console_provider; /* b0 Console provider (??) */
95 WORD env_selector; /* b4 Selector to process environment */
96 WORD error_mode; /* b6 Error mode */
97 HANDLE load_done_evt; /* b8 Event for process loading done */
98 void *UTState; /* bc Head of Univeral Thunk list */
99 DWORD unknown8; /* c0 Unknown (NT) */
100 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
101 } PDB;
103 PDB current_process;
105 /* Process flags */
106 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
107 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
108 #define PDB32_DOS_PROC 0x0010 /* Dos process */
109 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
110 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
111 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
113 static char main_exe_name[MAX_PATH];
114 static char *main_exe_name_ptr = main_exe_name;
115 static HANDLE main_exe_file;
116 static int main_create_flags;
118 static unsigned int server_startticks;
120 /* memory/environ.c */
121 extern struct _ENVDB *ENV_InitStartupInfo( handle_t info_handle, size_t info_size,
122 char *main_exe_name, size_t main_exe_size );
123 extern BOOL ENV_BuildCommandLine( char **argv );
124 extern STARTUPINFOA current_startupinfo;
126 /* scheduler/pthread.c */
127 extern void PTHREAD_init_done(void);
129 extern BOOL MAIN_MainInit(void);
131 typedef WORD (WINAPI *pUserSignalProc)( UINT, DWORD, DWORD, HMODULE16 );
133 /***********************************************************************
134 * PROCESS_CallUserSignalProc
136 * FIXME: Some of the signals aren't sent correctly!
138 * The exact meaning of the USER signals is undocumented, but this
139 * should cover the basic idea:
141 * USIG_DLL_UNLOAD_WIN16
142 * This is sent when a 16-bit module is unloaded.
144 * USIG_DLL_UNLOAD_WIN32
145 * This is sent when a 32-bit module is unloaded.
147 * USIG_DLL_UNLOAD_ORPHANS
148 * This is sent after the last Win3.1 module is unloaded,
149 * to allow removal of orphaned menus.
151 * USIG_FAULT_DIALOG_PUSH
152 * USIG_FAULT_DIALOG_POP
153 * These are called to allow USER to prepare for displaying a
154 * fault dialog, even though the fault might have happened while
155 * inside a USER critical section.
157 * USIG_THREAD_INIT
158 * This is called from the context of a new thread, as soon as it
159 * has started to run.
161 * USIG_THREAD_EXIT
162 * This is called, still in its context, just before a thread is
163 * about to terminate.
165 * USIG_PROCESS_CREATE
166 * This is called, in the parent process context, after a new process
167 * has been created.
169 * USIG_PROCESS_INIT
170 * This is called in the new process context, just after the main thread
171 * has started execution (after the main thread's USIG_THREAD_INIT has
172 * been sent).
174 * USIG_PROCESS_LOADED
175 * This is called after the executable file has been loaded into the
176 * new process context.
178 * USIG_PROCESS_RUNNING
179 * This is called immediately before the main entry point is called.
181 * USIG_PROCESS_EXIT
182 * This is called in the context of a process that is about to
183 * terminate (but before the last thread's USIG_THREAD_EXIT has
184 * been sent).
186 * USIG_PROCESS_DESTROY
187 * This is called after a process has terminated.
190 * The meaning of the dwFlags bits is as follows:
192 * USIG_FLAGS_WIN32
193 * Current process is 32-bit.
195 * USIG_FLAGS_GUI
196 * Current process is a (Win32) GUI process.
198 * USIG_FLAGS_FEEDBACK
199 * Current process needs 'feedback' (determined from the STARTUPINFO
200 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
202 * USIG_FLAGS_FAULT
203 * The signal is being sent due to a fault.
205 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
207 DWORD dwFlags = 0;
208 HMODULE user;
209 pUserSignalProc proc;
211 if (!(user = GetModuleHandleA( "user32.dll" ))) return;
212 if (!(proc = (pUserSignalProc)GetProcAddress( user, "UserSignalProc" ))) return;
214 /* Determine dwFlags */
216 if ( !(current_process.flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
217 if ( !(current_process.flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
219 if ( dwFlags & USIG_FLAGS_GUI )
221 /* Feedback defaults to ON */
222 if ( !(current_startupinfo.dwFlags & STARTF_FORCEOFFFEEDBACK) )
223 dwFlags |= USIG_FLAGS_FEEDBACK;
225 else
227 /* Feedback defaults to OFF */
228 if (current_startupinfo.dwFlags & STARTF_FORCEONFEEDBACK)
229 dwFlags |= USIG_FLAGS_FEEDBACK;
232 /* Call USER signal proc */
234 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
235 proc( uCode, GetCurrentThreadId(), dwFlags, hModule );
236 else
237 proc( uCode, GetCurrentProcessId(), dwFlags, hModule );
241 /***********************************************************************
242 * get_basename
244 inline static const char *get_basename( const char *name )
246 char *p;
248 if ((p = strrchr( name, '/' ))) name = p + 1;
249 if ((p = strrchr( name, '\\' ))) name = p + 1;
250 return name;
254 /***********************************************************************
255 * open_exe_file
257 * Open an exe file, taking load order into account.
258 * Returns the file handle or 0 for a builtin exe.
260 static HANDLE open_exe_file( const char *name )
262 enum loadorder_type loadorder[LOADORDER_NTYPES];
263 HANDLE handle;
264 int i;
266 SetLastError( ERROR_FILE_NOT_FOUND );
267 MODULE_GetLoadOrder( loadorder, name, TRUE );
269 for(i = 0; i < LOADORDER_NTYPES; i++)
271 if (loadorder[i] == LOADORDER_INVALID) break;
272 switch(loadorder[i])
274 case LOADORDER_DLL:
275 TRACE( "Trying native exe %s\n", debugstr_a(name) );
276 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
277 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
278 return handle;
279 if (GetLastError() != ERROR_FILE_NOT_FOUND) return INVALID_HANDLE_VALUE;
280 break;
281 case LOADORDER_BI:
282 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
283 if (wine_dll_load_main_exe( get_basename(name), NULL, 0, 1 )) return 0;
284 break;
285 default:
286 break;
289 return INVALID_HANDLE_VALUE;
293 /***********************************************************************
294 * find_exe_file
296 * Open an exe file, and return the full name and file handle.
297 * Returns FALSE if file could not be found.
298 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
299 * If file is a builtin exe, returns TRUE and sets handle to 0.
301 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
303 enum loadorder_type loadorder[LOADORDER_NTYPES];
304 int i;
306 TRACE("looking for %s\n", debugstr_a(name) );
308 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ))
310 *handle = open_exe_file( buffer );
311 return TRUE;
314 /* no such file in path, try builtin with .exe extension */
316 lstrcpynA( buffer, get_basename(name), buflen );
317 if (!strchr( buffer, '.' ))
319 char *p = buffer + strlen(buffer);
320 lstrcpynA( p, ".exe", buflen - (p - buffer) );
323 MODULE_GetLoadOrder( loadorder, buffer, TRUE );
324 for (i = 0; i < LOADORDER_NTYPES; i++)
326 if (loadorder[i] == LOADORDER_BI)
328 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
329 if (wine_dll_load_main_exe( buffer, NULL, 0, 1 ))
331 *handle = 0;
332 return TRUE;
334 break;
336 if (loadorder[i] == LOADORDER_INVALID) break;
339 /* no builtin found, try native without extension in case it is a Unix app */
341 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
343 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
344 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
345 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
346 return TRUE;
348 return FALSE;
352 /***********************************************************************
353 * process_init
355 * Main process initialisation code
357 static BOOL process_init( char *argv[] )
359 BOOL ret;
360 size_t info_size = 0;
361 handle_t info = 0;
363 /* store the program name */
364 argv0 = argv[0];
366 /* Fill the initial process structure */
367 current_process.exit_code = STILL_ACTIVE;
368 current_process.threads = 1;
369 current_process.running_threads = 1;
370 current_process.ring0_threads = 1;
371 current_process.group = &current_process;
372 current_process.priority = 8; /* Normal */
374 /* Setup the server connection */
375 CLIENT_InitServer();
377 /* Retrieve startup info from the server */
378 SERVER_START_REQ( init_process )
380 req->ldt_copy = &wine_ldt_copy;
381 req->ppid = getppid();
382 if ((ret = !wine_server_call_err( req )))
384 main_exe_file = reply->exe_file;
385 main_create_flags = reply->create_flags;
386 info_size = reply->info_size;
387 info = reply->info;
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 SetStdHandle( STD_INPUT_HANDLE, FILE_DupUnixHandle( 0, GENERIC_READ|SYNCHRONIZE, TRUE ));
409 SetStdHandle( STD_OUTPUT_HANDLE, FILE_DupUnixHandle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE ));
410 SetStdHandle( STD_ERROR_HANDLE, FILE_DupUnixHandle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE ));
412 else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
414 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
415 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
416 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
419 /* Now we can use the pthreads routines */
420 PTHREAD_init_done();
422 /* Copy the parent environment */
423 if (!(current_process.env_db = ENV_InitStartupInfo( info, info_size,
424 main_exe_name, sizeof(main_exe_name) )))
425 return FALSE;
427 /* Parse command line arguments */
428 OPTIONS_ParseOptions( !info ? argv : NULL );
430 ret = MAIN_MainInit();
432 return ret;
436 /***********************************************************************
437 * start_process
439 * Startup routine of a new process. Runs on the new process stack.
441 static void start_process(void)
443 int debugged, console_app;
444 LPTHREAD_START_ROUTINE entry;
445 WINE_MODREF *wm;
446 HFILE main_file = main_exe_file;
448 /* use original argv[0] as name for the main module */
449 if (!main_exe_name[0])
451 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
452 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
455 if (main_file)
457 UINT drive_type = GetDriveTypeA( main_exe_name );
458 /* don't keep the file handle open on removable media */
459 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
462 /* Retrieve entry point address */
463 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
464 PE_HEADER(current_process.module)->OptionalHeader.AddressOfEntryPoint);
465 console_app = (PE_HEADER(current_process.module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
466 if (console_app)
468 current_process.flags |= PDB32_CONSOLE_PROC;
469 if (main_create_flags & CREATE_NEW_CONSOLE) AllocConsole();
472 /* Signal the parent process to continue */
473 SERVER_START_REQ( init_process_done )
475 req->module = (void *)current_process.module;
476 req->module_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfImage;
477 req->entry = entry;
478 /* API requires a double indirection */
479 req->name = &main_exe_name_ptr;
480 req->exe_file = main_file;
481 req->gui = !console_app;
482 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
483 wine_server_call( req );
484 debugged = reply->debugged;
486 SERVER_END_REQ;
488 /* Install signal handlers; this cannot be done before, since we cannot
489 * send exceptions to the debugger before the create process event that
490 * is sent by REQ_INIT_PROCESS_DONE */
491 if (!SIGNAL_Init()) goto error;
493 /* create the main modref and load dependencies */
494 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
495 goto error;
496 wm->refCount++;
498 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
500 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
502 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
503 * context of the parent process. Actually, the USER signal proc
504 * doesn't really care about that, but it *does* require that the
505 * startup parameters are correctly set up, so that GetProcessDword
506 * works. Furthermore, before calling the USER signal proc the
507 * 16-bit stack must be set up, which it is only after TASK_Create
508 * in the case of a 16-bit process. Thus, we send the signal here.
510 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
511 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
512 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
513 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
514 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
515 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
517 if (TRACE_ON(relay))
518 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
519 GetCurrentThreadId(), main_exe_name, entry );
520 if (debugged) DbgBreakPoint();
521 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
522 * Dunno about other OSs */
523 SetLastError(0); /* clear error code */
524 ExitThread( entry(NULL) );
526 error:
527 ExitProcess( GetLastError() );
531 /***********************************************************************
532 * PROCESS_InitWine
534 * Wine initialisation: load and start the main exe file.
536 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
538 char error[100];
539 DWORD stack_size = 0;
541 /* Initialize everything */
542 if (!process_init( argv )) exit(1);
544 argv++; /* remove argv[0] (wine itself) */
546 TRACE( "starting process name=%s file=%x argv[0]=%s\n",
547 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
549 if (!main_exe_name[0])
551 if (!argv[0]) OPTIONS_Usage();
553 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
555 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
556 ExitProcess(1);
558 if (main_exe_file == INVALID_HANDLE_VALUE)
560 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
561 ExitProcess(1);
565 if (!main_exe_file) /* no file handle -> Winelib app */
567 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
568 if (wine_dll_load_main_exe( get_basename(main_exe_name), error, sizeof(error), 0 ))
569 goto found;
570 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
571 ExitProcess(1);
574 switch( MODULE_GetBinaryType( main_exe_file ))
576 case BINARY_UNKNOWN:
577 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
578 ExitProcess(1);
579 case BINARY_PE_EXE:
580 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
581 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
582 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
583 ExitProcess(1);
584 case BINARY_PE_DLL:
585 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
586 ExitProcess(1);
587 case BINARY_WIN16:
588 case BINARY_DOS:
589 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
590 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
591 current_process.flags |= PDB32_WIN16_PROC;
592 strcpy( win16_exe_name, main_exe_name );
593 main_exe_name[0] = 0;
594 *win16_exe_file = main_exe_file;
595 main_exe_file = 0;
596 _EnterWin16Lock();
597 goto found;
598 case BINARY_OS216:
599 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
600 ExitProcess(1);
601 case BINARY_UNIX_EXE:
602 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
603 ExitProcess(1);
604 case BINARY_UNIX_LIB:
606 DOS_FULL_NAME full_name;
607 const char *name = main_exe_name;
609 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
610 if (DOSFS_GetFullName( name, TRUE, &full_name )) name = full_name.long_name;
611 CloseHandle( main_exe_file );
612 main_exe_file = 0;
613 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) )) goto found;
614 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
615 ExitProcess(1);
619 found:
620 /* build command line */
621 if (!ENV_BuildCommandLine( argv )) goto error;
623 /* create 32-bit module for main exe */
624 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
625 stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
627 /* allocate main thread stack */
628 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
630 /* switch to the new stack */
631 SYSDEPS_SwitchToThreadStack( start_process );
633 error:
634 ExitProcess( GetLastError() );
638 /***********************************************************************
639 * build_argv
641 * Build an argv array from a command-line.
642 * The command-line is modified to insert nulls.
643 * 'reserved' is the number of args to reserve before the first one.
645 static char **build_argv( char *cmdline, int reserved )
647 int argc;
648 char** argv;
649 char *arg,*s,*d;
650 int in_quotes,bcount;
652 argc=reserved+1;
653 bcount=0;
654 in_quotes=0;
655 s=cmdline;
656 while (1) {
657 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
658 /* space */
659 argc++;
660 /* skip the remaining spaces */
661 while (*s==' ' || *s=='\t') {
662 s++;
664 if (*s=='\0')
665 break;
666 bcount=0;
667 continue;
668 } else if (*s=='\\') {
669 /* '\', count them */
670 bcount++;
671 } else if ((*s=='"') && ((bcount & 1)==0)) {
672 /* unescaped '"' */
673 in_quotes=!in_quotes;
674 bcount=0;
675 } else {
676 /* a regular character */
677 bcount=0;
679 s++;
681 argv=malloc(argc*sizeof(*argv));
682 if (!argv)
683 return NULL;
685 arg=d=s=cmdline;
686 bcount=0;
687 in_quotes=0;
688 argc=reserved;
689 while (*s) {
690 if ((*s==' ' || *s=='\t') && !in_quotes) {
691 /* Close the argument and copy it */
692 *d=0;
693 argv[argc++]=arg;
695 /* skip the remaining spaces */
696 do {
697 s++;
698 } while (*s==' ' || *s=='\t');
700 /* Start with a new argument */
701 arg=d=s;
702 bcount=0;
703 } else if (*s=='\\') {
704 /* '\\' */
705 *d++=*s++;
706 bcount++;
707 } else if (*s=='"') {
708 /* '"' */
709 if ((bcount & 1)==0) {
710 /* Preceeded by an even number of '\', this is half that
711 * number of '\', plus a '"' which we discard.
713 d-=bcount/2;
714 s++;
715 in_quotes=!in_quotes;
716 } else {
717 /* Preceeded by an odd number of '\', this is half that
718 * number of '\' followed by a '"'
720 d=d-bcount/2-1;
721 *d++='"';
722 s++;
724 bcount=0;
725 } else {
726 /* a regular character */
727 *d++=*s++;
728 bcount=0;
731 if (*arg) {
732 *d='\0';
733 argv[argc++]=arg;
735 argv[argc]=NULL;
737 return argv;
741 /***********************************************************************
742 * build_envp
744 * Build the environment of a new child process.
746 static char **build_envp( const char *env, const char *extra_env )
748 const char *p;
749 char **envp;
750 int count = 0;
752 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
753 for (p = env; *p; count++) p += strlen(p) + 1;
754 count += 3;
756 if ((envp = malloc( count * sizeof(*envp) )))
758 extern char **environ;
759 char **envptr = envp;
760 char **unixptr = environ;
761 /* first the extra strings */
762 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
763 /* then put PATH, HOME and WINEPREFIX from the unix env */
764 for (unixptr = environ; unixptr && *unixptr; unixptr++)
765 if (!memcmp( *unixptr, "PATH=", 5 ) ||
766 !memcmp( *unixptr, "HOME=", 5 ) ||
767 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
768 /* now put the Windows environment strings */
769 for (p = env; *p; p += strlen(p) + 1)
771 if (memcmp( p, "PATH=", 5 ) &&
772 memcmp( p, "HOME=", 5 ) &&
773 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
775 *envptr = 0;
777 return envp;
781 /***********************************************************************
782 * exec_wine_binary
784 * Locate the Wine binary to exec for a new Win32 process.
786 static void exec_wine_binary( char **argv, char **envp )
788 const char *path, *pos, *ptr;
790 /* first, try for a WINELOADER environment variable */
791 argv[0] = getenv("WINELOADER");
792 if (argv[0])
793 execve( argv[0], argv, envp );
795 /* next, try bin directory */
796 argv[0] = BINDIR "/wine";
797 execve( argv[0], argv, envp );
799 /* now try the path of argv0 of the current binary */
800 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
801 if ((ptr = strrchr( full_argv0, '/' )))
803 memcpy( argv[0], full_argv0, ptr - full_argv0 );
804 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
805 execve( argv[0], argv, envp );
807 free( argv[0] );
809 /* now search in the Unix path */
810 if ((path = getenv( "PATH" )))
812 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
813 pos = path;
814 for (;;)
816 while (*pos == ':') pos++;
817 if (!*pos) break;
818 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
819 memcpy( argv[0], pos, ptr - pos );
820 strcpy( argv[0] + (ptr - pos), "/wine" );
821 execve( argv[0], argv, envp );
822 pos = ptr;
825 free( argv[0] );
829 /***********************************************************************
830 * fork_and_exec
832 * Fork and exec a new Unix process, checking for errors.
834 static int fork_and_exec( const char *filename, char *cmdline,
835 const char *env, const char *newdir )
837 int fd[2];
838 int pid, err;
839 char *extra_env = NULL;
841 if (!env)
843 env = GetEnvironmentStringsA();
844 extra_env = DRIVE_BuildEnv();
847 if (pipe(fd) == -1)
849 FILE_SetDosError();
850 return -1;
852 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
853 if (!(pid = fork())) /* child */
855 char **argv = build_argv( cmdline, filename ? 0 : 1 );
856 char **envp = build_envp( env, extra_env );
857 close( fd[0] );
859 if (newdir) chdir(newdir);
861 if (argv && envp)
863 if (!filename) exec_wine_binary( argv, envp );
864 else execve( filename, argv, envp );
866 err = errno;
867 write( fd[1], &err, sizeof(err) );
868 _exit(1);
870 close( fd[1] );
871 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
873 errno = err;
874 pid = -1;
876 if (pid == -1) FILE_SetDosError();
877 close( fd[0] );
878 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
879 return pid;
883 /***********************************************************************
884 * create_process
886 * Create a new process. If hFile is a valid handle we have an exe
887 * file, otherwise it is a Winelib app.
889 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
890 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
891 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
892 LPPROCESS_INFORMATION info, LPCSTR unixdir )
894 BOOL ret;
895 HANDLE load_done_evt = 0;
896 HANDLE process_info;
897 startup_info_t startup_info;
899 /* fill the startup info structure */
901 startup_info.size = sizeof(startup_info);
902 /* startup_info.filename_len is set below */
903 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
904 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
905 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
906 startup_info.x = startup->dwX;
907 startup_info.y = startup->dwY;
908 startup_info.cx = startup->dwXSize;
909 startup_info.cy = startup->dwYSize;
910 startup_info.x_chars = startup->dwXCountChars;
911 startup_info.y_chars = startup->dwYCountChars;
912 startup_info.attribute = startup->dwFillAttribute;
913 startup_info.cmd_show = startup->wShowWindow;
914 startup_info.flags = startup->dwFlags;
916 /* create the process on the server side */
918 SERVER_START_REQ( new_process )
920 char buf[MAX_PATH];
921 LPCSTR nameptr;
923 req->inherit_all = inherit;
924 req->create_flags = flags;
925 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
926 req->exe_file = hFile;
927 if (startup->dwFlags & STARTF_USESTDHANDLES)
929 req->hstdin = startup->hStdInput;
930 req->hstdout = startup->hStdOutput;
931 req->hstderr = startup->hStdError;
933 else
935 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
936 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
937 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
940 if (GetLongPathNameA( filename, buf, MAX_PATH ))
941 nameptr = buf;
942 else
943 nameptr = filename;
945 startup_info.filename_len = strlen(nameptr);
946 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
947 wine_server_add_data( req, nameptr, startup_info.filename_len );
948 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
949 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
950 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
952 ret = !wine_server_call_err( req );
953 process_info = reply->info;
955 SERVER_END_REQ;
956 if (!ret) return FALSE;
958 /* fork and execute */
960 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
962 CloseHandle( process_info );
963 return FALSE;
966 /* wait for the new process info to be ready */
968 ret = TRUE; /* pretend success even if we don't get the new process info */
969 if (WaitForSingleObject( process_info, 2000 ) == STATUS_WAIT_0)
971 SERVER_START_REQ( get_new_process_info )
973 req->info = process_info;
974 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
975 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
976 if ((ret = !wine_server_call_err( req )))
978 info->dwProcessId = (DWORD)reply->pid;
979 info->dwThreadId = (DWORD)reply->tid;
980 info->hProcess = reply->phandle;
981 info->hThread = reply->thandle;
982 load_done_evt = reply->event;
985 SERVER_END_REQ;
987 CloseHandle( process_info );
988 if (!ret) return FALSE;
990 /* Wait until process is initialized (or initialization failed) */
991 if (load_done_evt)
993 DWORD res;
994 HANDLE handles[2];
996 handles[0] = info->hProcess;
997 handles[1] = load_done_evt;
998 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
999 CloseHandle( load_done_evt );
1000 if (res == STATUS_WAIT_0) /* the process died */
1002 DWORD exitcode;
1003 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1004 CloseHandle( info->hThread );
1005 CloseHandle( info->hProcess );
1006 return FALSE;
1009 return TRUE;
1013 /*************************************************************************
1014 * get_file_name
1016 * Helper for CreateProcess: retrieve the file name to load from the
1017 * app name and command line. Store the file name in buffer, and
1018 * return a possibly modified command line.
1019 * Also returns a handle to the opened file if it's a Windows binary.
1021 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1022 int buflen, HANDLE *handle )
1024 char *name, *pos, *ret = NULL;
1025 const char *p;
1027 /* if we have an app name, everything is easy */
1029 if (appname)
1031 /* use the unmodified app name as file name */
1032 lstrcpynA( buffer, appname, buflen );
1033 *handle = open_exe_file( buffer );
1034 if (!(ret = cmdline))
1036 /* no command-line, create one */
1037 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1038 sprintf( ret, "\"%s\"", appname );
1040 return ret;
1043 if (!cmdline)
1045 SetLastError( ERROR_INVALID_PARAMETER );
1046 return NULL;
1049 /* first check for a quoted file name */
1051 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1053 int len = p - cmdline - 1;
1054 /* extract the quoted portion as file name */
1055 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1056 memcpy( name, cmdline + 1, len );
1057 name[len] = 0;
1059 if (find_exe_file( name, buffer, buflen, handle ))
1060 ret = cmdline; /* no change necessary */
1061 goto done;
1064 /* now try the command-line word by word */
1066 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1067 pos = name;
1068 p = cmdline;
1070 while (*p)
1072 do *pos++ = *p++; while (*p && *p != ' ');
1073 *pos = 0;
1074 if (find_exe_file( name, buffer, buflen, handle ))
1076 ret = cmdline;
1077 break;
1081 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1083 /* now build a new command-line with quotes */
1085 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1086 sprintf( ret, "\"%s\"%s", name, p );
1088 done:
1089 HeapFree( GetProcessHeap(), 0, name );
1090 return ret;
1094 /**********************************************************************
1095 * CreateProcessA (KERNEL32.@)
1097 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1098 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1099 DWORD flags, LPVOID env, LPCSTR cur_dir,
1100 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1102 BOOL retv = FALSE;
1103 HANDLE hFile = 0;
1104 const char *unixdir = NULL;
1105 DOS_FULL_NAME full_dir;
1106 char name[MAX_PATH];
1107 LPSTR tidy_cmdline;
1109 /* Process the AppName and/or CmdLine to get module name and path */
1111 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1113 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1114 return FALSE;
1115 if (hFile == INVALID_HANDLE_VALUE) goto done;
1117 /* Warn if unsupported features are used */
1119 if (flags & NORMAL_PRIORITY_CLASS)
1120 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1121 if (flags & IDLE_PRIORITY_CLASS)
1122 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1123 if (flags & HIGH_PRIORITY_CLASS)
1124 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1125 if (flags & REALTIME_PRIORITY_CLASS)
1126 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1127 if (flags & CREATE_NEW_PROCESS_GROUP)
1128 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1129 if (flags & CREATE_UNICODE_ENVIRONMENT)
1130 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1131 if (flags & CREATE_SEPARATE_WOW_VDM)
1132 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1133 if (flags & CREATE_SHARED_WOW_VDM)
1134 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1135 if (flags & CREATE_DEFAULT_ERROR_MODE)
1136 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1137 if (flags & CREATE_NO_WINDOW)
1138 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1139 if (flags & PROFILE_USER)
1140 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1141 if (flags & PROFILE_KERNEL)
1142 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1143 if (flags & PROFILE_SERVER)
1144 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1145 if (startup_info->lpDesktop)
1146 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1147 name, debugstr_a(startup_info->lpDesktop));
1148 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1149 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1150 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1151 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1152 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1153 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1154 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1155 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1157 if (cur_dir)
1159 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir ))
1160 unixdir = full_dir.long_name;
1162 else
1164 char buf[MAX_PATH];
1165 if (GetCurrentDirectoryA(sizeof(buf),buf))
1167 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1171 info->hThread = info->hProcess = 0;
1172 info->dwProcessId = info->dwThreadId = 0;
1174 /* Determine executable type */
1176 if (!hFile) /* builtin exe */
1178 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1179 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1180 inherit, flags, startup_info, info, unixdir );
1181 goto done;
1184 switch( MODULE_GetBinaryType( hFile ))
1186 case BINARY_PE_EXE:
1187 case BINARY_WIN16:
1188 case BINARY_DOS:
1189 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1190 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1191 inherit, flags, startup_info, info, unixdir );
1192 break;
1193 case BINARY_OS216:
1194 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1195 SetLastError( ERROR_BAD_EXE_FORMAT );
1196 break;
1197 case BINARY_PE_DLL:
1198 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1199 SetLastError( ERROR_BAD_EXE_FORMAT );
1200 break;
1201 case BINARY_UNIX_LIB:
1202 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1203 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1204 inherit, flags, startup_info, info, unixdir );
1205 break;
1206 case BINARY_UNIX_EXE:
1207 case BINARY_UNKNOWN:
1209 /* unknown file, try as unix executable */
1211 DOS_FULL_NAME full_name;
1212 const char *unixfilename = name;
1214 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1215 if (DOSFS_GetFullName( name, TRUE, &full_name )) unixfilename = full_name.long_name;
1216 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1218 break;
1220 CloseHandle( hFile );
1222 done:
1223 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1224 return retv;
1228 /**********************************************************************
1229 * CreateProcessW (KERNEL32.@)
1230 * NOTES
1231 * lpReserved is not converted
1233 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1234 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1235 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1236 LPPROCESS_INFORMATION info )
1238 BOOL ret;
1239 STARTUPINFOA StartupInfoA;
1241 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1242 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1243 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1245 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1246 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1247 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1249 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1251 if (startup_info->lpReserved)
1252 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1253 debugstr_w(startup_info->lpReserved));
1255 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1256 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1258 HeapFree( GetProcessHeap(), 0, cur_dirA );
1259 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1260 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1261 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1263 return ret;
1267 /***********************************************************************
1268 * ExitProcess (KERNEL32.@)
1270 void WINAPI ExitProcess( DWORD status )
1272 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1273 SERVER_START_REQ( terminate_process )
1275 /* send the exit code to the server */
1276 req->handle = GetCurrentProcess();
1277 req->exit_code = status;
1278 wine_server_call( req );
1280 SERVER_END_REQ;
1281 exit( status );
1284 /***********************************************************************
1285 * ExitProcess (KERNEL.466)
1287 void WINAPI ExitProcess16( WORD status )
1289 DWORD count;
1290 ReleaseThunkLock( &count );
1291 ExitProcess( status );
1294 /******************************************************************************
1295 * TerminateProcess (KERNEL32.@)
1297 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1299 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1300 if (status) SetLastError( RtlNtStatusToDosError(status) );
1301 return !status;
1305 /***********************************************************************
1306 * GetProcessDword (KERNEL.485)
1307 * GetProcessDword (KERNEL32.18)
1308 * 'Of course you cannot directly access Windows internal structures'
1310 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1312 DWORD x, y;
1314 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1316 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1318 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1319 return 0;
1322 switch ( offset )
1324 case GPD_APP_COMPAT_FLAGS:
1325 return GetAppCompatFlags16(0);
1327 case GPD_LOAD_DONE_EVENT:
1328 return current_process.load_done_evt;
1330 case GPD_HINSTANCE16:
1331 return GetTaskDS16();
1333 case GPD_WINDOWS_VERSION:
1334 return GetExeVersion16();
1336 case GPD_THDB:
1337 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1339 case GPD_PDB:
1340 return (DWORD)&current_process;
1342 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1343 return current_startupinfo.hStdOutput;
1345 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1346 return current_startupinfo.hStdInput;
1348 case GPD_STARTF_SHOWWINDOW:
1349 return current_startupinfo.wShowWindow;
1351 case GPD_STARTF_SIZE:
1352 x = current_startupinfo.dwXSize;
1353 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1354 y = current_startupinfo.dwYSize;
1355 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1356 return MAKELONG( x, y );
1358 case GPD_STARTF_POSITION:
1359 x = current_startupinfo.dwX;
1360 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1361 y = current_startupinfo.dwY;
1362 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1363 return MAKELONG( x, y );
1365 case GPD_STARTF_FLAGS:
1366 return current_startupinfo.dwFlags;
1368 case GPD_PARENT:
1369 return 0;
1371 case GPD_FLAGS:
1372 return current_process.flags;
1374 case GPD_USERDATA:
1375 return current_process.process_dword;
1377 default:
1378 ERR_(win32)("Unknown offset %d\n", offset );
1379 return 0;
1383 /***********************************************************************
1384 * SetProcessDword (KERNEL.484)
1385 * 'Of course you cannot directly access Windows internal structures'
1387 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1389 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1391 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1393 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1394 return;
1397 switch ( offset )
1399 case GPD_APP_COMPAT_FLAGS:
1400 case GPD_LOAD_DONE_EVENT:
1401 case GPD_HINSTANCE16:
1402 case GPD_WINDOWS_VERSION:
1403 case GPD_THDB:
1404 case GPD_PDB:
1405 case GPD_STARTF_SHELLDATA:
1406 case GPD_STARTF_HOTKEY:
1407 case GPD_STARTF_SHOWWINDOW:
1408 case GPD_STARTF_SIZE:
1409 case GPD_STARTF_POSITION:
1410 case GPD_STARTF_FLAGS:
1411 case GPD_PARENT:
1412 case GPD_FLAGS:
1413 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1414 break;
1416 case GPD_USERDATA:
1417 current_process.process_dword = value;
1418 break;
1420 default:
1421 ERR_(win32)("Unknown offset %d\n", offset );
1422 break;
1427 /*********************************************************************
1428 * OpenProcess (KERNEL32.@)
1430 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1432 HANDLE ret = 0;
1433 SERVER_START_REQ( open_process )
1435 req->pid = (void *)id;
1436 req->access = access;
1437 req->inherit = inherit;
1438 if (!wine_server_call_err( req )) ret = reply->handle;
1440 SERVER_END_REQ;
1441 return ret;
1444 /*********************************************************************
1445 * MapProcessHandle (KERNEL.483)
1447 DWORD WINAPI MapProcessHandle( HANDLE handle )
1449 DWORD ret = 0;
1450 SERVER_START_REQ( get_process_info )
1452 req->handle = handle;
1453 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1455 SERVER_END_REQ;
1456 return ret;
1459 /***********************************************************************
1460 * SetPriorityClass (KERNEL32.@)
1462 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1464 BOOL ret;
1465 SERVER_START_REQ( set_process_info )
1467 req->handle = hprocess;
1468 req->priority = priorityclass;
1469 req->mask = SET_PROCESS_INFO_PRIORITY;
1470 ret = !wine_server_call_err( req );
1472 SERVER_END_REQ;
1473 return ret;
1477 /***********************************************************************
1478 * GetPriorityClass (KERNEL32.@)
1480 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1482 DWORD ret = 0;
1483 SERVER_START_REQ( get_process_info )
1485 req->handle = hprocess;
1486 if (!wine_server_call_err( req )) ret = reply->priority;
1488 SERVER_END_REQ;
1489 return ret;
1493 /***********************************************************************
1494 * SetProcessAffinityMask (KERNEL32.@)
1496 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1498 BOOL ret;
1499 SERVER_START_REQ( set_process_info )
1501 req->handle = hProcess;
1502 req->affinity = affmask;
1503 req->mask = SET_PROCESS_INFO_AFFINITY;
1504 ret = !wine_server_call_err( req );
1506 SERVER_END_REQ;
1507 return ret;
1510 /**********************************************************************
1511 * GetProcessAffinityMask (KERNEL32.@)
1513 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1514 LPDWORD lpProcessAffinityMask,
1515 LPDWORD lpSystemAffinityMask )
1517 BOOL ret = FALSE;
1518 SERVER_START_REQ( get_process_info )
1520 req->handle = hProcess;
1521 if (!wine_server_call_err( req ))
1523 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1524 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1525 ret = TRUE;
1528 SERVER_END_REQ;
1529 return ret;
1533 /***********************************************************************
1534 * GetProcessVersion (KERNEL32.@)
1536 DWORD WINAPI GetProcessVersion( DWORD processid )
1538 IMAGE_NT_HEADERS *nt;
1540 if (processid && processid != GetCurrentProcessId())
1542 FIXME("should use ReadProcessMemory\n");
1543 return 0;
1545 if ((nt = RtlImageNtHeader( current_process.module )))
1546 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1547 nt->OptionalHeader.MinorSubsystemVersion);
1548 return 0;
1551 /***********************************************************************
1552 * GetProcessFlags (KERNEL32.@)
1554 DWORD WINAPI GetProcessFlags( DWORD processid )
1556 if (processid && processid != GetCurrentProcessId()) return 0;
1557 return current_process.flags;
1561 /***********************************************************************
1562 * SetProcessWorkingSetSize [KERNEL32.@]
1563 * Sets the min/max working set sizes for a specified process.
1565 * PARAMS
1566 * hProcess [I] Handle to the process of interest
1567 * minset [I] Specifies minimum working set size
1568 * maxset [I] Specifies maximum working set size
1570 * RETURNS STD
1572 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1573 DWORD maxset)
1575 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1576 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1577 /* Trim the working set to zero */
1578 /* Swap the process out of physical RAM */
1580 return TRUE;
1583 /***********************************************************************
1584 * GetProcessWorkingSetSize (KERNEL32.@)
1586 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1587 LPDWORD maxset)
1589 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1590 /* 32 MB working set size */
1591 if (minset) *minset = 32*1024*1024;
1592 if (maxset) *maxset = 32*1024*1024;
1593 return TRUE;
1596 /***********************************************************************
1597 * SetProcessShutdownParameters (KERNEL32.@)
1599 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1600 * Now tracks changes made (but does not act on these changes)
1602 static DWORD shutdown_flags = 0;
1603 static DWORD shutdown_priority = 0x280;
1605 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1607 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1608 shutdown_flags = flags;
1609 shutdown_priority = level;
1610 return TRUE;
1614 /***********************************************************************
1615 * GetProcessShutdownParameters (KERNEL32.@)
1618 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1620 *lpdwLevel = shutdown_priority;
1621 *lpdwFlags = shutdown_flags;
1622 return TRUE;
1626 /***********************************************************************
1627 * SetProcessPriorityBoost (KERNEL32.@)
1629 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1631 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1632 /* Say we can do it. I doubt the program will notice that we don't. */
1633 return TRUE;
1637 /***********************************************************************
1638 * ReadProcessMemory (KERNEL32.@)
1640 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1641 LPDWORD bytes_read )
1643 DWORD res;
1645 SERVER_START_REQ( read_process_memory )
1647 req->handle = process;
1648 req->addr = (void *)addr;
1649 wine_server_set_reply( req, buffer, size );
1650 if ((res = wine_server_call_err( req ))) size = 0;
1652 SERVER_END_REQ;
1653 if (bytes_read) *bytes_read = size;
1654 return !res;
1658 /***********************************************************************
1659 * WriteProcessMemory (KERNEL32.@)
1661 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1662 LPDWORD bytes_written )
1664 static const int zero;
1665 unsigned int first_offset, last_offset, first_mask, last_mask;
1666 DWORD res;
1668 if (!size)
1670 SetLastError( ERROR_INVALID_PARAMETER );
1671 return FALSE;
1674 /* compute the mask for the first int */
1675 first_mask = ~0;
1676 first_offset = (unsigned int)addr % sizeof(int);
1677 memset( &first_mask, 0, first_offset );
1679 /* compute the mask for the last int */
1680 last_offset = (size + first_offset) % sizeof(int);
1681 last_mask = 0;
1682 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1684 SERVER_START_REQ( write_process_memory )
1686 req->handle = process;
1687 req->addr = (char *)addr - first_offset;
1688 req->first_mask = first_mask;
1689 req->last_mask = last_mask;
1690 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1691 wine_server_add_data( req, buffer, size );
1692 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1694 if ((res = wine_server_call_err( req ))) size = 0;
1696 SERVER_END_REQ;
1697 if (bytes_written) *bytes_written = size;
1699 char dummy[32];
1700 DWORD read;
1701 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1703 return !res;
1707 /***********************************************************************
1708 * RegisterServiceProcess (KERNEL.491)
1709 * RegisterServiceProcess (KERNEL32.@)
1711 * A service process calls this function to ensure that it continues to run
1712 * even after a user logged off.
1714 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1716 /* I don't think that Wine needs to do anything in that function */
1717 return 1; /* success */
1720 /***********************************************************************
1721 * GetExitCodeProcess [KERNEL32.@]
1723 * Gets termination status of specified process
1725 * RETURNS
1726 * Success: TRUE
1727 * Failure: FALSE
1729 BOOL WINAPI GetExitCodeProcess(
1730 HANDLE hProcess, /* [in] handle to the process */
1731 LPDWORD lpExitCode) /* [out] address to receive termination status */
1733 BOOL ret;
1734 SERVER_START_REQ( get_process_info )
1736 req->handle = hProcess;
1737 ret = !wine_server_call_err( req );
1738 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1740 SERVER_END_REQ;
1741 return ret;
1745 /***********************************************************************
1746 * SetErrorMode (KERNEL32.@)
1748 UINT WINAPI SetErrorMode( UINT mode )
1750 UINT old = current_process.error_mode;
1751 current_process.error_mode = mode;
1752 return old;
1756 /**************************************************************************
1757 * SetFileApisToOEM (KERNEL32.@)
1759 VOID WINAPI SetFileApisToOEM(void)
1761 current_process.flags |= PDB32_FILE_APIS_OEM;
1765 /**************************************************************************
1766 * SetFileApisToANSI (KERNEL32.@)
1768 VOID WINAPI SetFileApisToANSI(void)
1770 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1774 /******************************************************************************
1775 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1777 * RETURNS
1778 * TRUE: Set of file functions is using ANSI code page
1779 * FALSE: Set of file functions is using OEM code page
1781 BOOL WINAPI AreFileApisANSI(void)
1783 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1787 /***********************************************************************
1788 * GetTickCount (USER.13)
1789 * GetCurrentTime (USER.15)
1790 * GetTickCount (KERNEL32.@)
1791 * GetSystemMSecCount (SYSTEM.6)
1793 * Returns the number of milliseconds, modulo 2^32, since the start
1794 * of the wineserver.
1796 DWORD WINAPI GetTickCount(void)
1798 struct timeval t;
1799 gettimeofday( &t, NULL );
1800 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1804 /**********************************************************************
1805 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1807 * Allocates a thread local storage index
1809 * RETURNS
1810 * Success: TLS Index
1811 * Failure: 0xFFFFFFFF
1813 DWORD WINAPI TlsAlloc( void )
1815 DWORD i, mask, ret = 0;
1816 DWORD *bits = current_process.tls_bits;
1817 RtlAcquirePebLock();
1818 if (*bits == 0xffffffff)
1820 bits++;
1821 ret = 32;
1822 if (*bits == 0xffffffff)
1824 RtlReleasePebLock();
1825 SetLastError( ERROR_NO_MORE_ITEMS );
1826 return 0xffffffff;
1829 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1830 *bits |= mask;
1831 RtlReleasePebLock();
1832 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1833 return ret + i;
1837 /**********************************************************************
1838 * TlsFree [KERNEL32.@] Releases a TLS index.
1840 * Releases a thread local storage index, making it available for reuse
1842 * RETURNS
1843 * Success: TRUE
1844 * Failure: FALSE
1846 BOOL WINAPI TlsFree(
1847 DWORD index) /* [in] TLS Index to free */
1849 DWORD mask = (1 << (index & 31));
1850 DWORD *bits = current_process.tls_bits;
1851 if (index >= 64)
1853 SetLastError( ERROR_INVALID_PARAMETER );
1854 return FALSE;
1856 if (index >= 32) bits++;
1857 RtlAcquirePebLock();
1858 if (!(*bits & mask)) /* already free? */
1860 RtlReleasePebLock();
1861 SetLastError( ERROR_INVALID_PARAMETER );
1862 return FALSE;
1864 *bits &= ~mask;
1865 NtCurrentTeb()->tls_array[index] = 0;
1866 /* FIXME: should zero all other thread values */
1867 RtlReleasePebLock();
1868 return TRUE;
1872 /**********************************************************************
1873 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1875 * RETURNS
1876 * Success: Value stored in calling thread's TLS slot for index
1877 * Failure: 0 and GetLastError returns NO_ERROR
1879 LPVOID WINAPI TlsGetValue(
1880 DWORD index) /* [in] TLS index to retrieve value for */
1882 if (index >= 64)
1884 SetLastError( ERROR_INVALID_PARAMETER );
1885 return NULL;
1887 SetLastError( ERROR_SUCCESS );
1888 return NtCurrentTeb()->tls_array[index];
1892 /**********************************************************************
1893 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1895 * RETURNS
1896 * Success: TRUE
1897 * Failure: FALSE
1899 BOOL WINAPI TlsSetValue(
1900 DWORD index, /* [in] TLS index to set value for */
1901 LPVOID value) /* [in] Value to be stored */
1903 if (index >= 64)
1905 SetLastError( ERROR_INVALID_PARAMETER );
1906 return FALSE;
1908 NtCurrentTeb()->tls_array[index] = value;
1909 return TRUE;
1913 /***********************************************************************
1914 * GetCurrentProcess (KERNEL32.@)
1916 #undef GetCurrentProcess
1917 HANDLE WINAPI GetCurrentProcess(void)
1919 return 0xffffffff;