Move get current directory and set current directory int21
[wine/gsoc_dplay.git] / scheduler / process.c
blob35fdb056148635fc39f743ca05c8a5142a5db17e
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 <locale.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #ifdef HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36 #include "wine/winbase16.h"
37 #include "wine/winuser16.h"
38 #include "wine/exception.h"
39 #include "wine/library.h"
40 #include "drive.h"
41 #include "module.h"
42 #include "file.h"
43 #include "heap.h"
44 #include "thread.h"
45 #include "winerror.h"
46 #include "wincon.h"
47 #include "wine/server.h"
48 #include "options.h"
49 #include "wine/debug.h"
50 #include "ntdll_misc.h"
52 WINE_DEFAULT_DEBUG_CHANNEL(process);
53 WINE_DECLARE_DEBUG_CHANNEL(server);
54 WINE_DECLARE_DEBUG_CHANNEL(relay);
55 WINE_DECLARE_DEBUG_CHANNEL(snoop);
56 WINE_DECLARE_DEBUG_CHANNEL(win32);
58 struct _ENVDB;
60 /* Win32 process database */
61 typedef struct _PDB
63 LONG header[2]; /* 00 Kernel object header */
64 HMODULE module; /* 08 Main exe module (NT) */
65 void *event; /* 0c Pointer to an event object (unused) */
66 DWORD exit_code; /* 10 Process exit code */
67 DWORD unknown2; /* 14 Unknown */
68 HANDLE heap; /* 18 Default process heap */
69 HANDLE mem_context; /* 1c Process memory context */
70 DWORD flags; /* 20 Flags */
71 void *pdb16; /* 24 DOS PSP */
72 WORD PSP_sel; /* 28 Selector to DOS PSP */
73 WORD imte; /* 2a IMTE for the process module */
74 WORD threads; /* 2c Number of threads */
75 WORD running_threads; /* 2e Number of running threads */
76 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
77 WORD ring0_threads; /* 32 Number of ring 0 threads */
78 HANDLE system_heap; /* 34 System heap to allocate handles */
79 HTASK task; /* 38 Win16 task */
80 void *mem_map_files; /* 3c Pointer to mem-mapped files */
81 struct _ENVDB *env_db; /* 40 Environment database */
82 void *handle_table; /* 44 Handle table */
83 struct _PDB *parent; /* 48 Parent process */
84 void *modref_list; /* 4c MODREF list */
85 void *thread_list; /* 50 List of threads */
86 void *debuggee_CB; /* 54 Debuggee context block */
87 void *local_heap_free; /* 58 Head of local heap free list */
88 DWORD unknown4; /* 5c Unknown */
89 CRITICAL_SECTION crit_section; /* 60 Critical section */
90 DWORD unknown5[3]; /* 78 Unknown */
91 void *console; /* 84 Console */
92 DWORD tls_bits[2]; /* 88 TLS in-use bits */
93 DWORD process_dword; /* 90 Unknown */
94 struct _PDB *group; /* 94 Process group */
95 void *exe_modref; /* 98 MODREF for the process EXE */
96 void *top_filter; /* 9c Top exception filter */
97 DWORD priority; /* a0 Priority level */
98 HANDLE heap_list; /* a4 Head of process heap list */
99 void *heap_handles; /* a8 Head of heap handles list */
100 DWORD unknown6; /* ac Unknown */
101 void *console_provider; /* b0 Console provider (??) */
102 WORD env_selector; /* b4 Selector to process environment */
103 WORD error_mode; /* b6 Error mode */
104 HANDLE load_done_evt; /* b8 Event for process loading done */
105 void *UTState; /* bc Head of Univeral Thunk list */
106 DWORD unknown8; /* c0 Unknown (NT) */
107 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
108 } PDB;
110 PDB current_process;
112 RTL_USER_PROCESS_PARAMETERS process_pmts;
114 /* Process flags */
115 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
116 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
117 #define PDB32_DOS_PROC 0x0010 /* Dos process */
118 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
119 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
120 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
122 static char main_exe_name[MAX_PATH];
123 static char *main_exe_name_ptr = main_exe_name;
124 static HANDLE main_exe_file;
125 static unsigned int server_startticks;
127 int main_create_flags = 0;
129 /* memory/environ.c */
130 extern struct _ENVDB *ENV_InitStartupInfo( size_t info_size, char *main_exe_name,
131 size_t main_exe_size );
132 extern BOOL ENV_BuildCommandLine( char **argv );
133 extern STARTUPINFOA current_startupinfo;
135 /* scheduler/pthread.c */
136 extern void PTHREAD_init_done(void);
138 extern void RELAY_InitDebugLists(void);
139 extern void SHELL_LoadRegistry(void);
140 extern void VERSION_Init( const char *appname );
142 /***********************************************************************
143 * get_basename
145 inline static const char *get_basename( const char *name )
147 char *p;
149 if ((p = strrchr( name, '/' ))) name = p + 1;
150 if ((p = strrchr( name, '\\' ))) name = p + 1;
151 return name;
155 /***********************************************************************
156 * open_builtin_exe_file
158 * Open an exe file for a builtin exe.
160 static void *open_builtin_exe_file( const char *name, char *error, int error_size, int test_only )
162 char exename[MAX_PATH], *p;
163 const char *basename = get_basename(name);
165 if (strlen(basename) >= sizeof(exename)) return NULL;
166 strcpy( exename, basename );
167 for (p = exename; *p; p++) *p = FILE_tolower(*p);
168 return wine_dll_load_main_exe( exename, error, error_size, test_only );
172 /***********************************************************************
173 * open_exe_file
175 * Open a specific exe file, taking load order into account.
176 * Returns the file handle or 0 for a builtin exe.
178 static HANDLE open_exe_file( const char *name )
180 enum loadorder_type loadorder[LOADORDER_NTYPES];
181 char buffer[MAX_PATH];
182 HANDLE handle;
183 int i;
185 TRACE("looking for %s\n", debugstr_a(name) );
187 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
188 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
190 /* file doesn't exist, check for builtin */
191 if (!FILE_contains_path( name )) goto error;
192 if (!MODULE_GetBuiltinPath( name, "", buffer, sizeof(buffer) )) goto error;
193 name = buffer;
196 MODULE_GetLoadOrder( loadorder, name, TRUE );
198 for(i = 0; i < LOADORDER_NTYPES; i++)
200 if (loadorder[i] == LOADORDER_INVALID) break;
201 switch(loadorder[i])
203 case LOADORDER_DLL:
204 TRACE( "Trying native exe %s\n", debugstr_a(name) );
205 if (handle != INVALID_HANDLE_VALUE) return handle;
206 break;
207 case LOADORDER_BI:
208 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
209 if (open_builtin_exe_file( name, NULL, 0, 1 ))
211 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
212 return 0;
214 default:
215 break;
218 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
220 error:
221 SetLastError( ERROR_FILE_NOT_FOUND );
222 return INVALID_HANDLE_VALUE;
226 /***********************************************************************
227 * find_exe_file
229 * Open an exe file, and return the full name and file handle.
230 * Returns FALSE if file could not be found.
231 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
232 * If file is a builtin exe, returns TRUE and sets handle to 0.
234 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
236 enum loadorder_type loadorder[LOADORDER_NTYPES];
237 int i;
239 TRACE("looking for %s\n", debugstr_a(name) );
241 if (!SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) &&
242 !MODULE_GetBuiltinPath( name, ".exe", buffer, buflen ))
244 /* no builtin found, try native without extension in case it is a Unix app */
246 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
248 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
249 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
250 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
251 return TRUE;
253 return FALSE;
256 MODULE_GetLoadOrder( loadorder, buffer, TRUE );
258 for(i = 0; i < LOADORDER_NTYPES; i++)
260 if (loadorder[i] == LOADORDER_INVALID) break;
261 switch(loadorder[i])
263 case LOADORDER_DLL:
264 TRACE( "Trying native exe %s\n", debugstr_a(buffer) );
265 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
266 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
267 return TRUE;
268 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
269 break;
270 case LOADORDER_BI:
271 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
272 if (open_builtin_exe_file( buffer, NULL, 0, 1 ))
274 *handle = 0;
275 return TRUE;
277 break;
278 default:
279 break;
282 SetLastError( ERROR_FILE_NOT_FOUND );
283 return FALSE;
287 /***********************************************************************
288 * process_init
290 * Main process initialisation code
292 static BOOL process_init( char *argv[] )
294 BOOL ret;
295 size_t info_size = 0;
297 setbuf(stdout,NULL);
298 setbuf(stderr,NULL);
299 setlocale(LC_CTYPE,"");
301 /* store the program name */
302 argv0 = argv[0];
304 /* Fill the initial process structure */
305 current_process.exit_code = STILL_ACTIVE;
306 current_process.threads = 1;
307 current_process.running_threads = 1;
308 current_process.ring0_threads = 1;
309 current_process.group = &current_process;
310 current_process.priority = 8; /* Normal */
312 /* Setup the server connection */
313 CLIENT_InitServer();
315 /* Retrieve startup info from the server */
316 SERVER_START_REQ( init_process )
318 req->ldt_copy = &wine_ldt_copy;
319 if ((ret = !wine_server_call_err( req )))
321 main_exe_file = reply->exe_file;
322 main_create_flags = reply->create_flags;
323 info_size = reply->info_size;
324 server_startticks = reply->server_start;
325 current_startupinfo.hStdInput = reply->hstdin;
326 current_startupinfo.hStdOutput = reply->hstdout;
327 current_startupinfo.hStdError = reply->hstderr;
330 SERVER_END_REQ;
331 if (!ret) return FALSE;
333 /* Create the process heap */
334 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
336 if (main_create_flags == 0 &&
337 current_startupinfo.hStdInput == 0 &&
338 current_startupinfo.hStdOutput == 0 &&
339 current_startupinfo.hStdError == 0)
341 /* no parent, and no new console requested, create a simple console with bare handles to
342 * unix stdio input & output streams (aka simple console)
344 HANDLE handle;
345 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &handle );
346 SetStdHandle( STD_INPUT_HANDLE, handle );
347 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
348 SetStdHandle( STD_OUTPUT_HANDLE, handle );
349 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &handle );
350 SetStdHandle( STD_ERROR_HANDLE, handle );
352 else if (!(main_create_flags & (DETACHED_PROCESS|CREATE_NEW_CONSOLE)))
354 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
355 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
356 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
359 /* Now we can use the pthreads routines */
360 PTHREAD_init_done();
362 /* Copy the parent environment */
363 if (!(current_process.env_db = ENV_InitStartupInfo( info_size, main_exe_name,
364 sizeof(main_exe_name) )))
365 return FALSE;
367 /* Parse command line arguments */
368 OPTIONS_ParseOptions( !info_size ? argv : NULL );
370 /* <hack: to be changed later on> */
371 build_initial_environment();
372 process_pmts.CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
373 process_pmts.CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
374 process_pmts.CurrentDirectoryName.Buffer = RtlAllocateHeap( ntdll_get_process_heap(), 0, process_pmts.CurrentDirectoryName.MaximumLength);
375 process_pmts.CurrentDirectoryName.Buffer[0] = 'C';
376 process_pmts.CurrentDirectoryName.Buffer[1] = ':';
377 process_pmts.CurrentDirectoryName.Buffer[2] = '\\';
378 process_pmts.CurrentDirectoryName.Buffer[3] = '\0';
379 /* </hack: to be changed later on> */
381 /* initialise DOS drives */
382 if (!DRIVE_Init()) return FALSE;
384 /* initialise DOS directories */
385 if (!DIR_Init()) return FALSE;
387 /* registry initialisation */
388 SHELL_LoadRegistry();
390 /* global boot finished, the rest is process-local */
391 CLIENT_BootDone( TRACE_ON(server) );
392 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
394 return TRUE;
398 /***********************************************************************
399 * start_process
401 * Startup routine of a new process. Runs on the new process stack.
403 static void start_process(void)
405 int debugged, console_app;
406 LPTHREAD_START_ROUTINE entry;
407 WINE_MODREF *wm;
408 HANDLE main_file = main_exe_file;
409 IMAGE_NT_HEADERS *nt;
411 /* use original argv[0] as name for the main module */
412 if (!main_exe_name[0])
414 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
415 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
418 if (main_file)
420 UINT drive_type = GetDriveTypeA( main_exe_name );
421 /* don't keep the file handle open on removable media */
422 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
425 /* Retrieve entry point address */
426 nt = RtlImageNtHeader( current_process.module );
427 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
428 nt->OptionalHeader.AddressOfEntryPoint);
429 console_app = (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
430 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
432 /* Install signal handlers; this cannot be done before, since we cannot
433 * send exceptions to the debugger before the create process event that
434 * is sent by REQ_INIT_PROCESS_DONE.
435 * We do need the handlers in place by the time the request is over, so
436 * we set them up here. If we segfault between here and the server call
437 * something is very wrong... */
438 if (!SIGNAL_Init()) goto error;
440 /* Signal the parent process to continue */
441 SERVER_START_REQ( init_process_done )
443 req->module = (void *)current_process.module;
444 req->module_size = nt->OptionalHeader.SizeOfImage;
445 req->entry = entry;
446 /* API requires a double indirection */
447 req->name = &main_exe_name_ptr;
448 req->exe_file = main_file;
449 req->gui = !console_app;
450 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
451 wine_server_call( req );
452 debugged = reply->debugged;
454 SERVER_END_REQ;
456 /* create the main modref and load dependencies */
457 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
458 goto error;
460 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
462 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
464 if (TRACE_ON(relay))
465 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n",
466 GetCurrentThreadId(), main_exe_name, entry );
467 if (debugged) DbgBreakPoint();
468 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
469 * Dunno about other OSs */
470 SetLastError(0); /* clear error code */
471 ExitThread( entry(NULL) );
473 error:
474 ExitProcess( GetLastError() );
478 /***********************************************************************
479 * __wine_process_init
481 * Wine initialisation: load and start the main exe file.
483 void __wine_process_init( int argc, char *argv[] )
485 char error[1024], *p;
486 DWORD stack_size = 0;
488 /* Initialize everything */
489 if (!process_init( argv )) exit(1);
491 argv++; /* remove argv[0] (wine itself) */
493 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
494 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
496 if (!main_exe_name[0])
498 if (!argv[0]) OPTIONS_Usage();
500 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
502 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
503 ExitProcess(1);
505 if (main_exe_file == INVALID_HANDLE_VALUE)
507 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
508 ExitProcess(1);
512 if (!main_exe_file) /* no file handle -> Winelib app */
514 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
515 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0 ))
516 goto found;
517 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
518 ExitProcess(1);
520 VERSION_Init( main_exe_name );
522 switch( MODULE_GetBinaryType( main_exe_file ))
524 case BINARY_PE_EXE:
525 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
526 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
527 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
528 ExitProcess(1);
529 case BINARY_PE_DLL:
530 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
531 ExitProcess(1);
532 case BINARY_UNKNOWN:
533 /* check for .com extension */
534 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
536 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
537 ExitProcess(1);
539 /* fall through */
540 case BINARY_WIN16:
541 case BINARY_DOS:
542 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
543 CloseHandle( main_exe_file );
544 main_exe_file = 0;
545 argv--;
546 argv[0] = "winevdm.exe";
547 if (open_builtin_exe_file( "winevdm.exe", error, sizeof(error), 0 ))
548 goto found;
549 MESSAGE( "%s: trying to run '%s', cannot open builtin library for 'winevdm.exe': %s\n",
550 argv0, main_exe_name, error );
551 ExitProcess(1);
552 case BINARY_OS216:
553 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
554 ExitProcess(1);
555 case BINARY_UNIX_EXE:
556 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
557 ExitProcess(1);
558 case BINARY_UNIX_LIB:
560 DOS_FULL_NAME full_name;
561 const char *name = main_exe_name;
562 UNICODE_STRING nameW;
564 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
565 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
566 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
567 RtlFreeUnicodeString(&nameW);
568 CloseHandle( main_exe_file );
569 main_exe_file = 0;
570 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
572 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
573 goto found;
575 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
576 ExitProcess(1);
580 found:
581 /* build command line */
582 if (!ENV_BuildCommandLine( argv )) goto error;
584 /* create 32-bit module for main exe */
585 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
586 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
588 /* allocate main thread stack */
589 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
591 /* switch to the new stack */
592 SYSDEPS_SwitchToThreadStack( start_process );
594 error:
595 ExitProcess( GetLastError() );
599 /***********************************************************************
600 * build_argv
602 * Build an argv array from a command-line.
603 * The command-line is modified to insert nulls.
604 * 'reserved' is the number of args to reserve before the first one.
606 static char **build_argv( char *cmdline, int reserved )
608 int argc;
609 char** argv;
610 char *arg,*s,*d;
611 int in_quotes,bcount;
613 argc=reserved+1;
614 bcount=0;
615 in_quotes=0;
616 s=cmdline;
617 while (1) {
618 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
619 /* space */
620 argc++;
621 /* skip the remaining spaces */
622 while (*s==' ' || *s=='\t') {
623 s++;
625 if (*s=='\0')
626 break;
627 bcount=0;
628 continue;
629 } else if (*s=='\\') {
630 /* '\', count them */
631 bcount++;
632 } else if ((*s=='"') && ((bcount & 1)==0)) {
633 /* unescaped '"' */
634 in_quotes=!in_quotes;
635 bcount=0;
636 } else {
637 /* a regular character */
638 bcount=0;
640 s++;
642 argv=malloc(argc*sizeof(*argv));
643 if (!argv)
644 return NULL;
646 arg=d=s=cmdline;
647 bcount=0;
648 in_quotes=0;
649 argc=reserved;
650 while (*s) {
651 if ((*s==' ' || *s=='\t') && !in_quotes) {
652 /* Close the argument and copy it */
653 *d=0;
654 argv[argc++]=arg;
656 /* skip the remaining spaces */
657 do {
658 s++;
659 } while (*s==' ' || *s=='\t');
661 /* Start with a new argument */
662 arg=d=s;
663 bcount=0;
664 } else if (*s=='\\') {
665 /* '\\' */
666 *d++=*s++;
667 bcount++;
668 } else if (*s=='"') {
669 /* '"' */
670 if ((bcount & 1)==0) {
671 /* Preceeded by an even number of '\', this is half that
672 * number of '\', plus a '"' which we discard.
674 d-=bcount/2;
675 s++;
676 in_quotes=!in_quotes;
677 } else {
678 /* Preceeded by an odd number of '\', this is half that
679 * number of '\' followed by a '"'
681 d=d-bcount/2-1;
682 *d++='"';
683 s++;
685 bcount=0;
686 } else {
687 /* a regular character */
688 *d++=*s++;
689 bcount=0;
692 if (*arg) {
693 *d='\0';
694 argv[argc++]=arg;
696 argv[argc]=NULL;
698 return argv;
702 /***********************************************************************
703 * build_envp
705 * Build the environment of a new child process.
707 static char **build_envp( const char *env, const char *extra_env )
709 const char *p;
710 char **envp;
711 int count = 0;
713 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
714 for (p = env; *p; count++) p += strlen(p) + 1;
715 count += 3;
717 if ((envp = malloc( count * sizeof(*envp) )))
719 extern char **environ;
720 char **envptr = envp;
721 char **unixptr = environ;
722 /* first the extra strings */
723 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
724 /* then put PATH, HOME and WINEPREFIX from the unix env */
725 for (unixptr = environ; unixptr && *unixptr; unixptr++)
726 if (!memcmp( *unixptr, "PATH=", 5 ) ||
727 !memcmp( *unixptr, "HOME=", 5 ) ||
728 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
729 /* now put the Windows environment strings */
730 for (p = env; *p; p += strlen(p) + 1)
732 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
734 char *winepath = malloc( strlen(p) + 5 );
735 strcpy( winepath, "WINE" );
736 strcpy( winepath + 4, p );
737 *envptr++ = winepath;
739 else if (memcmp( p, "HOME=", 5 ) &&
740 memcmp( p, "WINEPATH=", 9 ) &&
741 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
743 *envptr = 0;
745 return envp;
749 /***********************************************************************
750 * exec_wine_binary
752 * Locate the Wine binary to exec for a new Win32 process.
754 static void exec_wine_binary( char **argv, char **envp )
756 const char *path, *pos, *ptr;
758 /* first, try for a WINELOADER environment variable */
759 argv[0] = getenv("WINELOADER");
760 if (argv[0])
761 execve( argv[0], argv, envp );
763 /* next, try bin directory */
764 argv[0] = BINDIR "/wine";
765 execve( argv[0], argv, envp );
767 /* now try the path of argv0 of the current binary */
768 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
769 if ((ptr = strrchr( full_argv0, '/' )))
771 memcpy( argv[0], full_argv0, ptr - full_argv0 );
772 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
773 execve( argv[0], argv, envp );
775 free( argv[0] );
777 /* now search in the Unix path */
778 if ((path = getenv( "PATH" )))
780 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
781 pos = path;
782 for (;;)
784 while (*pos == ':') pos++;
785 if (!*pos) break;
786 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
787 memcpy( argv[0], pos, ptr - pos );
788 strcpy( argv[0] + (ptr - pos), "/wine" );
789 execve( argv[0], argv, envp );
790 pos = ptr;
793 free( argv[0] );
797 /***********************************************************************
798 * fork_and_exec
800 * Fork and exec a new Unix binary, checking for errors.
802 static int fork_and_exec( const char *filename, char *cmdline,
803 const char *env, const char *newdir )
805 int fd[2];
806 int pid, err;
808 if (!env) env = GetEnvironmentStringsA();
810 if (pipe(fd) == -1)
812 FILE_SetDosError();
813 return -1;
815 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
816 if (!(pid = fork())) /* child */
818 char **argv = build_argv( cmdline, 0 );
819 char **envp = build_envp( env, NULL );
820 close( fd[0] );
822 /* Reset signals that we previously set to SIG_IGN */
823 signal( SIGPIPE, SIG_DFL );
824 signal( SIGCHLD, SIG_DFL );
826 if (newdir) chdir(newdir);
828 if (argv && envp) execve( filename, argv, envp );
829 err = errno;
830 write( fd[1], &err, sizeof(err) );
831 _exit(1);
833 close( fd[1] );
834 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
836 errno = err;
837 pid = -1;
839 if (pid == -1) FILE_SetDosError();
840 close( fd[0] );
841 return pid;
845 /***********************************************************************
846 * create_process
848 * Create a new process. If hFile is a valid handle we have an exe
849 * file, otherwise it is a Winelib app.
851 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
852 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
853 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
854 LPPROCESS_INFORMATION info, LPCSTR unixdir )
856 BOOL ret, success = FALSE;
857 HANDLE process_info;
858 startup_info_t startup_info;
859 char *extra_env = NULL;
860 int startfd[2];
861 int execfd[2];
862 pid_t pid;
863 int err;
864 char dummy;
866 if (!env)
868 env = GetEnvironmentStringsA();
869 extra_env = DRIVE_BuildEnv();
872 /* create the synchronization pipes */
874 if (pipe( startfd ) == -1)
876 FILE_SetDosError();
877 return FALSE;
879 if (pipe( execfd ) == -1)
881 close( startfd[0] );
882 close( startfd[1] );
883 FILE_SetDosError();
884 return FALSE;
886 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
888 /* create the child process */
890 if (!(pid = fork())) /* child */
892 char **argv = build_argv( cmd_line, 1 );
893 char **envp = build_envp( env, extra_env );
895 close( startfd[1] );
896 close( execfd[0] );
898 /* wait for parent to tell us to start */
899 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
901 close( startfd[0] );
902 /* Reset signals that we previously set to SIG_IGN */
903 signal( SIGPIPE, SIG_DFL );
904 signal( SIGCHLD, SIG_DFL );
906 if (unixdir) chdir(unixdir);
908 if (argv && envp) exec_wine_binary( argv, envp );
910 err = errno;
911 write( execfd[1], &err, sizeof(err) );
912 _exit(1);
915 /* this is the parent */
917 close( startfd[0] );
918 close( execfd[1] );
919 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
920 if (pid == -1)
922 close( startfd[1] );
923 close( execfd[0] );
924 FILE_SetDosError();
925 return FALSE;
928 /* fill the startup info structure */
930 startup_info.size = sizeof(startup_info);
931 /* startup_info.filename_len is set below */
932 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
933 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
934 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
935 startup_info.x = startup->dwX;
936 startup_info.y = startup->dwY;
937 startup_info.cx = startup->dwXSize;
938 startup_info.cy = startup->dwYSize;
939 startup_info.x_chars = startup->dwXCountChars;
940 startup_info.y_chars = startup->dwYCountChars;
941 startup_info.attribute = startup->dwFillAttribute;
942 startup_info.cmd_show = startup->wShowWindow;
943 startup_info.flags = startup->dwFlags;
945 /* create the process on the server side */
947 SERVER_START_REQ( new_process )
949 char buf[MAX_PATH];
950 LPCSTR nameptr;
952 req->inherit_all = inherit;
953 req->create_flags = flags;
954 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
955 req->unix_pid = pid;
956 req->exe_file = hFile;
957 if (startup->dwFlags & STARTF_USESTDHANDLES)
959 req->hstdin = startup->hStdInput;
960 req->hstdout = startup->hStdOutput;
961 req->hstderr = startup->hStdError;
963 else
965 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
966 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
967 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
970 if (GetLongPathNameA( filename, buf, MAX_PATH ))
971 nameptr = buf;
972 else
973 nameptr = filename;
975 startup_info.filename_len = strlen(nameptr);
976 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
977 wine_server_add_data( req, nameptr, startup_info.filename_len );
978 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
979 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
980 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
982 ret = !wine_server_call_err( req );
983 process_info = reply->info;
985 SERVER_END_REQ;
987 if (!ret)
989 close( startfd[1] );
990 close( execfd[0] );
991 return FALSE;
994 /* tell child to start and wait for it to exec */
996 write( startfd[1], &dummy, 1 );
997 close( startfd[1] );
999 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1001 errno = err;
1002 FILE_SetDosError();
1003 close( execfd[0] );
1004 CloseHandle( process_info );
1005 return FALSE;
1008 /* wait for the new process info to be ready */
1010 WaitForSingleObject( process_info, INFINITE );
1011 SERVER_START_REQ( get_new_process_info )
1013 req->info = process_info;
1014 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1015 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1016 if ((ret = !wine_server_call_err( req )))
1018 info->dwProcessId = (DWORD)reply->pid;
1019 info->dwThreadId = (DWORD)reply->tid;
1020 info->hProcess = reply->phandle;
1021 info->hThread = reply->thandle;
1022 success = reply->success;
1025 SERVER_END_REQ;
1027 if (ret && !success) /* new process failed to start */
1029 DWORD exitcode;
1030 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1031 CloseHandle( info->hThread );
1032 CloseHandle( info->hProcess );
1033 ret = FALSE;
1035 CloseHandle( process_info );
1036 return ret;
1040 /***********************************************************************
1041 * create_vdm_process
1043 * Create a new VDM process for a 16-bit or DOS application.
1045 static BOOL create_vdm_process( LPCSTR filename, LPSTR cmd_line, LPCSTR env,
1046 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1047 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
1048 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1050 BOOL ret;
1051 LPSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + strlen(cmd_line) + 30 );
1053 if (!new_cmd_line)
1055 SetLastError( ERROR_OUTOFMEMORY );
1056 return FALSE;
1058 sprintf( new_cmd_line, "winevdm.exe --app-name \"%s\" %s", filename, cmd_line );
1059 ret = create_process( 0, "winevdm.exe", new_cmd_line, env, psa, tsa, inherit,
1060 flags, startup, info, unixdir );
1061 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1062 return ret;
1066 /*************************************************************************
1067 * get_file_name
1069 * Helper for CreateProcess: retrieve the file name to load from the
1070 * app name and command line. Store the file name in buffer, and
1071 * return a possibly modified command line.
1072 * Also returns a handle to the opened file if it's a Windows binary.
1074 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1075 int buflen, HANDLE *handle )
1077 char *name, *pos, *ret = NULL;
1078 const char *p;
1080 /* if we have an app name, everything is easy */
1082 if (appname)
1084 /* use the unmodified app name as file name */
1085 lstrcpynA( buffer, appname, buflen );
1086 *handle = open_exe_file( buffer );
1087 if (!(ret = cmdline) || !cmdline[0])
1089 /* no command-line, create one */
1090 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1091 sprintf( ret, "\"%s\"", appname );
1093 return ret;
1096 if (!cmdline)
1098 SetLastError( ERROR_INVALID_PARAMETER );
1099 return NULL;
1102 /* first check for a quoted file name */
1104 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1106 int len = p - cmdline - 1;
1107 /* extract the quoted portion as file name */
1108 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1109 memcpy( name, cmdline + 1, len );
1110 name[len] = 0;
1112 if (find_exe_file( name, buffer, buflen, handle ))
1113 ret = cmdline; /* no change necessary */
1114 goto done;
1117 /* now try the command-line word by word */
1119 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1120 pos = name;
1121 p = cmdline;
1123 while (*p)
1125 do *pos++ = *p++; while (*p && *p != ' ');
1126 *pos = 0;
1127 if (find_exe_file( name, buffer, buflen, handle ))
1129 ret = cmdline;
1130 break;
1134 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1136 /* now build a new command-line with quotes */
1138 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1139 sprintf( ret, "\"%s\"%s", name, p );
1141 done:
1142 HeapFree( GetProcessHeap(), 0, name );
1143 return ret;
1147 /**********************************************************************
1148 * CreateProcessA (KERNEL32.@)
1150 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1151 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1152 DWORD flags, LPVOID env, LPCSTR cur_dir,
1153 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1155 BOOL retv = FALSE;
1156 HANDLE hFile = 0;
1157 const char *unixdir = NULL;
1158 DOS_FULL_NAME full_dir;
1159 char name[MAX_PATH];
1160 LPSTR tidy_cmdline;
1161 char *p;
1163 /* Process the AppName and/or CmdLine to get module name and path */
1165 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1167 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1168 return FALSE;
1169 if (hFile == INVALID_HANDLE_VALUE) goto done;
1171 /* Warn if unsupported features are used */
1173 if (flags & NORMAL_PRIORITY_CLASS)
1174 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1175 if (flags & IDLE_PRIORITY_CLASS)
1176 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1177 if (flags & HIGH_PRIORITY_CLASS)
1178 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1179 if (flags & REALTIME_PRIORITY_CLASS)
1180 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1181 if (flags & CREATE_NEW_PROCESS_GROUP)
1182 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1183 if (flags & CREATE_UNICODE_ENVIRONMENT)
1184 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1185 if (flags & CREATE_SEPARATE_WOW_VDM)
1186 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1187 if (flags & CREATE_SHARED_WOW_VDM)
1188 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1189 if (flags & CREATE_DEFAULT_ERROR_MODE)
1190 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1191 if (flags & CREATE_NO_WINDOW)
1192 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1193 if (flags & PROFILE_USER)
1194 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1195 if (flags & PROFILE_KERNEL)
1196 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1197 if (flags & PROFILE_SERVER)
1198 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1199 if (startup_info->lpDesktop)
1200 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1201 name, debugstr_a(startup_info->lpDesktop));
1202 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1203 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1204 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1205 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1206 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1207 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1208 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1209 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1211 if (cur_dir)
1213 UNICODE_STRING cur_dirW;
1214 RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1215 if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1216 unixdir = full_dir.long_name;
1217 RtlFreeUnicodeString(&cur_dirW);
1219 else
1221 WCHAR buf[MAX_PATH];
1222 if (GetCurrentDirectoryW(MAX_PATH, buf))
1224 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1228 info->hThread = info->hProcess = 0;
1229 info->dwProcessId = info->dwThreadId = 0;
1231 /* Determine executable type */
1233 if (!hFile) /* builtin exe */
1235 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1236 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1237 inherit, flags, startup_info, info, unixdir );
1238 goto done;
1241 switch( MODULE_GetBinaryType( hFile ))
1243 case BINARY_PE_EXE:
1244 TRACE( "starting %s as Win32 binary\n", debugstr_a(name) );
1245 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1246 inherit, flags, startup_info, info, unixdir );
1247 break;
1248 case BINARY_WIN16:
1249 case BINARY_DOS:
1250 TRACE( "starting %s as Win16/DOS binary\n", debugstr_a(name) );
1251 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1252 inherit, flags, startup_info, info, unixdir );
1253 break;
1254 case BINARY_OS216:
1255 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1256 SetLastError( ERROR_BAD_EXE_FORMAT );
1257 break;
1258 case BINARY_PE_DLL:
1259 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1260 SetLastError( ERROR_BAD_EXE_FORMAT );
1261 break;
1262 case BINARY_UNIX_LIB:
1263 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1264 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1265 inherit, flags, startup_info, info, unixdir );
1266 break;
1267 case BINARY_UNKNOWN:
1268 /* check for .com or .bat extension */
1269 if ((p = strrchr( name, '.' )))
1271 if (!FILE_strcasecmp( p, ".com" ))
1273 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1274 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1275 inherit, flags, startup_info, info, unixdir );
1276 break;
1278 if (!FILE_strcasecmp( p, ".bat" ))
1280 char comspec[MAX_PATH];
1281 if (GetEnvironmentVariableA("COMSPEC", comspec, sizeof(comspec)))
1283 char *newcmdline;
1284 if ((newcmdline = HeapAlloc( GetProcessHeap(), 0,
1285 strlen(comspec) + 4 + strlen(tidy_cmdline) + 1)))
1287 sprintf( newcmdline, "%s /c %s", comspec, tidy_cmdline);
1288 TRACE( "starting %s as batch binary: %s\n",
1289 debugstr_a(name), debugstr_a(newcmdline) );
1290 retv = CreateProcessA( comspec, newcmdline, process_attr, thread_attr,
1291 inherit, flags, env, cur_dir, startup_info, info );
1292 HeapFree( GetProcessHeap(), 0, newcmdline );
1293 break;
1298 /* fall through */
1299 case BINARY_UNIX_EXE:
1301 /* unknown file, try as unix executable */
1302 UNICODE_STRING nameW;
1303 DOS_FULL_NAME full_name;
1304 const char *unixfilename = name;
1306 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1308 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1309 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1310 RtlFreeUnicodeString(&nameW);
1311 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1313 break;
1315 CloseHandle( hFile );
1317 done:
1318 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1319 return retv;
1323 /**********************************************************************
1324 * CreateProcessW (KERNEL32.@)
1325 * NOTES
1326 * lpReserved is not converted
1328 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1329 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1330 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1331 LPPROCESS_INFORMATION info )
1333 BOOL ret;
1334 STARTUPINFOA StartupInfoA;
1336 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1337 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1338 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1340 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1341 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1342 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1344 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1346 if (startup_info->lpReserved)
1347 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1348 debugstr_w(startup_info->lpReserved));
1350 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1351 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1353 HeapFree( GetProcessHeap(), 0, cur_dirA );
1354 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1355 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1356 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1358 return ret;
1362 /***********************************************************************
1363 * ExitProcess (KERNEL32.@)
1365 void WINAPI ExitProcess( DWORD status )
1367 LdrShutdownProcess();
1368 SERVER_START_REQ( terminate_process )
1370 /* send the exit code to the server */
1371 req->handle = GetCurrentProcess();
1372 req->exit_code = status;
1373 wine_server_call( req );
1375 SERVER_END_REQ;
1376 exit( status );
1379 /***********************************************************************
1380 * ExitProcess (KERNEL.466)
1382 void WINAPI ExitProcess16( WORD status )
1384 DWORD count;
1385 ReleaseThunkLock( &count );
1386 ExitProcess( status );
1389 /******************************************************************************
1390 * TerminateProcess (KERNEL32.@)
1392 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1394 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1395 if (status) SetLastError( RtlNtStatusToDosError(status) );
1396 return !status;
1400 /***********************************************************************
1401 * GetProcessDword (KERNEL.485)
1402 * GetProcessDword (KERNEL32.18)
1403 * 'Of course you cannot directly access Windows internal structures'
1405 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1407 DWORD x, y;
1409 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1411 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1413 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1414 return 0;
1417 switch ( offset )
1419 case GPD_APP_COMPAT_FLAGS:
1420 return GetAppCompatFlags16(0);
1422 case GPD_LOAD_DONE_EVENT:
1423 return (DWORD)current_process.load_done_evt;
1425 case GPD_HINSTANCE16:
1426 return GetTaskDS16();
1428 case GPD_WINDOWS_VERSION:
1429 return GetExeVersion16();
1431 case GPD_THDB:
1432 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
1434 case GPD_PDB:
1435 return (DWORD)&current_process;
1437 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
1438 return (DWORD)current_startupinfo.hStdOutput;
1440 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
1441 return (DWORD)current_startupinfo.hStdInput;
1443 case GPD_STARTF_SHOWWINDOW:
1444 return current_startupinfo.wShowWindow;
1446 case GPD_STARTF_SIZE:
1447 x = current_startupinfo.dwXSize;
1448 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1449 y = current_startupinfo.dwYSize;
1450 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1451 return MAKELONG( x, y );
1453 case GPD_STARTF_POSITION:
1454 x = current_startupinfo.dwX;
1455 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1456 y = current_startupinfo.dwY;
1457 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1458 return MAKELONG( x, y );
1460 case GPD_STARTF_FLAGS:
1461 return current_startupinfo.dwFlags;
1463 case GPD_PARENT:
1464 return 0;
1466 case GPD_FLAGS:
1467 return current_process.flags;
1469 case GPD_USERDATA:
1470 return current_process.process_dword;
1472 default:
1473 ERR_(win32)("Unknown offset %d\n", offset );
1474 return 0;
1478 /***********************************************************************
1479 * SetProcessDword (KERNEL.484)
1480 * 'Of course you cannot directly access Windows internal structures'
1482 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1484 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1486 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1488 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1489 return;
1492 switch ( offset )
1494 case GPD_APP_COMPAT_FLAGS:
1495 case GPD_LOAD_DONE_EVENT:
1496 case GPD_HINSTANCE16:
1497 case GPD_WINDOWS_VERSION:
1498 case GPD_THDB:
1499 case GPD_PDB:
1500 case GPD_STARTF_SHELLDATA:
1501 case GPD_STARTF_HOTKEY:
1502 case GPD_STARTF_SHOWWINDOW:
1503 case GPD_STARTF_SIZE:
1504 case GPD_STARTF_POSITION:
1505 case GPD_STARTF_FLAGS:
1506 case GPD_PARENT:
1507 case GPD_FLAGS:
1508 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1509 break;
1511 case GPD_USERDATA:
1512 current_process.process_dword = value;
1513 break;
1515 default:
1516 ERR_(win32)("Unknown offset %d\n", offset );
1517 break;
1522 /*********************************************************************
1523 * OpenProcess (KERNEL32.@)
1525 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1527 HANDLE ret = 0;
1528 SERVER_START_REQ( open_process )
1530 req->pid = id;
1531 req->access = access;
1532 req->inherit = inherit;
1533 if (!wine_server_call_err( req )) ret = reply->handle;
1535 SERVER_END_REQ;
1536 return ret;
1539 /*********************************************************************
1540 * MapProcessHandle (KERNEL.483)
1542 DWORD WINAPI MapProcessHandle( HANDLE handle )
1544 DWORD ret = 0;
1545 SERVER_START_REQ( get_process_info )
1547 req->handle = handle;
1548 if (!wine_server_call_err( req )) ret = (DWORD)reply->pid;
1550 SERVER_END_REQ;
1551 return ret;
1554 /***********************************************************************
1555 * SetPriorityClass (KERNEL32.@)
1557 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1559 BOOL ret;
1560 SERVER_START_REQ( set_process_info )
1562 req->handle = hprocess;
1563 req->priority = priorityclass;
1564 req->mask = SET_PROCESS_INFO_PRIORITY;
1565 ret = !wine_server_call_err( req );
1567 SERVER_END_REQ;
1568 return ret;
1572 /***********************************************************************
1573 * GetPriorityClass (KERNEL32.@)
1575 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1577 DWORD ret = 0;
1578 SERVER_START_REQ( get_process_info )
1580 req->handle = hprocess;
1581 if (!wine_server_call_err( req )) ret = reply->priority;
1583 SERVER_END_REQ;
1584 return ret;
1588 /***********************************************************************
1589 * SetProcessAffinityMask (KERNEL32.@)
1591 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1593 BOOL ret;
1594 SERVER_START_REQ( set_process_info )
1596 req->handle = hProcess;
1597 req->affinity = affmask;
1598 req->mask = SET_PROCESS_INFO_AFFINITY;
1599 ret = !wine_server_call_err( req );
1601 SERVER_END_REQ;
1602 return ret;
1605 /**********************************************************************
1606 * GetProcessAffinityMask (KERNEL32.@)
1608 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1609 LPDWORD lpProcessAffinityMask,
1610 LPDWORD lpSystemAffinityMask )
1612 BOOL ret = FALSE;
1613 SERVER_START_REQ( get_process_info )
1615 req->handle = hProcess;
1616 if (!wine_server_call_err( req ))
1618 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
1619 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
1620 ret = TRUE;
1623 SERVER_END_REQ;
1624 return ret;
1628 /***********************************************************************
1629 * GetProcessVersion (KERNEL32.@)
1631 DWORD WINAPI GetProcessVersion( DWORD processid )
1633 IMAGE_NT_HEADERS *nt;
1635 if (processid && processid != GetCurrentProcessId())
1637 FIXME("should use ReadProcessMemory\n");
1638 return 0;
1640 if ((nt = RtlImageNtHeader( current_process.module )))
1641 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1642 nt->OptionalHeader.MinorSubsystemVersion);
1643 return 0;
1646 /***********************************************************************
1647 * GetProcessFlags (KERNEL32.@)
1649 DWORD WINAPI GetProcessFlags( DWORD processid )
1651 if (processid && processid != GetCurrentProcessId()) return 0;
1652 return current_process.flags;
1656 /***********************************************************************
1657 * SetProcessWorkingSetSize [KERNEL32.@]
1658 * Sets the min/max working set sizes for a specified process.
1660 * PARAMS
1661 * hProcess [I] Handle to the process of interest
1662 * minset [I] Specifies minimum working set size
1663 * maxset [I] Specifies maximum working set size
1665 * RETURNS STD
1667 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
1668 SIZE_T maxset)
1670 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1671 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
1672 /* Trim the working set to zero */
1673 /* Swap the process out of physical RAM */
1675 return TRUE;
1678 /***********************************************************************
1679 * GetProcessWorkingSetSize (KERNEL32.@)
1681 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
1682 PSIZE_T maxset)
1684 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
1685 /* 32 MB working set size */
1686 if (minset) *minset = 32*1024*1024;
1687 if (maxset) *maxset = 32*1024*1024;
1688 return TRUE;
1691 /***********************************************************************
1692 * SetProcessShutdownParameters (KERNEL32.@)
1694 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1695 * Now tracks changes made (but does not act on these changes)
1697 static DWORD shutdown_flags = 0;
1698 static DWORD shutdown_priority = 0x280;
1700 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1702 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1703 shutdown_flags = flags;
1704 shutdown_priority = level;
1705 return TRUE;
1709 /***********************************************************************
1710 * GetProcessShutdownParameters (KERNEL32.@)
1713 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1715 *lpdwLevel = shutdown_priority;
1716 *lpdwFlags = shutdown_flags;
1717 return TRUE;
1721 /***********************************************************************
1722 * GetProcessPriorityBoost (KERNEL32.@)
1724 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
1726 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
1728 /* Report that no boost is present.. */
1729 *pDisablePriorityBoost = FALSE;
1731 return TRUE;
1734 /***********************************************************************
1735 * SetProcessPriorityBoost (KERNEL32.@)
1737 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1739 FIXME("(%p,%d): stub\n",hprocess,disableboost);
1740 /* Say we can do it. I doubt the program will notice that we don't. */
1741 return TRUE;
1745 /***********************************************************************
1746 * ReadProcessMemory (KERNEL32.@)
1748 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
1749 SIZE_T *bytes_read )
1751 DWORD res;
1753 SERVER_START_REQ( read_process_memory )
1755 req->handle = process;
1756 req->addr = (void *)addr;
1757 wine_server_set_reply( req, buffer, size );
1758 if ((res = wine_server_call_err( req ))) size = 0;
1760 SERVER_END_REQ;
1761 if (bytes_read) *bytes_read = size;
1762 return !res;
1766 /***********************************************************************
1767 * WriteProcessMemory (KERNEL32.@)
1769 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
1770 SIZE_T *bytes_written )
1772 static const int zero;
1773 unsigned int first_offset, last_offset, first_mask, last_mask;
1774 DWORD res;
1776 if (!size)
1778 SetLastError( ERROR_INVALID_PARAMETER );
1779 return FALSE;
1782 /* compute the mask for the first int */
1783 first_mask = ~0;
1784 first_offset = (unsigned int)addr % sizeof(int);
1785 memset( &first_mask, 0, first_offset );
1787 /* compute the mask for the last int */
1788 last_offset = (size + first_offset) % sizeof(int);
1789 last_mask = 0;
1790 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1792 SERVER_START_REQ( write_process_memory )
1794 req->handle = process;
1795 req->addr = (char *)addr - first_offset;
1796 req->first_mask = first_mask;
1797 req->last_mask = last_mask;
1798 if (first_offset) wine_server_add_data( req, &zero, first_offset );
1799 wine_server_add_data( req, buffer, size );
1800 if (last_offset) wine_server_add_data( req, &zero, sizeof(int) - last_offset );
1802 if ((res = wine_server_call_err( req ))) size = 0;
1804 SERVER_END_REQ;
1805 if (bytes_written) *bytes_written = size;
1807 char dummy[32];
1808 SIZE_T read;
1809 ReadProcessMemory( process, addr, dummy, sizeof(dummy), &read );
1811 return !res;
1815 /***********************************************************************
1816 * RegisterServiceProcess (KERNEL.491)
1817 * RegisterServiceProcess (KERNEL32.@)
1819 * A service process calls this function to ensure that it continues to run
1820 * even after a user logged off.
1822 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1824 /* I don't think that Wine needs to do anything in that function */
1825 return 1; /* success */
1828 /***********************************************************************
1829 * GetExitCodeProcess [KERNEL32.@]
1831 * Gets termination status of specified process
1833 * RETURNS
1834 * Success: TRUE
1835 * Failure: FALSE
1837 BOOL WINAPI GetExitCodeProcess(
1838 HANDLE hProcess, /* [in] handle to the process */
1839 LPDWORD lpExitCode) /* [out] address to receive termination status */
1841 BOOL ret;
1842 SERVER_START_REQ( get_process_info )
1844 req->handle = hProcess;
1845 ret = !wine_server_call_err( req );
1846 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1848 SERVER_END_REQ;
1849 return ret;
1853 /***********************************************************************
1854 * SetErrorMode (KERNEL32.@)
1856 UINT WINAPI SetErrorMode( UINT mode )
1858 UINT old = current_process.error_mode;
1859 current_process.error_mode = mode;
1860 return old;
1864 /**************************************************************************
1865 * SetFileApisToOEM (KERNEL32.@)
1867 VOID WINAPI SetFileApisToOEM(void)
1869 current_process.flags |= PDB32_FILE_APIS_OEM;
1873 /**************************************************************************
1874 * SetFileApisToANSI (KERNEL32.@)
1876 VOID WINAPI SetFileApisToANSI(void)
1878 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1882 /******************************************************************************
1883 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1885 * RETURNS
1886 * TRUE: Set of file functions is using ANSI code page
1887 * FALSE: Set of file functions is using OEM code page
1889 BOOL WINAPI AreFileApisANSI(void)
1891 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1895 /***********************************************************************
1896 * GetTickCount (KERNEL32.@)
1898 * Returns the number of milliseconds, modulo 2^32, since the start
1899 * of the wineserver.
1901 DWORD WINAPI GetTickCount(void)
1903 struct timeval t;
1904 gettimeofday( &t, NULL );
1905 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1909 /**********************************************************************
1910 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1912 * Allocates a thread local storage index
1914 * RETURNS
1915 * Success: TLS Index
1916 * Failure: 0xFFFFFFFF
1918 DWORD WINAPI TlsAlloc( void )
1920 DWORD i, mask, ret = 0;
1921 DWORD *bits = current_process.tls_bits;
1922 RtlAcquirePebLock();
1923 if (*bits == 0xffffffff)
1925 bits++;
1926 ret = 32;
1927 if (*bits == 0xffffffff)
1929 RtlReleasePebLock();
1930 SetLastError( ERROR_NO_MORE_ITEMS );
1931 return 0xffffffff;
1934 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1935 *bits |= mask;
1936 RtlReleasePebLock();
1937 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1938 return ret + i;
1942 /**********************************************************************
1943 * TlsFree [KERNEL32.@] Releases a TLS index.
1945 * Releases a thread local storage index, making it available for reuse
1947 * RETURNS
1948 * Success: TRUE
1949 * Failure: FALSE
1951 BOOL WINAPI TlsFree(
1952 DWORD index) /* [in] TLS Index to free */
1954 DWORD mask = (1 << (index & 31));
1955 DWORD *bits = current_process.tls_bits;
1956 if (index >= 64)
1958 SetLastError( ERROR_INVALID_PARAMETER );
1959 return FALSE;
1961 if (index >= 32) bits++;
1962 RtlAcquirePebLock();
1963 if (!(*bits & mask)) /* already free? */
1965 RtlReleasePebLock();
1966 SetLastError( ERROR_INVALID_PARAMETER );
1967 return FALSE;
1969 *bits &= ~mask;
1970 NtCurrentTeb()->tls_array[index] = 0;
1971 /* FIXME: should zero all other thread values */
1972 RtlReleasePebLock();
1973 return TRUE;
1977 /**********************************************************************
1978 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1980 * RETURNS
1981 * Success: Value stored in calling thread's TLS slot for index
1982 * Failure: 0 and GetLastError returns NO_ERROR
1984 LPVOID WINAPI TlsGetValue(
1985 DWORD index) /* [in] TLS index to retrieve value for */
1987 if (index >= 64)
1989 SetLastError( ERROR_INVALID_PARAMETER );
1990 return NULL;
1992 SetLastError( ERROR_SUCCESS );
1993 return NtCurrentTeb()->tls_array[index];
1997 /**********************************************************************
1998 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2000 * RETURNS
2001 * Success: TRUE
2002 * Failure: FALSE
2004 BOOL WINAPI TlsSetValue(
2005 DWORD index, /* [in] TLS index to set value for */
2006 LPVOID value) /* [in] Value to be stored */
2008 if (index >= 64)
2010 SetLastError( ERROR_INVALID_PARAMETER );
2011 return FALSE;
2013 NtCurrentTeb()->tls_array[index] = value;
2014 return TRUE;
2018 /***********************************************************************
2019 * GetCurrentProcess (KERNEL32.@)
2021 #undef GetCurrentProcess
2022 HANDLE WINAPI GetCurrentProcess(void)
2024 return (HANDLE)0xffffffff;