Updated the "TODO" comments.
[wine/multimedia.git] / scheduler / process.c
blob266e285a10781f3c32c7eccf78dc1d080256b9cf
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 "../kernel/kernel_private.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 /* Win32 process database */
59 typedef struct _PDB
61 LONG header[2]; /* 00 Kernel object header */
62 HMODULE module; /* 08 Main exe module (NT) */
63 PPEB_LDR_DATA LdrData; /* 0c Pointer to loader information */
64 RTL_USER_PROCESS_PARAMETERS *ProcessParameters; /* 10 Process parameters */
65 DWORD unknown2; /* 14 Unknown */
66 HANDLE heap; /* 18 Default process heap */
67 HANDLE mem_context; /* 1c Process memory context */
68 DWORD flags; /* 20 Flags */
69 void *pdb16; /* 24 DOS PSP */
70 WORD PSP_sel; /* 28 Selector to DOS PSP */
71 WORD imte; /* 2a IMTE for the process module */
72 WORD threads; /* 2c Number of threads */
73 WORD running_threads; /* 2e Number of running threads */
74 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
75 WORD ring0_threads; /* 32 Number of ring 0 threads */
76 HANDLE system_heap; /* 34 System heap to allocate handles */
77 HTASK task; /* 38 Win16 task */
78 void *mem_map_files; /* 3c Pointer to mem-mapped files */
79 struct _ENVDB *env_db; /* 40 Environment database */
80 void *handle_table; /* 44 Handle table */
81 struct _PDB *parent; /* 48 Parent process */
82 void *modref_list; /* 4c MODREF list */
83 void *thread_list; /* 50 List of threads */
84 void *debuggee_CB; /* 54 Debuggee context block */
85 void *local_heap_free; /* 58 Head of local heap free list */
86 DWORD unknown4; /* 5c Unknown */
87 CRITICAL_SECTION crit_section; /* 60 Critical section */
88 DWORD unknown5[3]; /* 78 Unknown */
89 void *console; /* 84 Console */
90 DWORD tls_bits[2]; /* 88 TLS in-use bits */
91 DWORD process_dword; /* 90 Unknown */
92 struct _PDB *group; /* 94 Process group */
93 void *exe_modref; /* 98 MODREF for the process EXE */
94 void *top_filter; /* 9c Top exception filter */
95 DWORD priority; /* a0 Priority level */
96 HANDLE heap_list; /* a4 Head of process heap list */
97 void *heap_handles; /* a8 Head of heap handles list */
98 DWORD unknown6; /* ac Unknown */
99 void *console_provider; /* b0 Console provider (??) */
100 WORD env_selector; /* b4 Selector to process environment */
101 WORD error_mode; /* b6 Error mode */
102 HANDLE load_done_evt; /* b8 Event for process loading done */
103 void *UTState; /* bc Head of Univeral Thunk list */
104 DWORD unknown8; /* c0 Unknown (NT) */
105 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
106 } PDB;
108 PDB current_process;
110 static RTL_USER_PROCESS_PARAMETERS process_pmts;
111 static PEB_LDR_DATA process_ldr;
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 unsigned int server_startticks;
118 int main_create_flags = 0;
120 /* dlls/ntdll/env.c */
121 extern BOOL init_user_process_pmts( size_t, char*, size_t );
122 extern BOOL build_command_line( char **argv );
124 extern void RELAY_InitDebugLists(void);
125 extern void SHELL_LoadRegistry(void);
126 extern void VERSION_Init( const char *appname );
128 /***********************************************************************
129 * get_basename
131 inline static const char *get_basename( const char *name )
133 char *p;
135 if ((p = strrchr( name, '/' ))) name = p + 1;
136 if ((p = strrchr( name, '\\' ))) name = p + 1;
137 return name;
141 /***********************************************************************
142 * open_builtin_exe_file
144 * Open an exe file for a builtin exe.
146 static void *open_builtin_exe_file( const char *name, char *error, int error_size,
147 int test_only, int *file_exists )
149 char exename[MAX_PATH], *p;
150 const char *basename = get_basename(name);
152 if (strlen(basename) >= sizeof(exename)) return NULL;
153 strcpy( exename, basename );
154 for (p = exename; *p; p++) *p = FILE_tolower(*p);
155 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
159 /***********************************************************************
160 * open_exe_file
162 * Open a specific exe file, taking load order into account.
163 * Returns the file handle or 0 for a builtin exe.
165 static HANDLE open_exe_file( const char *name )
167 enum loadorder_type loadorder[LOADORDER_NTYPES];
168 char buffer[MAX_PATH];
169 HANDLE handle;
170 int i, file_exists;
172 TRACE("looking for %s\n", debugstr_a(name) );
174 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
175 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
177 /* file doesn't exist, check for builtin */
178 if (!FILE_contains_path( name )) goto error;
179 if (!MODULE_GetBuiltinPath( name, "", buffer, sizeof(buffer) )) goto error;
180 name = buffer;
183 MODULE_GetLoadOrder( loadorder, name, TRUE );
185 for(i = 0; i < LOADORDER_NTYPES; i++)
187 if (loadorder[i] == LOADORDER_INVALID) break;
188 switch(loadorder[i])
190 case LOADORDER_DLL:
191 TRACE( "Trying native exe %s\n", debugstr_a(name) );
192 if (handle != INVALID_HANDLE_VALUE) return handle;
193 break;
194 case LOADORDER_BI:
195 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
196 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
197 if (file_exists)
199 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
200 return 0;
202 default:
203 break;
206 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
208 error:
209 SetLastError( ERROR_FILE_NOT_FOUND );
210 return INVALID_HANDLE_VALUE;
214 /***********************************************************************
215 * find_exe_file
217 * Open an exe file, and return the full name and file handle.
218 * Returns FALSE if file could not be found.
219 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
220 * If file is a builtin exe, returns TRUE and sets handle to 0.
222 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
224 enum loadorder_type loadorder[LOADORDER_NTYPES];
225 int i, file_exists;
227 TRACE("looking for %s\n", debugstr_a(name) );
229 if (!SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) &&
230 !MODULE_GetBuiltinPath( name, ".exe", buffer, buflen ))
232 /* no builtin found, try native without extension in case it is a Unix app */
234 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
236 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
237 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
238 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
239 return TRUE;
241 return FALSE;
244 MODULE_GetLoadOrder( loadorder, buffer, TRUE );
246 for(i = 0; i < LOADORDER_NTYPES; i++)
248 if (loadorder[i] == LOADORDER_INVALID) break;
249 switch(loadorder[i])
251 case LOADORDER_DLL:
252 TRACE( "Trying native exe %s\n", debugstr_a(buffer) );
253 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
254 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
255 return TRUE;
256 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
257 break;
258 case LOADORDER_BI:
259 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
260 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
261 if (file_exists)
263 *handle = 0;
264 return TRUE;
266 break;
267 default:
268 break;
271 SetLastError( ERROR_FILE_NOT_FOUND );
272 return FALSE;
276 /***********************************************************************
277 * process_init
279 * Main process initialisation code
281 static BOOL process_init( char *argv[] )
283 BOOL ret;
284 size_t info_size = 0;
286 setbuf(stdout,NULL);
287 setbuf(stderr,NULL);
288 setlocale(LC_CTYPE,"");
290 /* store the program name */
291 argv0 = argv[0];
293 /* Fill the initial process structure */
294 current_process.threads = 1;
295 current_process.running_threads = 1;
296 current_process.ring0_threads = 1;
297 current_process.group = &current_process;
298 current_process.priority = 8; /* Normal */
299 current_process.ProcessParameters = &process_pmts;
300 current_process.LdrData = &process_ldr;
301 InitializeListHead(&process_ldr.InLoadOrderModuleList);
302 InitializeListHead(&process_ldr.InMemoryOrderModuleList);
303 InitializeListHead(&process_ldr.InInitializationOrderModuleList);
305 /* Setup the server connection */
306 CLIENT_InitServer();
308 /* Retrieve startup info from the server */
309 SERVER_START_REQ( init_process )
311 req->ldt_copy = &wine_ldt_copy;
312 if ((ret = !wine_server_call_err( req )))
314 main_exe_file = reply->exe_file;
315 main_create_flags = reply->create_flags;
316 info_size = reply->info_size;
317 server_startticks = reply->server_start;
318 process_pmts.hStdInput = reply->hstdin;
319 process_pmts.hStdOutput = reply->hstdout;
320 process_pmts.hStdError = reply->hstderr;
323 SERVER_END_REQ;
324 if (!ret) return FALSE;
326 /* Create the process heap */
327 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
329 if (info_size == 0)
331 /* This is wine specific: we have no parent (we're started from unix)
332 * so, create a simple console with bare handles to unix stdio
333 * input & output streams (aka simple console)
335 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &process_pmts.hStdInput );
336 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &process_pmts.hStdOutput );
337 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &process_pmts.hStdError );
339 else
341 /* convert value from server:
342 * + 0 => INVALID_HANDLE_VALUE
343 * + console handle need to be mapped
345 if (!process_pmts.hStdInput)
346 process_pmts.hStdInput = INVALID_HANDLE_VALUE;
347 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdInput)))
348 process_pmts.hStdInput = console_handle_map(process_pmts.hStdInput);
349 if (!process_pmts.hStdOutput)
350 process_pmts.hStdOutput = INVALID_HANDLE_VALUE;
351 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdOutput)))
352 process_pmts.hStdOutput = console_handle_map(process_pmts.hStdOutput);
353 if (!process_pmts.hStdError)
354 process_pmts.hStdError = INVALID_HANDLE_VALUE;
355 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdError)))
356 process_pmts.hStdError = console_handle_map(process_pmts.hStdError);
359 /* Copy the parent environment */
360 if (!init_user_process_pmts( info_size, main_exe_name, sizeof(main_exe_name) ))
361 return FALSE;
363 /* Parse command line arguments */
364 OPTIONS_ParseOptions( !info_size ? argv : NULL );
366 /* <hack: to be changed later on> */
367 process_pmts.CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
368 process_pmts.CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
369 process_pmts.CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, process_pmts.CurrentDirectoryName.MaximumLength);
370 process_pmts.CurrentDirectoryName.Buffer[0] = 'C';
371 process_pmts.CurrentDirectoryName.Buffer[1] = ':';
372 process_pmts.CurrentDirectoryName.Buffer[2] = '\\';
373 process_pmts.CurrentDirectoryName.Buffer[3] = '\0';
374 /* </hack: to be changed later on> */
376 /* initialise DOS drives */
377 if (!DRIVE_Init()) return FALSE;
379 /* initialise DOS directories */
380 if (!DIR_Init()) return FALSE;
382 /* registry initialisation */
383 SHELL_LoadRegistry();
385 /* global boot finished, the rest is process-local */
386 CLIENT_BootDone( TRACE_ON(server) );
387 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
389 return TRUE;
393 /***********************************************************************
394 * start_process
396 * Startup routine of a new process. Runs on the new process stack.
398 static void start_process( void *arg )
400 __TRY
402 LPTHREAD_START_ROUTINE entry;
403 HANDLE main_file = main_exe_file;
404 IMAGE_NT_HEADERS *nt;
405 PEB *peb = NtCurrentTeb()->Peb;
407 if (main_file)
409 UINT drive_type = GetDriveTypeA( main_exe_name );
410 /* don't keep the file handle open on removable media */
411 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
414 /* Retrieve entry point address */
415 nt = RtlImageNtHeader( peb->ImageBaseAddress );
416 entry = (LPTHREAD_START_ROUTINE)((char*)peb->ImageBaseAddress +
417 nt->OptionalHeader.AddressOfEntryPoint);
419 /* Install signal handlers; this cannot be done before, since we cannot
420 * send exceptions to the debugger before the create process event that
421 * is sent by REQ_INIT_PROCESS_DONE.
422 * We do need the handlers in place by the time the request is over, so
423 * we set them up here. If we segfault between here and the server call
424 * something is very wrong... */
425 if (!SIGNAL_Init()) goto error;
427 /* Signal the parent process to continue */
428 SERVER_START_REQ( init_process_done )
430 req->module = peb->ImageBaseAddress;
431 req->module_size = nt->OptionalHeader.SizeOfImage;
432 req->entry = entry;
433 /* API requires a double indirection */
434 req->name = &main_exe_name_ptr;
435 req->exe_file = main_file;
436 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
437 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
438 wine_server_call( req );
439 peb->BeingDebugged = reply->debugged;
441 SERVER_END_REQ;
443 /* create the main modref and load dependencies */
444 if (!PE_CreateModule( peb->ImageBaseAddress, main_exe_name, 0, 0, FALSE )) goto error;
446 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
448 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
450 if (TRACE_ON(relay))
451 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n",
452 GetCurrentThreadId(), main_exe_name, entry );
453 if (peb->BeingDebugged) DbgBreakPoint();
454 SetLastError(0); /* clear error code */
455 ExitThread( entry( NtCurrentTeb()->Peb ) );
457 error:
458 ExitProcess( GetLastError() );
460 __EXCEPT(UnhandledExceptionFilter)
462 TerminateThread( GetCurrentThread(), GetExceptionCode() );
464 __ENDTRY
468 /***********************************************************************
469 * __wine_process_init
471 * Wine initialisation: load and start the main exe file.
473 void __wine_process_init( int argc, char *argv[] )
475 char error[1024], *p;
476 DWORD stack_size = 0;
477 int file_exists;
479 /* Initialize everything */
480 if (!process_init( argv )) exit(1);
482 argv++; /* remove argv[0] (wine itself) */
484 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
485 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
487 if (!main_exe_name[0])
489 if (!argv[0]) OPTIONS_Usage();
491 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
493 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
494 ExitProcess(1);
496 if (main_exe_file == INVALID_HANDLE_VALUE)
498 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
499 ExitProcess(1);
503 if (!main_exe_file) /* no file handle -> Winelib app */
505 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
506 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
507 goto found;
508 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
509 ExitProcess(1);
511 VERSION_Init( main_exe_name );
513 switch( MODULE_GetBinaryType( main_exe_file ))
515 case BINARY_PE_EXE:
516 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
517 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
518 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
519 ExitProcess(1);
520 case BINARY_PE_DLL:
521 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
522 ExitProcess(1);
523 case BINARY_UNKNOWN:
524 /* check for .com extension */
525 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
527 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
528 ExitProcess(1);
530 /* fall through */
531 case BINARY_WIN16:
532 case BINARY_DOS:
533 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
534 CloseHandle( main_exe_file );
535 main_exe_file = 0;
536 argv--;
537 argv[0] = "winevdm.exe";
538 if (open_builtin_exe_file( "winevdm.exe", error, sizeof(error), 0, &file_exists ))
539 goto found;
540 MESSAGE( "%s: trying to run '%s', cannot open builtin library for 'winevdm.exe': %s\n",
541 argv0, main_exe_name, error );
542 ExitProcess(1);
543 case BINARY_OS216:
544 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
545 ExitProcess(1);
546 case BINARY_UNIX_EXE:
547 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
548 ExitProcess(1);
549 case BINARY_UNIX_LIB:
551 DOS_FULL_NAME full_name;
552 const char *name = main_exe_name;
553 UNICODE_STRING nameW;
555 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
556 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
557 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
558 RtlFreeUnicodeString(&nameW);
559 CloseHandle( main_exe_file );
560 main_exe_file = 0;
561 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
563 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
564 goto found;
566 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
567 ExitProcess(1);
571 found:
572 /* build command line */
573 if (!build_command_line( argv )) goto error;
575 /* create 32-bit module for main exe */
576 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
577 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
579 /* allocate main thread stack */
580 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
582 /* switch to the new stack */
583 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
585 error:
586 ExitProcess( GetLastError() );
590 /***********************************************************************
591 * build_argv
593 * Build an argv array from a command-line.
594 * The command-line is modified to insert nulls.
595 * 'reserved' is the number of args to reserve before the first one.
597 static char **build_argv( char *cmdline, int reserved )
599 int argc;
600 char** argv;
601 char *arg,*s,*d;
602 int in_quotes,bcount;
604 argc=reserved+1;
605 bcount=0;
606 in_quotes=0;
607 s=cmdline;
608 while (1) {
609 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
610 /* space */
611 argc++;
612 /* skip the remaining spaces */
613 while (*s==' ' || *s=='\t') {
614 s++;
616 if (*s=='\0')
617 break;
618 bcount=0;
619 continue;
620 } else if (*s=='\\') {
621 /* '\', count them */
622 bcount++;
623 } else if ((*s=='"') && ((bcount & 1)==0)) {
624 /* unescaped '"' */
625 in_quotes=!in_quotes;
626 bcount=0;
627 } else {
628 /* a regular character */
629 bcount=0;
631 s++;
633 argv=malloc(argc*sizeof(*argv));
634 if (!argv)
635 return NULL;
637 arg=d=s=cmdline;
638 bcount=0;
639 in_quotes=0;
640 argc=reserved;
641 while (*s) {
642 if ((*s==' ' || *s=='\t') && !in_quotes) {
643 /* Close the argument and copy it */
644 *d=0;
645 argv[argc++]=arg;
647 /* skip the remaining spaces */
648 do {
649 s++;
650 } while (*s==' ' || *s=='\t');
652 /* Start with a new argument */
653 arg=d=s;
654 bcount=0;
655 } else if (*s=='\\') {
656 /* '\\' */
657 *d++=*s++;
658 bcount++;
659 } else if (*s=='"') {
660 /* '"' */
661 if ((bcount & 1)==0) {
662 /* Preceeded by an even number of '\', this is half that
663 * number of '\', plus a '"' which we discard.
665 d-=bcount/2;
666 s++;
667 in_quotes=!in_quotes;
668 } else {
669 /* Preceeded by an odd number of '\', this is half that
670 * number of '\' followed by a '"'
672 d=d-bcount/2-1;
673 *d++='"';
674 s++;
676 bcount=0;
677 } else {
678 /* a regular character */
679 *d++=*s++;
680 bcount=0;
683 if (*arg) {
684 *d='\0';
685 argv[argc++]=arg;
687 argv[argc]=NULL;
689 return argv;
693 /***********************************************************************
694 * build_envp
696 * Build the environment of a new child process.
698 static char **build_envp( const char *env, const char *extra_env )
700 const char *p;
701 char **envp;
702 int count = 0;
704 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
705 for (p = env; *p; count++) p += strlen(p) + 1;
706 count += 3;
708 if ((envp = malloc( count * sizeof(*envp) )))
710 extern char **environ;
711 char **envptr = envp;
712 char **unixptr = environ;
713 /* first the extra strings */
714 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
715 /* then put PATH, HOME and WINEPREFIX from the unix env */
716 for (unixptr = environ; unixptr && *unixptr; unixptr++)
717 if (!memcmp( *unixptr, "PATH=", 5 ) ||
718 !memcmp( *unixptr, "HOME=", 5 ) ||
719 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
720 /* now put the Windows environment strings */
721 for (p = env; *p; p += strlen(p) + 1)
723 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
725 char *winepath = malloc( strlen(p) + 5 );
726 strcpy( winepath, "WINE" );
727 strcpy( winepath + 4, p );
728 *envptr++ = winepath;
730 else if (memcmp( p, "HOME=", 5 ) &&
731 memcmp( p, "WINEPATH=", 9 ) &&
732 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
734 *envptr = 0;
736 return envp;
740 /***********************************************************************
741 * exec_wine_binary
743 * Locate the Wine binary to exec for a new Win32 process.
745 static void exec_wine_binary( char **argv, char **envp )
747 const char *path, *pos, *ptr;
749 /* first, try for a WINELOADER environment variable */
750 argv[0] = getenv("WINELOADER");
751 if (argv[0])
752 execve( argv[0], argv, envp );
754 /* next, try bin directory */
755 argv[0] = BINDIR "/wine";
756 execve( argv[0], argv, envp );
758 /* now try the path of argv0 of the current binary */
759 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
760 if ((ptr = strrchr( full_argv0, '/' )))
762 memcpy( argv[0], full_argv0, ptr - full_argv0 );
763 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
764 execve( argv[0], argv, envp );
766 free( argv[0] );
768 /* now search in the Unix path */
769 if ((path = getenv( "PATH" )))
771 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
772 pos = path;
773 for (;;)
775 while (*pos == ':') pos++;
776 if (!*pos) break;
777 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
778 memcpy( argv[0], pos, ptr - pos );
779 strcpy( argv[0] + (ptr - pos), "/wine" );
780 execve( argv[0], argv, envp );
781 pos = ptr;
784 free( argv[0] );
788 /***********************************************************************
789 * fork_and_exec
791 * Fork and exec a new Unix binary, checking for errors.
793 static int fork_and_exec( const char *filename, char *cmdline,
794 const char *env, const char *newdir )
796 int fd[2];
797 int pid, err;
799 if (!env) env = GetEnvironmentStringsA();
801 if (pipe(fd) == -1)
803 FILE_SetDosError();
804 return -1;
806 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
807 if (!(pid = fork())) /* child */
809 char **argv = build_argv( cmdline, 0 );
810 char **envp = build_envp( env, NULL );
811 close( fd[0] );
813 /* Reset signals that we previously set to SIG_IGN */
814 signal( SIGPIPE, SIG_DFL );
815 signal( SIGCHLD, SIG_DFL );
817 if (newdir) chdir(newdir);
819 if (argv && envp) execve( filename, argv, envp );
820 err = errno;
821 write( fd[1], &err, sizeof(err) );
822 _exit(1);
824 close( fd[1] );
825 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
827 errno = err;
828 pid = -1;
830 if (pid == -1) FILE_SetDosError();
831 close( fd[0] );
832 return pid;
836 /***********************************************************************
837 * create_process
839 * Create a new process. If hFile is a valid handle we have an exe
840 * file, otherwise it is a Winelib app.
842 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
843 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
844 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
845 LPPROCESS_INFORMATION info, LPCSTR unixdir )
847 BOOL ret, success = FALSE;
848 HANDLE process_info;
849 startup_info_t startup_info;
850 char *extra_env = NULL;
851 int startfd[2];
852 int execfd[2];
853 pid_t pid;
854 int err;
855 char dummy = 0;
857 if (!env)
859 env = GetEnvironmentStringsA();
860 extra_env = DRIVE_BuildEnv();
863 /* create the synchronization pipes */
865 if (pipe( startfd ) == -1)
867 FILE_SetDosError();
868 return FALSE;
870 if (pipe( execfd ) == -1)
872 close( startfd[0] );
873 close( startfd[1] );
874 FILE_SetDosError();
875 return FALSE;
877 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
879 /* create the child process */
881 if (!(pid = fork())) /* child */
883 char **argv = build_argv( cmd_line, 1 );
884 char **envp = build_envp( env, extra_env );
886 close( startfd[1] );
887 close( execfd[0] );
889 /* wait for parent to tell us to start */
890 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
892 close( startfd[0] );
893 /* Reset signals that we previously set to SIG_IGN */
894 signal( SIGPIPE, SIG_DFL );
895 signal( SIGCHLD, SIG_DFL );
897 if (unixdir) chdir(unixdir);
899 if (argv && envp) exec_wine_binary( argv, envp );
901 err = errno;
902 write( execfd[1], &err, sizeof(err) );
903 _exit(1);
906 /* this is the parent */
908 close( startfd[0] );
909 close( execfd[1] );
910 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
911 if (pid == -1)
913 close( startfd[1] );
914 close( execfd[0] );
915 FILE_SetDosError();
916 return FALSE;
919 /* fill the startup info structure */
921 startup_info.size = sizeof(startup_info);
922 /* startup_info.filename_len is set below */
923 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
924 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
925 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
926 startup_info.x = startup->dwX;
927 startup_info.y = startup->dwY;
928 startup_info.cx = startup->dwXSize;
929 startup_info.cy = startup->dwYSize;
930 startup_info.x_chars = startup->dwXCountChars;
931 startup_info.y_chars = startup->dwYCountChars;
932 startup_info.attribute = startup->dwFillAttribute;
933 startup_info.cmd_show = startup->wShowWindow;
934 startup_info.flags = startup->dwFlags;
936 /* create the process on the server side */
938 SERVER_START_REQ( new_process )
940 char buf[MAX_PATH];
941 LPCSTR nameptr;
943 req->inherit_all = inherit;
944 req->create_flags = flags;
945 req->unix_pid = pid;
946 req->exe_file = hFile;
947 if (startup->dwFlags & STARTF_USESTDHANDLES)
949 req->hstdin = startup->hStdInput;
950 req->hstdout = startup->hStdOutput;
951 req->hstderr = startup->hStdError;
953 else
955 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
956 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
957 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
960 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
962 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
963 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
964 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
965 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
967 else
969 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
970 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
971 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
974 if (GetLongPathNameA( filename, buf, MAX_PATH ))
975 nameptr = buf;
976 else
977 nameptr = filename;
979 startup_info.filename_len = strlen(nameptr);
980 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
981 wine_server_add_data( req, nameptr, startup_info.filename_len );
982 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
983 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
984 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
986 ret = !wine_server_call_err( req );
987 process_info = reply->info;
989 SERVER_END_REQ;
991 if (!ret)
993 close( startfd[1] );
994 close( execfd[0] );
995 return FALSE;
998 /* tell child to start and wait for it to exec */
1000 write( startfd[1], &dummy, 1 );
1001 close( startfd[1] );
1003 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1005 errno = err;
1006 FILE_SetDosError();
1007 close( execfd[0] );
1008 CloseHandle( process_info );
1009 return FALSE;
1012 /* wait for the new process info to be ready */
1014 WaitForSingleObject( process_info, INFINITE );
1015 SERVER_START_REQ( get_new_process_info )
1017 req->info = process_info;
1018 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1019 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1020 if ((ret = !wine_server_call_err( req )))
1022 info->dwProcessId = (DWORD)reply->pid;
1023 info->dwThreadId = (DWORD)reply->tid;
1024 info->hProcess = reply->phandle;
1025 info->hThread = reply->thandle;
1026 success = reply->success;
1029 SERVER_END_REQ;
1031 if (ret && !success) /* new process failed to start */
1033 DWORD exitcode;
1034 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1035 CloseHandle( info->hThread );
1036 CloseHandle( info->hProcess );
1037 ret = FALSE;
1039 CloseHandle( process_info );
1040 return ret;
1044 /***********************************************************************
1045 * create_vdm_process
1047 * Create a new VDM process for a 16-bit or DOS application.
1049 static BOOL create_vdm_process( LPCSTR filename, LPSTR cmd_line, LPCSTR env,
1050 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1051 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
1052 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1054 BOOL ret;
1055 LPSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + strlen(cmd_line) + 30 );
1057 if (!new_cmd_line)
1059 SetLastError( ERROR_OUTOFMEMORY );
1060 return FALSE;
1062 sprintf( new_cmd_line, "winevdm.exe --app-name \"%s\" %s", filename, cmd_line );
1063 ret = create_process( 0, "winevdm.exe", new_cmd_line, env, psa, tsa, inherit,
1064 flags, startup, info, unixdir );
1065 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1066 return ret;
1070 /*************************************************************************
1071 * get_file_name
1073 * Helper for CreateProcess: retrieve the file name to load from the
1074 * app name and command line. Store the file name in buffer, and
1075 * return a possibly modified command line.
1076 * Also returns a handle to the opened file if it's a Windows binary.
1078 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1079 int buflen, HANDLE *handle )
1081 char *name, *pos, *ret = NULL;
1082 const char *p;
1084 /* if we have an app name, everything is easy */
1086 if (appname)
1088 /* use the unmodified app name as file name */
1089 lstrcpynA( buffer, appname, buflen );
1090 *handle = open_exe_file( buffer );
1091 if (!(ret = cmdline) || !cmdline[0])
1093 /* no command-line, create one */
1094 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1095 sprintf( ret, "\"%s\"", appname );
1097 return ret;
1100 if (!cmdline)
1102 SetLastError( ERROR_INVALID_PARAMETER );
1103 return NULL;
1106 /* first check for a quoted file name */
1108 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1110 int len = p - cmdline - 1;
1111 /* extract the quoted portion as file name */
1112 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1113 memcpy( name, cmdline + 1, len );
1114 name[len] = 0;
1116 if (find_exe_file( name, buffer, buflen, handle ))
1117 ret = cmdline; /* no change necessary */
1118 goto done;
1121 /* now try the command-line word by word */
1123 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1124 pos = name;
1125 p = cmdline;
1127 while (*p)
1129 do *pos++ = *p++; while (*p && *p != ' ');
1130 *pos = 0;
1131 if (find_exe_file( name, buffer, buflen, handle ))
1133 ret = cmdline;
1134 break;
1138 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1140 /* now build a new command-line with quotes */
1142 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1143 sprintf( ret, "\"%s\"%s", name, p );
1145 done:
1146 HeapFree( GetProcessHeap(), 0, name );
1147 return ret;
1151 /**********************************************************************
1152 * CreateProcessA (KERNEL32.@)
1154 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1155 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1156 DWORD flags, LPVOID env, LPCSTR cur_dir,
1157 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1159 BOOL retv = FALSE;
1160 HANDLE hFile = 0;
1161 const char *unixdir = NULL;
1162 DOS_FULL_NAME full_dir;
1163 char name[MAX_PATH];
1164 LPSTR tidy_cmdline;
1165 char *p;
1167 /* Process the AppName and/or CmdLine to get module name and path */
1169 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1171 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1172 return FALSE;
1173 if (hFile == INVALID_HANDLE_VALUE) goto done;
1175 /* Warn if unsupported features are used */
1177 if (flags & NORMAL_PRIORITY_CLASS)
1178 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1179 if (flags & IDLE_PRIORITY_CLASS)
1180 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1181 if (flags & HIGH_PRIORITY_CLASS)
1182 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1183 if (flags & REALTIME_PRIORITY_CLASS)
1184 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1185 if (flags & CREATE_NEW_PROCESS_GROUP)
1186 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1187 if (flags & CREATE_UNICODE_ENVIRONMENT)
1188 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1189 if (flags & CREATE_SEPARATE_WOW_VDM)
1190 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1191 if (flags & CREATE_SHARED_WOW_VDM)
1192 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1193 if (flags & CREATE_DEFAULT_ERROR_MODE)
1194 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1195 if (flags & CREATE_NO_WINDOW)
1196 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1197 if (flags & PROFILE_USER)
1198 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1199 if (flags & PROFILE_KERNEL)
1200 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1201 if (flags & PROFILE_SERVER)
1202 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1203 if (startup_info->lpDesktop)
1204 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1205 name, debugstr_a(startup_info->lpDesktop));
1206 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1207 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1208 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1209 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1210 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1211 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1212 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1213 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1215 if (cur_dir)
1217 UNICODE_STRING cur_dirW;
1218 RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1219 if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1220 unixdir = full_dir.long_name;
1221 RtlFreeUnicodeString(&cur_dirW);
1223 else
1225 WCHAR buf[MAX_PATH];
1226 if (GetCurrentDirectoryW(MAX_PATH, buf))
1228 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1232 info->hThread = info->hProcess = 0;
1233 info->dwProcessId = info->dwThreadId = 0;
1235 /* Determine executable type */
1237 if (!hFile) /* builtin exe */
1239 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1240 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1241 inherit, flags, startup_info, info, unixdir );
1242 goto done;
1245 switch( MODULE_GetBinaryType( hFile ))
1247 case BINARY_PE_EXE:
1248 TRACE( "starting %s as Win32 binary\n", debugstr_a(name) );
1249 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1250 inherit, flags, startup_info, info, unixdir );
1251 break;
1252 case BINARY_WIN16:
1253 case BINARY_DOS:
1254 TRACE( "starting %s as Win16/DOS binary\n", debugstr_a(name) );
1255 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1256 inherit, flags, startup_info, info, unixdir );
1257 break;
1258 case BINARY_OS216:
1259 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1260 SetLastError( ERROR_BAD_EXE_FORMAT );
1261 break;
1262 case BINARY_PE_DLL:
1263 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1264 SetLastError( ERROR_BAD_EXE_FORMAT );
1265 break;
1266 case BINARY_UNIX_LIB:
1267 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1268 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1269 inherit, flags, startup_info, info, unixdir );
1270 break;
1271 case BINARY_UNKNOWN:
1272 /* check for .com or .bat extension */
1273 if ((p = strrchr( name, '.' )))
1275 if (!FILE_strcasecmp( p, ".com" ))
1277 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1278 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1279 inherit, flags, startup_info, info, unixdir );
1280 break;
1282 if (!FILE_strcasecmp( p, ".bat" ))
1284 char comspec[MAX_PATH];
1285 if (GetEnvironmentVariableA("COMSPEC", comspec, sizeof(comspec)))
1287 char *newcmdline;
1288 if ((newcmdline = HeapAlloc( GetProcessHeap(), 0,
1289 strlen(comspec) + 4 + strlen(tidy_cmdline) + 1)))
1291 sprintf( newcmdline, "%s /c %s", comspec, tidy_cmdline);
1292 TRACE( "starting %s as batch binary: %s\n",
1293 debugstr_a(name), debugstr_a(newcmdline) );
1294 retv = CreateProcessA( comspec, newcmdline, process_attr, thread_attr,
1295 inherit, flags, env, cur_dir, startup_info, info );
1296 HeapFree( GetProcessHeap(), 0, newcmdline );
1297 break;
1302 /* fall through */
1303 case BINARY_UNIX_EXE:
1305 /* unknown file, try as unix executable */
1306 UNICODE_STRING nameW;
1307 DOS_FULL_NAME full_name;
1308 const char *unixfilename = name;
1310 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1312 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1313 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1314 RtlFreeUnicodeString(&nameW);
1315 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1317 break;
1319 CloseHandle( hFile );
1321 done:
1322 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1323 return retv;
1327 /**********************************************************************
1328 * CreateProcessW (KERNEL32.@)
1329 * NOTES
1330 * lpReserved is not converted
1332 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1333 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1334 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1335 LPPROCESS_INFORMATION info )
1337 BOOL ret;
1338 STARTUPINFOA StartupInfoA;
1340 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1341 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1342 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1344 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1345 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1346 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1348 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1350 if (startup_info->lpReserved)
1351 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1352 debugstr_w(startup_info->lpReserved));
1354 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1355 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1357 HeapFree( GetProcessHeap(), 0, cur_dirA );
1358 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1359 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1360 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1362 return ret;
1366 /***********************************************************************
1367 * ExitProcess (KERNEL32.@)
1369 void WINAPI ExitProcess( DWORD status )
1371 LdrShutdownProcess();
1372 SERVER_START_REQ( terminate_process )
1374 /* send the exit code to the server */
1375 req->handle = GetCurrentProcess();
1376 req->exit_code = status;
1377 wine_server_call( req );
1379 SERVER_END_REQ;
1380 exit( status );
1383 /******************************************************************************
1384 * TerminateProcess (KERNEL32.@)
1386 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1388 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1389 if (status) SetLastError( RtlNtStatusToDosError(status) );
1390 return !status;
1394 /***********************************************************************
1395 * GetExitCodeProcess [KERNEL32.@]
1397 * Gets termination status of specified process
1399 * RETURNS
1400 * Success: TRUE
1401 * Failure: FALSE
1403 BOOL WINAPI GetExitCodeProcess(
1404 HANDLE hProcess, /* [in] handle to the process */
1405 LPDWORD lpExitCode) /* [out] address to receive termination status */
1407 BOOL ret;
1408 SERVER_START_REQ( get_process_info )
1410 req->handle = hProcess;
1411 ret = !wine_server_call_err( req );
1412 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1414 SERVER_END_REQ;
1415 return ret;
1419 /***********************************************************************
1420 * SetErrorMode (KERNEL32.@)
1422 UINT WINAPI SetErrorMode( UINT mode )
1424 UINT old = current_process.error_mode;
1425 current_process.error_mode = mode;
1426 return old;
1430 /***********************************************************************
1431 * GetTickCount (KERNEL32.@)
1433 * Returns the number of milliseconds, modulo 2^32, since the start
1434 * of the wineserver.
1436 DWORD WINAPI GetTickCount(void)
1438 struct timeval t;
1439 gettimeofday( &t, NULL );
1440 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1444 /**********************************************************************
1445 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1447 * Allocates a thread local storage index
1449 * RETURNS
1450 * Success: TLS Index
1451 * Failure: 0xFFFFFFFF
1453 DWORD WINAPI TlsAlloc( void )
1455 DWORD i, mask, ret = 0;
1456 DWORD *bits = current_process.tls_bits;
1457 RtlAcquirePebLock();
1458 if (*bits == 0xffffffff)
1460 bits++;
1461 ret = 32;
1462 if (*bits == 0xffffffff)
1464 RtlReleasePebLock();
1465 SetLastError( ERROR_NO_MORE_ITEMS );
1466 return 0xffffffff;
1469 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1470 *bits |= mask;
1471 RtlReleasePebLock();
1472 NtCurrentTeb()->TlsSlots[ret+i] = 0; /* clear the value */
1473 return ret + i;
1477 /**********************************************************************
1478 * TlsFree [KERNEL32.@] Releases a TLS index.
1480 * Releases a thread local storage index, making it available for reuse
1482 * RETURNS
1483 * Success: TRUE
1484 * Failure: FALSE
1486 BOOL WINAPI TlsFree(
1487 DWORD index) /* [in] TLS Index to free */
1489 DWORD mask = (1 << (index & 31));
1490 DWORD *bits = current_process.tls_bits;
1491 if (index >= 64)
1493 SetLastError( ERROR_INVALID_PARAMETER );
1494 return FALSE;
1496 if (index >= 32) bits++;
1497 RtlAcquirePebLock();
1498 if (!(*bits & mask)) /* already free? */
1500 RtlReleasePebLock();
1501 SetLastError( ERROR_INVALID_PARAMETER );
1502 return FALSE;
1504 *bits &= ~mask;
1505 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1506 RtlReleasePebLock();
1507 return TRUE;
1511 /**********************************************************************
1512 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1514 * RETURNS
1515 * Success: Value stored in calling thread's TLS slot for index
1516 * Failure: 0 and GetLastError returns NO_ERROR
1518 LPVOID WINAPI TlsGetValue(
1519 DWORD index) /* [in] TLS index to retrieve value for */
1521 if (index >= 64)
1523 SetLastError( ERROR_INVALID_PARAMETER );
1524 return NULL;
1526 SetLastError( ERROR_SUCCESS );
1527 return NtCurrentTeb()->TlsSlots[index];
1531 /**********************************************************************
1532 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1534 * RETURNS
1535 * Success: TRUE
1536 * Failure: FALSE
1538 BOOL WINAPI TlsSetValue(
1539 DWORD index, /* [in] TLS index to set value for */
1540 LPVOID value) /* [in] Value to be stored */
1542 if (index >= 64)
1544 SetLastError( ERROR_INVALID_PARAMETER );
1545 return FALSE;
1547 NtCurrentTeb()->TlsSlots[index] = value;
1548 return TRUE;