Fixed another regression in PlaySound.
[wine.git] / scheduler / process.c
blob84399432fa4c01cb5083f000313c2e4e4856f170
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( size_t info_size, char *main_exe_name,
122 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;
362 /* store the program name */
363 argv0 = argv[0];
365 /* Fill the initial process structure */
366 current_process.exit_code = STILL_ACTIVE;
367 current_process.threads = 1;
368 current_process.running_threads = 1;
369 current_process.ring0_threads = 1;
370 current_process.group = &current_process;
371 current_process.priority = 8; /* Normal */
373 /* Setup the server connection */
374 CLIENT_InitServer();
376 /* Retrieve startup info from the server */
377 SERVER_START_REQ( init_process )
379 req->ldt_copy = &wine_ldt_copy;
380 req->ppid = getppid();
381 if ((ret = !wine_server_call_err( req )))
383 main_exe_file = reply->exe_file;
384 main_create_flags = reply->create_flags;
385 info_size = reply->info_size;
386 server_startticks = reply->server_start;
387 current_startupinfo.hStdInput = reply->hstdin;
388 current_startupinfo.hStdOutput = reply->hstdout;
389 current_startupinfo.hStdError = reply->hstderr;
392 SERVER_END_REQ;
393 if (!ret) return FALSE;
395 /* Create the process heap */
396 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
398 if (main_create_flags == 0 &&
399 current_startupinfo.hStdInput == 0 &&
400 current_startupinfo.hStdOutput == 0 &&
401 current_startupinfo.hStdError == 0)
403 /* no parent, and no new console requested, create a simple console with bare handles to
404 * unix stdio input & output streams (aka simple console)
406 HANDLE handle;
407 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &handle );
408 SetStdHandle( STD_INPUT_HANDLE, handle );
409 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
410 SetStdHandle( STD_OUTPUT_HANDLE, handle );
411 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
412 SetStdHandle( STD_ERROR_HANDLE, handle );
414 else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
416 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
417 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
418 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
421 /* Now we can use the pthreads routines */
422 PTHREAD_init_done();
424 /* Copy the parent environment */
425 if (!(current_process.env_db = ENV_InitStartupInfo( info_size, main_exe_name,
426 sizeof(main_exe_name) )))
427 return FALSE;
429 /* Parse command line arguments */
430 OPTIONS_ParseOptions( !info_size ? argv : NULL );
432 ret = MAIN_MainInit();
434 return ret;
438 /***********************************************************************
439 * start_process
441 * Startup routine of a new process. Runs on the new process stack.
443 static void start_process(void)
445 int debugged, console_app;
446 LPTHREAD_START_ROUTINE entry;
447 WINE_MODREF *wm;
448 HFILE main_file = main_exe_file;
450 /* use original argv[0] as name for the main module */
451 if (!main_exe_name[0])
453 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
454 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
457 if (main_file)
459 UINT drive_type = GetDriveTypeA( main_exe_name );
460 /* don't keep the file handle open on removable media */
461 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
464 /* Retrieve entry point address */
465 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
466 PE_HEADER(current_process.module)->OptionalHeader.AddressOfEntryPoint);
467 console_app = (PE_HEADER(current_process.module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
468 if (console_app)
470 current_process.flags |= PDB32_CONSOLE_PROC;
471 if (main_create_flags & CREATE_NEW_CONSOLE) AllocConsole();
474 /* Signal the parent process to continue */
475 SERVER_START_REQ( init_process_done )
477 req->module = (void *)current_process.module;
478 req->module_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfImage;
479 req->entry = entry;
480 /* API requires a double indirection */
481 req->name = &main_exe_name_ptr;
482 req->exe_file = main_file;
483 req->gui = !console_app;
484 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
485 wine_server_call( req );
486 debugged = reply->debugged;
488 SERVER_END_REQ;
490 /* Install signal handlers; this cannot be done before, since we cannot
491 * send exceptions to the debugger before the create process event that
492 * is sent by REQ_INIT_PROCESS_DONE */
493 if (!SIGNAL_Init()) goto error;
495 /* create the main modref and load dependencies */
496 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
497 goto error;
498 wm->refCount++;
500 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
502 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
504 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
505 * context of the parent process. Actually, the USER signal proc
506 * doesn't really care about that, but it *does* require that the
507 * startup parameters are correctly set up, so that GetProcessDword
508 * works. Furthermore, before calling the USER signal proc the
509 * 16-bit stack must be set up, which it is only after TASK_Create
510 * in the case of a 16-bit process. Thus, we send the signal here.
512 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
513 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
514 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
515 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
516 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
517 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
519 if (TRACE_ON(relay))
520 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
521 GetCurrentThreadId(), main_exe_name, entry );
522 if (debugged) DbgBreakPoint();
523 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
524 * Dunno about other OSs */
525 SetLastError(0); /* clear error code */
526 ExitThread( entry(NULL) );
528 error:
529 ExitProcess( GetLastError() );
533 /***********************************************************************
534 * PROCESS_InitWine
536 * Wine initialisation: load and start the main exe file.
538 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
540 char error[100];
541 DWORD stack_size = 0;
543 /* Initialize everything */
544 if (!process_init( argv )) exit(1);
546 argv++; /* remove argv[0] (wine itself) */
548 TRACE( "starting process name=%s file=%x argv[0]=%s\n",
549 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
551 if (!main_exe_name[0])
553 if (!argv[0]) OPTIONS_Usage();
555 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
557 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
558 ExitProcess(1);
560 if (main_exe_file == INVALID_HANDLE_VALUE)
562 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
563 ExitProcess(1);
567 if (!main_exe_file) /* no file handle -> Winelib app */
569 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
570 if (wine_dll_load_main_exe( get_basename(main_exe_name), error, sizeof(error), 0 ))
571 goto found;
572 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
573 ExitProcess(1);
576 switch( MODULE_GetBinaryType( main_exe_file ))
578 case BINARY_UNKNOWN:
579 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
580 ExitProcess(1);
581 case BINARY_PE_EXE:
582 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
583 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
584 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
585 ExitProcess(1);
586 case BINARY_PE_DLL:
587 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
588 ExitProcess(1);
589 case BINARY_WIN16:
590 case BINARY_DOS:
591 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
592 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
593 current_process.flags |= PDB32_WIN16_PROC;
594 strcpy( win16_exe_name, main_exe_name );
595 main_exe_name[0] = 0;
596 *win16_exe_file = main_exe_file;
597 main_exe_file = 0;
598 _EnterWin16Lock();
599 goto found;
600 case BINARY_OS216:
601 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
602 ExitProcess(1);
603 case BINARY_UNIX_EXE:
604 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
605 ExitProcess(1);
606 case BINARY_UNIX_LIB:
608 DOS_FULL_NAME full_name;
609 const char *name = main_exe_name;
611 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
612 if (DOSFS_GetFullName( name, TRUE, &full_name )) name = full_name.long_name;
613 CloseHandle( main_exe_file );
614 main_exe_file = 0;
615 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) )) goto found;
616 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
617 ExitProcess(1);
621 found:
622 /* build command line */
623 if (!ENV_BuildCommandLine( argv )) goto error;
625 /* create 32-bit module for main exe */
626 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
627 stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
629 /* allocate main thread stack */
630 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
632 /* switch to the new stack */
633 SYSDEPS_SwitchToThreadStack( start_process );
635 error:
636 ExitProcess( GetLastError() );
640 /***********************************************************************
641 * build_argv
643 * Build an argv array from a command-line.
644 * The command-line is modified to insert nulls.
645 * 'reserved' is the number of args to reserve before the first one.
647 static char **build_argv( char *cmdline, int reserved )
649 int argc;
650 char** argv;
651 char *arg,*s,*d;
652 int in_quotes,bcount;
654 argc=reserved+1;
655 bcount=0;
656 in_quotes=0;
657 s=cmdline;
658 while (1) {
659 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
660 /* space */
661 argc++;
662 /* skip the remaining spaces */
663 while (*s==' ' || *s=='\t') {
664 s++;
666 if (*s=='\0')
667 break;
668 bcount=0;
669 continue;
670 } else if (*s=='\\') {
671 /* '\', count them */
672 bcount++;
673 } else if ((*s=='"') && ((bcount & 1)==0)) {
674 /* unescaped '"' */
675 in_quotes=!in_quotes;
676 bcount=0;
677 } else {
678 /* a regular character */
679 bcount=0;
681 s++;
683 argv=malloc(argc*sizeof(*argv));
684 if (!argv)
685 return NULL;
687 arg=d=s=cmdline;
688 bcount=0;
689 in_quotes=0;
690 argc=reserved;
691 while (*s) {
692 if ((*s==' ' || *s=='\t') && !in_quotes) {
693 /* Close the argument and copy it */
694 *d=0;
695 argv[argc++]=arg;
697 /* skip the remaining spaces */
698 do {
699 s++;
700 } while (*s==' ' || *s=='\t');
702 /* Start with a new argument */
703 arg=d=s;
704 bcount=0;
705 } else if (*s=='\\') {
706 /* '\\' */
707 *d++=*s++;
708 bcount++;
709 } else if (*s=='"') {
710 /* '"' */
711 if ((bcount & 1)==0) {
712 /* Preceeded by an even number of '\', this is half that
713 * number of '\', plus a '"' which we discard.
715 d-=bcount/2;
716 s++;
717 in_quotes=!in_quotes;
718 } else {
719 /* Preceeded by an odd number of '\', this is half that
720 * number of '\' followed by a '"'
722 d=d-bcount/2-1;
723 *d++='"';
724 s++;
726 bcount=0;
727 } else {
728 /* a regular character */
729 *d++=*s++;
730 bcount=0;
733 if (*arg) {
734 *d='\0';
735 argv[argc++]=arg;
737 argv[argc]=NULL;
739 return argv;
743 /***********************************************************************
744 * build_envp
746 * Build the environment of a new child process.
748 static char **build_envp( const char *env, const char *extra_env )
750 const char *p;
751 char **envp;
752 int count = 0;
754 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
755 for (p = env; *p; count++) p += strlen(p) + 1;
756 count += 3;
758 if ((envp = malloc( count * sizeof(*envp) )))
760 extern char **environ;
761 char **envptr = envp;
762 char **unixptr = environ;
763 /* first the extra strings */
764 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
765 /* then put PATH, HOME and WINEPREFIX from the unix env */
766 for (unixptr = environ; unixptr && *unixptr; unixptr++)
767 if (!memcmp( *unixptr, "PATH=", 5 ) ||
768 !memcmp( *unixptr, "HOME=", 5 ) ||
769 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
770 /* now put the Windows environment strings */
771 for (p = env; *p; p += strlen(p) + 1)
773 if (memcmp( p, "PATH=", 5 ) &&
774 memcmp( p, "HOME=", 5 ) &&
775 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
777 *envptr = 0;
779 return envp;
783 /***********************************************************************
784 * exec_wine_binary
786 * Locate the Wine binary to exec for a new Win32 process.
788 static void exec_wine_binary( char **argv, char **envp )
790 const char *path, *pos, *ptr;
792 /* first, try for a WINELOADER environment variable */
793 argv[0] = getenv("WINELOADER");
794 if (argv[0])
795 execve( argv[0], argv, envp );
797 /* next, try bin directory */
798 argv[0] = BINDIR "/wine";
799 execve( argv[0], argv, envp );
801 /* now try the path of argv0 of the current binary */
802 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
803 if ((ptr = strrchr( full_argv0, '/' )))
805 memcpy( argv[0], full_argv0, ptr - full_argv0 );
806 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
807 execve( argv[0], argv, envp );
809 free( argv[0] );
811 /* now search in the Unix path */
812 if ((path = getenv( "PATH" )))
814 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
815 pos = path;
816 for (;;)
818 while (*pos == ':') pos++;
819 if (!*pos) break;
820 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
821 memcpy( argv[0], pos, ptr - pos );
822 strcpy( argv[0] + (ptr - pos), "/wine" );
823 execve( argv[0], argv, envp );
824 pos = ptr;
827 free( argv[0] );
831 /***********************************************************************
832 * fork_and_exec
834 * Fork and exec a new Unix process, checking for errors.
836 static int fork_and_exec( const char *filename, char *cmdline,
837 const char *env, const char *newdir )
839 int fd[2];
840 int pid, err;
841 char *extra_env = NULL;
843 if (!env)
845 env = GetEnvironmentStringsA();
846 extra_env = DRIVE_BuildEnv();
849 if (pipe(fd) == -1)
851 FILE_SetDosError();
852 return -1;
854 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
855 if (!(pid = fork())) /* child */
857 char **argv = build_argv( cmdline, filename ? 0 : 1 );
858 char **envp = build_envp( env, extra_env );
859 close( fd[0] );
861 if (newdir) chdir(newdir);
863 if (argv && envp)
865 if (!filename) exec_wine_binary( argv, envp );
866 else execve( filename, argv, envp );
868 err = errno;
869 write( fd[1], &err, sizeof(err) );
870 _exit(1);
872 close( fd[1] );
873 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
875 errno = err;
876 pid = -1;
878 if (pid == -1) FILE_SetDosError();
879 close( fd[0] );
880 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
881 return pid;
885 /***********************************************************************
886 * create_process
888 * Create a new process. If hFile is a valid handle we have an exe
889 * file, otherwise it is a Winelib app.
891 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
892 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
893 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
894 LPPROCESS_INFORMATION info, LPCSTR unixdir )
896 BOOL ret, success = FALSE;
897 HANDLE process_info;
898 startup_info_t startup_info;
900 /* fill the startup info structure */
902 startup_info.size = sizeof(startup_info);
903 /* startup_info.filename_len is set below */
904 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
905 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
906 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
907 startup_info.x = startup->dwX;
908 startup_info.y = startup->dwY;
909 startup_info.cx = startup->dwXSize;
910 startup_info.cy = startup->dwYSize;
911 startup_info.x_chars = startup->dwXCountChars;
912 startup_info.y_chars = startup->dwYCountChars;
913 startup_info.attribute = startup->dwFillAttribute;
914 startup_info.cmd_show = startup->wShowWindow;
915 startup_info.flags = startup->dwFlags;
917 /* create the process on the server side */
919 SERVER_START_REQ( new_process )
921 char buf[MAX_PATH];
922 LPCSTR nameptr;
924 req->inherit_all = inherit;
925 req->create_flags = flags;
926 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
927 req->exe_file = hFile;
928 if (startup->dwFlags & STARTF_USESTDHANDLES)
930 req->hstdin = startup->hStdInput;
931 req->hstdout = startup->hStdOutput;
932 req->hstderr = startup->hStdError;
934 else
936 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
937 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
938 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
941 if (GetLongPathNameA( filename, buf, MAX_PATH ))
942 nameptr = buf;
943 else
944 nameptr = filename;
946 startup_info.filename_len = strlen(nameptr);
947 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
948 wine_server_add_data( req, nameptr, startup_info.filename_len );
949 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
950 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
951 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
953 ret = !wine_server_call_err( req );
954 process_info = reply->info;
956 SERVER_END_REQ;
957 if (!ret) return FALSE;
959 /* fork and execute */
961 if (fork_and_exec( NULL, cmd_line, env, unixdir ) == -1)
963 CloseHandle( process_info );
964 return FALSE;
967 /* wait for the new process info to be ready */
969 WaitForSingleObject( process_info, INFINITE );
970 SERVER_START_REQ( get_new_process_info )
972 req->info = process_info;
973 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
974 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
975 if ((ret = !wine_server_call_err( req )))
977 info->dwProcessId = (DWORD)reply->pid;
978 info->dwThreadId = (DWORD)reply->tid;
979 info->hProcess = reply->phandle;
980 info->hThread = reply->thandle;
981 success = reply->success;
984 SERVER_END_REQ;
986 if (ret && !success) /* new process failed to start */
988 DWORD exitcode;
989 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
990 CloseHandle( info->hThread );
991 CloseHandle( info->hProcess );
992 ret = FALSE;
994 CloseHandle( process_info );
995 return ret;
999 /*************************************************************************
1000 * get_file_name
1002 * Helper for CreateProcess: retrieve the file name to load from the
1003 * app name and command line. Store the file name in buffer, and
1004 * return a possibly modified command line.
1005 * Also returns a handle to the opened file if it's a Windows binary.
1007 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1008 int buflen, HANDLE *handle )
1010 char *name, *pos, *ret = NULL;
1011 const char *p;
1013 /* if we have an app name, everything is easy */
1015 if (appname)
1017 /* use the unmodified app name as file name */
1018 lstrcpynA( buffer, appname, buflen );
1019 *handle = open_exe_file( buffer );
1020 if (!(ret = cmdline))
1022 /* no command-line, create one */
1023 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1024 sprintf( ret, "\"%s\"", appname );
1026 return ret;
1029 if (!cmdline)
1031 SetLastError( ERROR_INVALID_PARAMETER );
1032 return NULL;
1035 /* first check for a quoted file name */
1037 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1039 int len = p - cmdline - 1;
1040 /* extract the quoted portion as file name */
1041 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1042 memcpy( name, cmdline + 1, len );
1043 name[len] = 0;
1045 if (find_exe_file( name, buffer, buflen, handle ))
1046 ret = cmdline; /* no change necessary */
1047 goto done;
1050 /* now try the command-line word by word */
1052 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1053 pos = name;
1054 p = cmdline;
1056 while (*p)
1058 do *pos++ = *p++; while (*p && *p != ' ');
1059 *pos = 0;
1060 if (find_exe_file( name, buffer, buflen, handle ))
1062 ret = cmdline;
1063 break;
1067 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1069 /* now build a new command-line with quotes */
1071 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1072 sprintf( ret, "\"%s\"%s", name, p );
1074 done:
1075 HeapFree( GetProcessHeap(), 0, name );
1076 return ret;
1080 /**********************************************************************
1081 * CreateProcessA (KERNEL32.@)
1083 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1084 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1085 DWORD flags, LPVOID env, LPCSTR cur_dir,
1086 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1088 BOOL retv = FALSE;
1089 HANDLE hFile = 0;
1090 const char *unixdir = NULL;
1091 DOS_FULL_NAME full_dir;
1092 char name[MAX_PATH];
1093 LPSTR tidy_cmdline;
1095 /* Process the AppName and/or CmdLine to get module name and path */
1097 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1099 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1100 return FALSE;
1101 if (hFile == INVALID_HANDLE_VALUE) goto done;
1103 /* Warn if unsupported features are used */
1105 if (flags & NORMAL_PRIORITY_CLASS)
1106 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1107 if (flags & IDLE_PRIORITY_CLASS)
1108 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1109 if (flags & HIGH_PRIORITY_CLASS)
1110 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1111 if (flags & REALTIME_PRIORITY_CLASS)
1112 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1113 if (flags & CREATE_NEW_PROCESS_GROUP)
1114 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1115 if (flags & CREATE_UNICODE_ENVIRONMENT)
1116 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1117 if (flags & CREATE_SEPARATE_WOW_VDM)
1118 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1119 if (flags & CREATE_SHARED_WOW_VDM)
1120 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1121 if (flags & CREATE_DEFAULT_ERROR_MODE)
1122 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1123 if (flags & CREATE_NO_WINDOW)
1124 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1125 if (flags & PROFILE_USER)
1126 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1127 if (flags & PROFILE_KERNEL)
1128 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1129 if (flags & PROFILE_SERVER)
1130 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1131 if (startup_info->lpDesktop)
1132 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1133 name, debugstr_a(startup_info->lpDesktop));
1134 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1135 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1136 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1137 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1138 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1139 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1140 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1141 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1143 if (cur_dir)
1145 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir ))
1146 unixdir = full_dir.long_name;
1148 else
1150 char buf[MAX_PATH];
1151 if (GetCurrentDirectoryA(sizeof(buf),buf))
1153 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1157 info->hThread = info->hProcess = 0;
1158 info->dwProcessId = info->dwThreadId = 0;
1160 /* Determine executable type */
1162 if (!hFile) /* builtin exe */
1164 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1165 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1166 inherit, flags, startup_info, info, unixdir );
1167 goto done;
1170 switch( MODULE_GetBinaryType( hFile ))
1172 case BINARY_PE_EXE:
1173 case BINARY_WIN16:
1174 case BINARY_DOS:
1175 TRACE( "starting %s as Windows binary\n", debugstr_a(name) );
1176 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1177 inherit, flags, startup_info, info, unixdir );
1178 break;
1179 case BINARY_OS216:
1180 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1181 SetLastError( ERROR_BAD_EXE_FORMAT );
1182 break;
1183 case BINARY_PE_DLL:
1184 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1185 SetLastError( ERROR_BAD_EXE_FORMAT );
1186 break;
1187 case BINARY_UNIX_LIB:
1188 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1189 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1190 inherit, flags, startup_info, info, unixdir );
1191 break;
1192 case BINARY_UNIX_EXE:
1193 case BINARY_UNKNOWN:
1195 /* unknown file, try as unix executable */
1197 DOS_FULL_NAME full_name;
1198 const char *unixfilename = name;
1200 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1201 if (DOSFS_GetFullName( name, TRUE, &full_name )) unixfilename = full_name.long_name;
1202 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1204 break;
1206 CloseHandle( hFile );
1208 done:
1209 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1210 return retv;
1214 /**********************************************************************
1215 * CreateProcessW (KERNEL32.@)
1216 * NOTES
1217 * lpReserved is not converted
1219 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1220 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1221 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1222 LPPROCESS_INFORMATION info )
1224 BOOL ret;
1225 STARTUPINFOA StartupInfoA;
1227 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1228 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1229 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1231 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1232 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1233 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1235 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1237 if (startup_info->lpReserved)
1238 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1239 debugstr_w(startup_info->lpReserved));
1241 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1242 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1244 HeapFree( GetProcessHeap(), 0, cur_dirA );
1245 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1246 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1247 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1249 return ret;
1253 /***********************************************************************
1254 * ExitProcess (KERNEL32.@)
1256 void WINAPI ExitProcess( DWORD status )
1258 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1259 SERVER_START_REQ( terminate_process )
1261 /* send the exit code to the server */
1262 req->handle = GetCurrentProcess();
1263 req->exit_code = status;
1264 wine_server_call( req );
1266 SERVER_END_REQ;
1267 exit( status );
1270 /***********************************************************************
1271 * ExitProcess (KERNEL.466)
1273 void WINAPI ExitProcess16( WORD status )
1275 DWORD count;
1276 ReleaseThunkLock( &count );
1277 ExitProcess( status );
1280 /******************************************************************************
1281 * TerminateProcess (KERNEL32.@)
1283 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1285 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1286 if (status) SetLastError( RtlNtStatusToDosError(status) );
1287 return !status;
1291 /***********************************************************************
1292 * GetProcessDword (KERNEL.485)
1293 * GetProcessDword (KERNEL32.18)
1294 * 'Of course you cannot directly access Windows internal structures'
1296 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1298 DWORD x, y;
1300 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1302 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1304 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1305 return 0;
1308 switch ( offset )
1310 case GPD_APP_COMPAT_FLAGS:
1311 return GetAppCompatFlags16(0);
1313 case GPD_LOAD_DONE_EVENT:
1314 return current_process.load_done_evt;
1316 case GPD_HINSTANCE16:
1317 return GetTaskDS16();
1319 case GPD_WINDOWS_VERSION:
1320 return GetExeVersion16();
1322 case GPD_THDB:
1323 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1325 case GPD_PDB:
1326 return (DWORD)&current_process;
1328 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1329 return current_startupinfo.hStdOutput;
1331 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1332 return current_startupinfo.hStdInput;
1334 case GPD_STARTF_SHOWWINDOW:
1335 return current_startupinfo.wShowWindow;
1337 case GPD_STARTF_SIZE:
1338 x = current_startupinfo.dwXSize;
1339 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1340 y = current_startupinfo.dwYSize;
1341 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1342 return MAKELONG( x, y );
1344 case GPD_STARTF_POSITION:
1345 x = current_startupinfo.dwX;
1346 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1347 y = current_startupinfo.dwY;
1348 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1349 return MAKELONG( x, y );
1351 case GPD_STARTF_FLAGS:
1352 return current_startupinfo.dwFlags;
1354 case GPD_PARENT:
1355 return 0;
1357 case GPD_FLAGS:
1358 return current_process.flags;
1360 case GPD_USERDATA:
1361 return current_process.process_dword;
1363 default:
1364 ERR_(win32)("Unknown offset %d\n", offset );
1365 return 0;
1369 /***********************************************************************
1370 * SetProcessDword (KERNEL.484)
1371 * 'Of course you cannot directly access Windows internal structures'
1373 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1375 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1377 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1379 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1380 return;
1383 switch ( offset )
1385 case GPD_APP_COMPAT_FLAGS:
1386 case GPD_LOAD_DONE_EVENT:
1387 case GPD_HINSTANCE16:
1388 case GPD_WINDOWS_VERSION:
1389 case GPD_THDB:
1390 case GPD_PDB:
1391 case GPD_STARTF_SHELLDATA:
1392 case GPD_STARTF_HOTKEY:
1393 case GPD_STARTF_SHOWWINDOW:
1394 case GPD_STARTF_SIZE:
1395 case GPD_STARTF_POSITION:
1396 case GPD_STARTF_FLAGS:
1397 case GPD_PARENT:
1398 case GPD_FLAGS:
1399 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1400 break;
1402 case GPD_USERDATA:
1403 current_process.process_dword = value;
1404 break;
1406 default:
1407 ERR_(win32)("Unknown offset %d\n", offset );
1408 break;
1413 /*********************************************************************
1414 * OpenProcess (KERNEL32.@)
1416 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1418 HANDLE ret = 0;
1419 SERVER_START_REQ( open_process )
1421 req->pid = (void *)id;
1422 req->access = access;
1423 req->inherit = inherit;
1424 if (!wine_server_call_err( req )) ret = reply->handle;
1426 SERVER_END_REQ;
1427 return ret;
1430 /*********************************************************************
1431 * MapProcessHandle (KERNEL.483)
1433 DWORD WINAPI MapProcessHandle( HANDLE handle )
1435 DWORD ret = 0;
1436 SERVER_START_REQ( get_process_info )
1438 req->handle = handle;
1439 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1441 SERVER_END_REQ;
1442 return ret;
1445 /***********************************************************************
1446 * SetPriorityClass (KERNEL32.@)
1448 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1450 BOOL ret;
1451 SERVER_START_REQ( set_process_info )
1453 req->handle = hprocess;
1454 req->priority = priorityclass;
1455 req->mask = SET_PROCESS_INFO_PRIORITY;
1456 ret = !wine_server_call_err( req );
1458 SERVER_END_REQ;
1459 return ret;
1463 /***********************************************************************
1464 * GetPriorityClass (KERNEL32.@)
1466 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1468 DWORD ret = 0;
1469 SERVER_START_REQ( get_process_info )
1471 req->handle = hprocess;
1472 if (!wine_server_call_err( req )) ret = reply->priority;
1474 SERVER_END_REQ;
1475 return ret;
1479 /***********************************************************************
1480 * SetProcessAffinityMask (KERNEL32.@)
1482 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1484 BOOL ret;
1485 SERVER_START_REQ( set_process_info )
1487 req->handle = hProcess;
1488 req->affinity = affmask;
1489 req->mask = SET_PROCESS_INFO_AFFINITY;
1490 ret = !wine_server_call_err( req );
1492 SERVER_END_REQ;
1493 return ret;
1496 /**********************************************************************
1497 * GetProcessAffinityMask (KERNEL32.@)
1499 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1500 LPDWORD lpProcessAffinityMask,
1501 LPDWORD lpSystemAffinityMask )
1503 BOOL ret = FALSE;
1504 SERVER_START_REQ( get_process_info )
1506 req->handle = hProcess;
1507 if (!wine_server_call_err( req ))
1509 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1510 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1511 ret = TRUE;
1514 SERVER_END_REQ;
1515 return ret;
1519 /***********************************************************************
1520 * GetProcessVersion (KERNEL32.@)
1522 DWORD WINAPI GetProcessVersion( DWORD processid )
1524 IMAGE_NT_HEADERS *nt;
1526 if (processid && processid != GetCurrentProcessId())
1528 FIXME("should use ReadProcessMemory\n");
1529 return 0;
1531 if ((nt = RtlImageNtHeader( current_process.module )))
1532 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1533 nt->OptionalHeader.MinorSubsystemVersion);
1534 return 0;
1537 /***********************************************************************
1538 * GetProcessFlags (KERNEL32.@)
1540 DWORD WINAPI GetProcessFlags( DWORD processid )
1542 if (processid && processid != GetCurrentProcessId()) return 0;
1543 return current_process.flags;
1547 /***********************************************************************
1548 * SetProcessWorkingSetSize [KERNEL32.@]
1549 * Sets the min/max working set sizes for a specified process.
1551 * PARAMS
1552 * hProcess [I] Handle to the process of interest
1553 * minset [I] Specifies minimum working set size
1554 * maxset [I] Specifies maximum working set size
1556 * RETURNS STD
1558 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1559 DWORD maxset)
1561 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1562 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1563 /* Trim the working set to zero */
1564 /* Swap the process out of physical RAM */
1566 return TRUE;
1569 /***********************************************************************
1570 * GetProcessWorkingSetSize (KERNEL32.@)
1572 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1573 LPDWORD maxset)
1575 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1576 /* 32 MB working set size */
1577 if (minset) *minset = 32*1024*1024;
1578 if (maxset) *maxset = 32*1024*1024;
1579 return TRUE;
1582 /***********************************************************************
1583 * SetProcessShutdownParameters (KERNEL32.@)
1585 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1586 * Now tracks changes made (but does not act on these changes)
1588 static DWORD shutdown_flags = 0;
1589 static DWORD shutdown_priority = 0x280;
1591 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1593 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1594 shutdown_flags = flags;
1595 shutdown_priority = level;
1596 return TRUE;
1600 /***********************************************************************
1601 * GetProcessShutdownParameters (KERNEL32.@)
1604 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1606 *lpdwLevel = shutdown_priority;
1607 *lpdwFlags = shutdown_flags;
1608 return TRUE;
1612 /***********************************************************************
1613 * SetProcessPriorityBoost (KERNEL32.@)
1615 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1617 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1618 /* Say we can do it. I doubt the program will notice that we don't. */
1619 return TRUE;
1623 /***********************************************************************
1624 * ReadProcessMemory (KERNEL32.@)
1626 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1627 LPDWORD bytes_read )
1629 DWORD res;
1631 SERVER_START_REQ( read_process_memory )
1633 req->handle = process;
1634 req->addr = (void *)addr;
1635 wine_server_set_reply( req, buffer, size );
1636 if ((res = wine_server_call_err( req ))) size = 0;
1638 SERVER_END_REQ;
1639 if (bytes_read) *bytes_read = size;
1640 return !res;
1644 /***********************************************************************
1645 * WriteProcessMemory (KERNEL32.@)
1647 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, DWORD size,
1648 LPDWORD bytes_written )
1650 static const int zero;
1651 unsigned int first_offset, last_offset, first_mask, last_mask;
1652 DWORD res;
1654 if (!size)
1656 SetLastError( ERROR_INVALID_PARAMETER );
1657 return FALSE;
1660 /* compute the mask for the first int */
1661 first_mask = ~0;
1662 first_offset = (unsigned int)addr % sizeof(int);
1663 memset( &first_mask, 0, first_offset );
1665 /* compute the mask for the last int */
1666 last_offset = (size + first_offset) % sizeof(int);
1667 last_mask = 0;
1668 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1670 SERVER_START_REQ( write_process_memory )
1672 req->handle = process;
1673 req->addr = (char *)addr - first_offset;
1674 req->first_mask = first_mask;
1675 req->last_mask = last_mask;
1676 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1677 wine_server_add_data( req, buffer, size );
1678 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1680 if ((res = wine_server_call_err( req ))) size = 0;
1682 SERVER_END_REQ;
1683 if (bytes_written) *bytes_written = size;
1685 char dummy[32];
1686 DWORD read;
1687 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1689 return !res;
1693 /***********************************************************************
1694 * RegisterServiceProcess (KERNEL.491)
1695 * RegisterServiceProcess (KERNEL32.@)
1697 * A service process calls this function to ensure that it continues to run
1698 * even after a user logged off.
1700 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1702 /* I don't think that Wine needs to do anything in that function */
1703 return 1; /* success */
1706 /***********************************************************************
1707 * GetExitCodeProcess [KERNEL32.@]
1709 * Gets termination status of specified process
1711 * RETURNS
1712 * Success: TRUE
1713 * Failure: FALSE
1715 BOOL WINAPI GetExitCodeProcess(
1716 HANDLE hProcess, /* [in] handle to the process */
1717 LPDWORD lpExitCode) /* [out] address to receive termination status */
1719 BOOL ret;
1720 SERVER_START_REQ( get_process_info )
1722 req->handle = hProcess;
1723 ret = !wine_server_call_err( req );
1724 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1726 SERVER_END_REQ;
1727 return ret;
1731 /***********************************************************************
1732 * SetErrorMode (KERNEL32.@)
1734 UINT WINAPI SetErrorMode( UINT mode )
1736 UINT old = current_process.error_mode;
1737 current_process.error_mode = mode;
1738 return old;
1742 /**************************************************************************
1743 * SetFileApisToOEM (KERNEL32.@)
1745 VOID WINAPI SetFileApisToOEM(void)
1747 current_process.flags |= PDB32_FILE_APIS_OEM;
1751 /**************************************************************************
1752 * SetFileApisToANSI (KERNEL32.@)
1754 VOID WINAPI SetFileApisToANSI(void)
1756 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1760 /******************************************************************************
1761 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1763 * RETURNS
1764 * TRUE: Set of file functions is using ANSI code page
1765 * FALSE: Set of file functions is using OEM code page
1767 BOOL WINAPI AreFileApisANSI(void)
1769 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1773 /***********************************************************************
1774 * GetTickCount (USER.13)
1775 * GetCurrentTime (USER.15)
1776 * GetTickCount (KERNEL32.@)
1777 * GetSystemMSecCount (SYSTEM.6)
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;