Fixed regression in process creation (std handle inheritance).
[wine/dcerpc.git] / scheduler / process.c
blob9b8d1abcf718246a92a9e975c7696c2e3fb6f6f0
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 /* scheduler/pthread.c */
121 extern void PTHREAD_init_done(void);
123 /* dlls/ntdll/env.c */
124 extern BOOL init_user_process_pmts( size_t, char*, size_t );
125 extern BOOL build_command_line( char **argv );
127 extern void RELAY_InitDebugLists(void);
128 extern void SHELL_LoadRegistry(void);
129 extern void VERSION_Init( const char *appname );
131 /***********************************************************************
132 * get_basename
134 inline static const char *get_basename( const char *name )
136 char *p;
138 if ((p = strrchr( name, '/' ))) name = p + 1;
139 if ((p = strrchr( name, '\\' ))) name = p + 1;
140 return name;
144 /***********************************************************************
145 * open_builtin_exe_file
147 * Open an exe file for a builtin exe.
149 static void *open_builtin_exe_file( const char *name, char *error, int error_size,
150 int test_only, int *file_exists )
152 char exename[MAX_PATH], *p;
153 const char *basename = get_basename(name);
155 if (strlen(basename) >= sizeof(exename)) return NULL;
156 strcpy( exename, basename );
157 for (p = exename; *p; p++) *p = FILE_tolower(*p);
158 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
162 /***********************************************************************
163 * open_exe_file
165 * Open a specific exe file, taking load order into account.
166 * Returns the file handle or 0 for a builtin exe.
168 static HANDLE open_exe_file( const char *name )
170 enum loadorder_type loadorder[LOADORDER_NTYPES];
171 char buffer[MAX_PATH];
172 HANDLE handle;
173 int i, file_exists;
175 TRACE("looking for %s\n", debugstr_a(name) );
177 if ((handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
178 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
180 /* file doesn't exist, check for builtin */
181 if (!FILE_contains_path( name )) goto error;
182 if (!MODULE_GetBuiltinPath( name, "", buffer, sizeof(buffer) )) goto error;
183 name = buffer;
186 MODULE_GetLoadOrder( loadorder, name, TRUE );
188 for(i = 0; i < LOADORDER_NTYPES; i++)
190 if (loadorder[i] == LOADORDER_INVALID) break;
191 switch(loadorder[i])
193 case LOADORDER_DLL:
194 TRACE( "Trying native exe %s\n", debugstr_a(name) );
195 if (handle != INVALID_HANDLE_VALUE) return handle;
196 break;
197 case LOADORDER_BI:
198 TRACE( "Trying built-in exe %s\n", debugstr_a(name) );
199 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
200 if (file_exists)
202 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
203 return 0;
205 default:
206 break;
209 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
211 error:
212 SetLastError( ERROR_FILE_NOT_FOUND );
213 return INVALID_HANDLE_VALUE;
217 /***********************************************************************
218 * find_exe_file
220 * Open an exe file, and return the full name and file handle.
221 * Returns FALSE if file could not be found.
222 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
223 * If file is a builtin exe, returns TRUE and sets handle to 0.
225 static BOOL find_exe_file( const char *name, char *buffer, int buflen, HANDLE *handle )
227 enum loadorder_type loadorder[LOADORDER_NTYPES];
228 int i, file_exists;
230 TRACE("looking for %s\n", debugstr_a(name) );
232 if (!SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) &&
233 !MODULE_GetBuiltinPath( name, ".exe", buffer, buflen ))
235 /* no builtin found, try native without extension in case it is a Unix app */
237 if (SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
239 TRACE( "Trying native/Unix binary %s\n", debugstr_a(buffer) );
240 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
241 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
242 return TRUE;
244 return FALSE;
247 MODULE_GetLoadOrder( loadorder, buffer, TRUE );
249 for(i = 0; i < LOADORDER_NTYPES; i++)
251 if (loadorder[i] == LOADORDER_INVALID) break;
252 switch(loadorder[i])
254 case LOADORDER_DLL:
255 TRACE( "Trying native exe %s\n", debugstr_a(buffer) );
256 if ((*handle = CreateFileA( buffer, GENERIC_READ, FILE_SHARE_READ,
257 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
258 return TRUE;
259 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
260 break;
261 case LOADORDER_BI:
262 TRACE( "Trying built-in exe %s\n", debugstr_a(buffer) );
263 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
264 if (file_exists)
266 *handle = 0;
267 return TRUE;
269 break;
270 default:
271 break;
274 SetLastError( ERROR_FILE_NOT_FOUND );
275 return FALSE;
279 /***********************************************************************
280 * process_init
282 * Main process initialisation code
284 static BOOL process_init( char *argv[] )
286 BOOL ret;
287 size_t info_size = 0;
289 setbuf(stdout,NULL);
290 setbuf(stderr,NULL);
291 setlocale(LC_CTYPE,"");
293 /* store the program name */
294 argv0 = argv[0];
296 /* Fill the initial process structure */
297 current_process.threads = 1;
298 current_process.running_threads = 1;
299 current_process.ring0_threads = 1;
300 current_process.group = &current_process;
301 current_process.priority = 8; /* Normal */
302 current_process.ProcessParameters = &process_pmts;
303 current_process.LdrData = &process_ldr;
304 InitializeListHead(&process_ldr.InLoadOrderModuleList);
305 InitializeListHead(&process_ldr.InMemoryOrderModuleList);
306 InitializeListHead(&process_ldr.InInitializationOrderModuleList);
308 /* Setup the server connection */
309 CLIENT_InitServer();
311 /* Retrieve startup info from the server */
312 SERVER_START_REQ( init_process )
314 req->ldt_copy = &wine_ldt_copy;
315 if ((ret = !wine_server_call_err( req )))
317 main_exe_file = reply->exe_file;
318 main_create_flags = reply->create_flags;
319 info_size = reply->info_size;
320 server_startticks = reply->server_start;
321 process_pmts.hStdInput = reply->hstdin;
322 process_pmts.hStdOutput = reply->hstdout;
323 process_pmts.hStdError = reply->hstderr;
326 SERVER_END_REQ;
327 if (!ret) return FALSE;
329 /* Create the process heap */
330 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
332 if (info_size == 0)
334 /* This is wine specific: we have no parent (we're started from unix)
335 * so, create a simple console with bare handles to unix stdio
336 * input & output streams (aka simple console)
338 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &process_pmts.hStdInput );
339 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &process_pmts.hStdOutput );
340 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &process_pmts.hStdError );
342 else
344 /* convert value from server:
345 * + 0 => INVALID_HANDLE_VALUE
346 * + console handle need to be mapped
348 if (!process_pmts.hStdInput)
349 process_pmts.hStdInput = INVALID_HANDLE_VALUE;
350 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdInput)))
351 process_pmts.hStdInput = console_handle_map(process_pmts.hStdInput);
352 if (!process_pmts.hStdOutput)
353 process_pmts.hStdOutput = INVALID_HANDLE_VALUE;
354 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdOutput)))
355 process_pmts.hStdOutput = console_handle_map(process_pmts.hStdOutput);
356 if (!process_pmts.hStdError)
357 process_pmts.hStdError = INVALID_HANDLE_VALUE;
358 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdError)))
359 process_pmts.hStdError = console_handle_map(process_pmts.hStdError);
362 /* Now we can use the pthreads routines */
363 PTHREAD_init_done();
365 /* Copy the parent environment */
366 if (!init_user_process_pmts( info_size, main_exe_name, sizeof(main_exe_name) ))
367 return FALSE;
369 /* Parse command line arguments */
370 OPTIONS_ParseOptions( !info_size ? argv : NULL );
372 /* <hack: to be changed later on> */
373 process_pmts.CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
374 process_pmts.CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
375 process_pmts.CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, process_pmts.CurrentDirectoryName.MaximumLength);
376 process_pmts.CurrentDirectoryName.Buffer[0] = 'C';
377 process_pmts.CurrentDirectoryName.Buffer[1] = ':';
378 process_pmts.CurrentDirectoryName.Buffer[2] = '\\';
379 process_pmts.CurrentDirectoryName.Buffer[3] = '\0';
380 /* </hack: to be changed later on> */
382 /* initialise DOS drives */
383 if (!DRIVE_Init()) return FALSE;
385 /* initialise DOS directories */
386 if (!DIR_Init()) return FALSE;
388 /* registry initialisation */
389 SHELL_LoadRegistry();
391 /* global boot finished, the rest is process-local */
392 CLIENT_BootDone( TRACE_ON(server) );
393 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
395 return TRUE;
399 /***********************************************************************
400 * start_process
402 * Startup routine of a new process. Runs on the new process stack.
404 static void start_process( void *arg )
406 __TRY
408 LPTHREAD_START_ROUTINE entry;
409 HANDLE main_file = main_exe_file;
410 IMAGE_NT_HEADERS *nt;
411 PEB *peb = NtCurrentTeb()->Peb;
413 if (main_file)
415 UINT drive_type = GetDriveTypeA( main_exe_name );
416 /* don't keep the file handle open on removable media */
417 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
420 /* Retrieve entry point address */
421 nt = RtlImageNtHeader( peb->ImageBaseAddress );
422 entry = (LPTHREAD_START_ROUTINE)((char*)peb->ImageBaseAddress +
423 nt->OptionalHeader.AddressOfEntryPoint);
425 /* Install signal handlers; this cannot be done before, since we cannot
426 * send exceptions to the debugger before the create process event that
427 * is sent by REQ_INIT_PROCESS_DONE.
428 * We do need the handlers in place by the time the request is over, so
429 * we set them up here. If we segfault between here and the server call
430 * something is very wrong... */
431 if (!SIGNAL_Init()) goto error;
433 /* Signal the parent process to continue */
434 SERVER_START_REQ( init_process_done )
436 req->module = peb->ImageBaseAddress;
437 req->module_size = nt->OptionalHeader.SizeOfImage;
438 req->entry = entry;
439 /* API requires a double indirection */
440 req->name = &main_exe_name_ptr;
441 req->exe_file = main_file;
442 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
443 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
444 wine_server_call( req );
445 peb->BeingDebugged = reply->debugged;
447 SERVER_END_REQ;
449 /* create the main modref and load dependencies */
450 if (!PE_CreateModule( peb->ImageBaseAddress, main_exe_name, 0, 0, FALSE )) goto error;
452 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
454 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
456 if (TRACE_ON(relay))
457 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n",
458 GetCurrentThreadId(), main_exe_name, entry );
459 if (peb->BeingDebugged) DbgBreakPoint();
460 SetLastError(0); /* clear error code */
461 ExitThread( entry( NtCurrentTeb()->Peb ) );
463 error:
464 ExitProcess( GetLastError() );
466 __EXCEPT(UnhandledExceptionFilter)
468 TerminateThread( GetCurrentThread(), GetExceptionCode() );
470 __ENDTRY
474 /***********************************************************************
475 * __wine_process_init
477 * Wine initialisation: load and start the main exe file.
479 void __wine_process_init( int argc, char *argv[] )
481 char error[1024], *p;
482 DWORD stack_size = 0;
483 int file_exists;
485 /* Initialize everything */
486 if (!process_init( argv )) exit(1);
488 argv++; /* remove argv[0] (wine itself) */
490 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
491 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
493 if (!main_exe_name[0])
495 if (!argv[0]) OPTIONS_Usage();
497 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
499 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
500 ExitProcess(1);
502 if (main_exe_file == INVALID_HANDLE_VALUE)
504 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
505 ExitProcess(1);
509 if (!main_exe_file) /* no file handle -> Winelib app */
511 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
512 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
513 goto found;
514 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
515 ExitProcess(1);
517 VERSION_Init( main_exe_name );
519 switch( MODULE_GetBinaryType( main_exe_file ))
521 case BINARY_PE_EXE:
522 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
523 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
524 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
525 ExitProcess(1);
526 case BINARY_PE_DLL:
527 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
528 ExitProcess(1);
529 case BINARY_UNKNOWN:
530 /* check for .com extension */
531 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
533 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
534 ExitProcess(1);
536 /* fall through */
537 case BINARY_WIN16:
538 case BINARY_DOS:
539 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
540 CloseHandle( main_exe_file );
541 main_exe_file = 0;
542 argv--;
543 argv[0] = "winevdm.exe";
544 if (open_builtin_exe_file( "winevdm.exe", error, sizeof(error), 0, &file_exists ))
545 goto found;
546 MESSAGE( "%s: trying to run '%s', cannot open builtin library for 'winevdm.exe': %s\n",
547 argv0, main_exe_name, error );
548 ExitProcess(1);
549 case BINARY_OS216:
550 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
551 ExitProcess(1);
552 case BINARY_UNIX_EXE:
553 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
554 ExitProcess(1);
555 case BINARY_UNIX_LIB:
557 DOS_FULL_NAME full_name;
558 const char *name = main_exe_name;
559 UNICODE_STRING nameW;
561 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
562 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
563 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
564 RtlFreeUnicodeString(&nameW);
565 CloseHandle( main_exe_file );
566 main_exe_file = 0;
567 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
569 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
570 goto found;
572 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
573 ExitProcess(1);
577 found:
578 /* build command line */
579 if (!build_command_line( argv )) goto error;
581 /* create 32-bit module for main exe */
582 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
583 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
585 /* allocate main thread stack */
586 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
588 /* switch to the new stack */
589 SYSDEPS_SwitchToThreadStack( start_process, NULL );
591 error:
592 ExitProcess( GetLastError() );
596 /***********************************************************************
597 * build_argv
599 * Build an argv array from a command-line.
600 * The command-line is modified to insert nulls.
601 * 'reserved' is the number of args to reserve before the first one.
603 static char **build_argv( char *cmdline, int reserved )
605 int argc;
606 char** argv;
607 char *arg,*s,*d;
608 int in_quotes,bcount;
610 argc=reserved+1;
611 bcount=0;
612 in_quotes=0;
613 s=cmdline;
614 while (1) {
615 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
616 /* space */
617 argc++;
618 /* skip the remaining spaces */
619 while (*s==' ' || *s=='\t') {
620 s++;
622 if (*s=='\0')
623 break;
624 bcount=0;
625 continue;
626 } else if (*s=='\\') {
627 /* '\', count them */
628 bcount++;
629 } else if ((*s=='"') && ((bcount & 1)==0)) {
630 /* unescaped '"' */
631 in_quotes=!in_quotes;
632 bcount=0;
633 } else {
634 /* a regular character */
635 bcount=0;
637 s++;
639 argv=malloc(argc*sizeof(*argv));
640 if (!argv)
641 return NULL;
643 arg=d=s=cmdline;
644 bcount=0;
645 in_quotes=0;
646 argc=reserved;
647 while (*s) {
648 if ((*s==' ' || *s=='\t') && !in_quotes) {
649 /* Close the argument and copy it */
650 *d=0;
651 argv[argc++]=arg;
653 /* skip the remaining spaces */
654 do {
655 s++;
656 } while (*s==' ' || *s=='\t');
658 /* Start with a new argument */
659 arg=d=s;
660 bcount=0;
661 } else if (*s=='\\') {
662 /* '\\' */
663 *d++=*s++;
664 bcount++;
665 } else if (*s=='"') {
666 /* '"' */
667 if ((bcount & 1)==0) {
668 /* Preceeded by an even number of '\', this is half that
669 * number of '\', plus a '"' which we discard.
671 d-=bcount/2;
672 s++;
673 in_quotes=!in_quotes;
674 } else {
675 /* Preceeded by an odd number of '\', this is half that
676 * number of '\' followed by a '"'
678 d=d-bcount/2-1;
679 *d++='"';
680 s++;
682 bcount=0;
683 } else {
684 /* a regular character */
685 *d++=*s++;
686 bcount=0;
689 if (*arg) {
690 *d='\0';
691 argv[argc++]=arg;
693 argv[argc]=NULL;
695 return argv;
699 /***********************************************************************
700 * build_envp
702 * Build the environment of a new child process.
704 static char **build_envp( const char *env, const char *extra_env )
706 const char *p;
707 char **envp;
708 int count = 0;
710 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
711 for (p = env; *p; count++) p += strlen(p) + 1;
712 count += 3;
714 if ((envp = malloc( count * sizeof(*envp) )))
716 extern char **environ;
717 char **envptr = envp;
718 char **unixptr = environ;
719 /* first the extra strings */
720 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
721 /* then put PATH, HOME and WINEPREFIX from the unix env */
722 for (unixptr = environ; unixptr && *unixptr; unixptr++)
723 if (!memcmp( *unixptr, "PATH=", 5 ) ||
724 !memcmp( *unixptr, "HOME=", 5 ) ||
725 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
726 /* now put the Windows environment strings */
727 for (p = env; *p; p += strlen(p) + 1)
729 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
731 char *winepath = malloc( strlen(p) + 5 );
732 strcpy( winepath, "WINE" );
733 strcpy( winepath + 4, p );
734 *envptr++ = winepath;
736 else if (memcmp( p, "HOME=", 5 ) &&
737 memcmp( p, "WINEPATH=", 9 ) &&
738 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
740 *envptr = 0;
742 return envp;
746 /***********************************************************************
747 * exec_wine_binary
749 * Locate the Wine binary to exec for a new Win32 process.
751 static void exec_wine_binary( char **argv, char **envp )
753 const char *path, *pos, *ptr;
755 /* first, try for a WINELOADER environment variable */
756 argv[0] = getenv("WINELOADER");
757 if (argv[0])
758 execve( argv[0], argv, envp );
760 /* next, try bin directory */
761 argv[0] = BINDIR "/wine";
762 execve( argv[0], argv, envp );
764 /* now try the path of argv0 of the current binary */
765 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
766 if ((ptr = strrchr( full_argv0, '/' )))
768 memcpy( argv[0], full_argv0, ptr - full_argv0 );
769 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
770 execve( argv[0], argv, envp );
772 free( argv[0] );
774 /* now search in the Unix path */
775 if ((path = getenv( "PATH" )))
777 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
778 pos = path;
779 for (;;)
781 while (*pos == ':') pos++;
782 if (!*pos) break;
783 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
784 memcpy( argv[0], pos, ptr - pos );
785 strcpy( argv[0] + (ptr - pos), "/wine" );
786 execve( argv[0], argv, envp );
787 pos = ptr;
790 free( argv[0] );
794 /***********************************************************************
795 * fork_and_exec
797 * Fork and exec a new Unix binary, checking for errors.
799 static int fork_and_exec( const char *filename, char *cmdline,
800 const char *env, const char *newdir )
802 int fd[2];
803 int pid, err;
805 if (!env) env = GetEnvironmentStringsA();
807 if (pipe(fd) == -1)
809 FILE_SetDosError();
810 return -1;
812 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
813 if (!(pid = fork())) /* child */
815 char **argv = build_argv( cmdline, 0 );
816 char **envp = build_envp( env, NULL );
817 close( fd[0] );
819 /* Reset signals that we previously set to SIG_IGN */
820 signal( SIGPIPE, SIG_DFL );
821 signal( SIGCHLD, SIG_DFL );
823 if (newdir) chdir(newdir);
825 if (argv && envp) execve( filename, argv, envp );
826 err = errno;
827 write( fd[1], &err, sizeof(err) );
828 _exit(1);
830 close( fd[1] );
831 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
833 errno = err;
834 pid = -1;
836 if (pid == -1) FILE_SetDosError();
837 close( fd[0] );
838 return pid;
842 /***********************************************************************
843 * create_process
845 * Create a new process. If hFile is a valid handle we have an exe
846 * file, otherwise it is a Winelib app.
848 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
849 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
850 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
851 LPPROCESS_INFORMATION info, LPCSTR unixdir )
853 BOOL ret, success = FALSE;
854 HANDLE process_info;
855 startup_info_t startup_info;
856 char *extra_env = NULL;
857 int startfd[2];
858 int execfd[2];
859 pid_t pid;
860 int err;
861 char dummy = 0;
863 if (!env)
865 env = GetEnvironmentStringsA();
866 extra_env = DRIVE_BuildEnv();
869 /* create the synchronization pipes */
871 if (pipe( startfd ) == -1)
873 FILE_SetDosError();
874 return FALSE;
876 if (pipe( execfd ) == -1)
878 close( startfd[0] );
879 close( startfd[1] );
880 FILE_SetDosError();
881 return FALSE;
883 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
885 /* create the child process */
887 if (!(pid = fork())) /* child */
889 char **argv = build_argv( cmd_line, 1 );
890 char **envp = build_envp( env, extra_env );
892 close( startfd[1] );
893 close( execfd[0] );
895 /* wait for parent to tell us to start */
896 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
898 close( startfd[0] );
899 /* Reset signals that we previously set to SIG_IGN */
900 signal( SIGPIPE, SIG_DFL );
901 signal( SIGCHLD, SIG_DFL );
903 if (unixdir) chdir(unixdir);
905 if (argv && envp) exec_wine_binary( argv, envp );
907 err = errno;
908 write( execfd[1], &err, sizeof(err) );
909 _exit(1);
912 /* this is the parent */
914 close( startfd[0] );
915 close( execfd[1] );
916 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
917 if (pid == -1)
919 close( startfd[1] );
920 close( execfd[0] );
921 FILE_SetDosError();
922 return FALSE;
925 /* fill the startup info structure */
927 startup_info.size = sizeof(startup_info);
928 /* startup_info.filename_len is set below */
929 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
930 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
931 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
932 startup_info.x = startup->dwX;
933 startup_info.y = startup->dwY;
934 startup_info.cx = startup->dwXSize;
935 startup_info.cy = startup->dwYSize;
936 startup_info.x_chars = startup->dwXCountChars;
937 startup_info.y_chars = startup->dwYCountChars;
938 startup_info.attribute = startup->dwFillAttribute;
939 startup_info.cmd_show = startup->wShowWindow;
940 startup_info.flags = startup->dwFlags;
942 /* create the process on the server side */
944 SERVER_START_REQ( new_process )
946 char buf[MAX_PATH];
947 LPCSTR nameptr;
949 req->inherit_all = inherit;
950 req->create_flags = flags;
951 req->unix_pid = pid;
952 req->exe_file = hFile;
953 if (startup->dwFlags & STARTF_USESTDHANDLES)
955 req->hstdin = startup->hStdInput;
956 req->hstdout = startup->hStdOutput;
957 req->hstderr = startup->hStdError;
959 else
961 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
962 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
963 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
966 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
968 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
969 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
970 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
971 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
973 else
975 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
976 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
977 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
980 if (GetLongPathNameA( filename, buf, MAX_PATH ))
981 nameptr = buf;
982 else
983 nameptr = filename;
985 startup_info.filename_len = strlen(nameptr);
986 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
987 wine_server_add_data( req, nameptr, startup_info.filename_len );
988 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
989 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
990 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
992 ret = !wine_server_call_err( req );
993 process_info = reply->info;
995 SERVER_END_REQ;
997 if (!ret)
999 close( startfd[1] );
1000 close( execfd[0] );
1001 return FALSE;
1004 /* tell child to start and wait for it to exec */
1006 write( startfd[1], &dummy, 1 );
1007 close( startfd[1] );
1009 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1011 errno = err;
1012 FILE_SetDosError();
1013 close( execfd[0] );
1014 CloseHandle( process_info );
1015 return FALSE;
1018 /* wait for the new process info to be ready */
1020 WaitForSingleObject( process_info, INFINITE );
1021 SERVER_START_REQ( get_new_process_info )
1023 req->info = process_info;
1024 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1025 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1026 if ((ret = !wine_server_call_err( req )))
1028 info->dwProcessId = (DWORD)reply->pid;
1029 info->dwThreadId = (DWORD)reply->tid;
1030 info->hProcess = reply->phandle;
1031 info->hThread = reply->thandle;
1032 success = reply->success;
1035 SERVER_END_REQ;
1037 if (ret && !success) /* new process failed to start */
1039 DWORD exitcode;
1040 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1041 CloseHandle( info->hThread );
1042 CloseHandle( info->hProcess );
1043 ret = FALSE;
1045 CloseHandle( process_info );
1046 return ret;
1050 /***********************************************************************
1051 * create_vdm_process
1053 * Create a new VDM process for a 16-bit or DOS application.
1055 static BOOL create_vdm_process( LPCSTR filename, LPSTR cmd_line, LPCSTR env,
1056 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1057 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
1058 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1060 BOOL ret;
1061 LPSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + strlen(cmd_line) + 30 );
1063 if (!new_cmd_line)
1065 SetLastError( ERROR_OUTOFMEMORY );
1066 return FALSE;
1068 sprintf( new_cmd_line, "winevdm.exe --app-name \"%s\" %s", filename, cmd_line );
1069 ret = create_process( 0, "winevdm.exe", new_cmd_line, env, psa, tsa, inherit,
1070 flags, startup, info, unixdir );
1071 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1072 return ret;
1076 /*************************************************************************
1077 * get_file_name
1079 * Helper for CreateProcess: retrieve the file name to load from the
1080 * app name and command line. Store the file name in buffer, and
1081 * return a possibly modified command line.
1082 * Also returns a handle to the opened file if it's a Windows binary.
1084 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1085 int buflen, HANDLE *handle )
1087 char *name, *pos, *ret = NULL;
1088 const char *p;
1090 /* if we have an app name, everything is easy */
1092 if (appname)
1094 /* use the unmodified app name as file name */
1095 lstrcpynA( buffer, appname, buflen );
1096 *handle = open_exe_file( buffer );
1097 if (!(ret = cmdline) || !cmdline[0])
1099 /* no command-line, create one */
1100 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1101 sprintf( ret, "\"%s\"", appname );
1103 return ret;
1106 if (!cmdline)
1108 SetLastError( ERROR_INVALID_PARAMETER );
1109 return NULL;
1112 /* first check for a quoted file name */
1114 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1116 int len = p - cmdline - 1;
1117 /* extract the quoted portion as file name */
1118 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1119 memcpy( name, cmdline + 1, len );
1120 name[len] = 0;
1122 if (find_exe_file( name, buffer, buflen, handle ))
1123 ret = cmdline; /* no change necessary */
1124 goto done;
1127 /* now try the command-line word by word */
1129 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1130 pos = name;
1131 p = cmdline;
1133 while (*p)
1135 do *pos++ = *p++; while (*p && *p != ' ');
1136 *pos = 0;
1137 if (find_exe_file( name, buffer, buflen, handle ))
1139 ret = cmdline;
1140 break;
1144 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1146 /* now build a new command-line with quotes */
1148 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1149 sprintf( ret, "\"%s\"%s", name, p );
1151 done:
1152 HeapFree( GetProcessHeap(), 0, name );
1153 return ret;
1157 /**********************************************************************
1158 * CreateProcessA (KERNEL32.@)
1160 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1161 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1162 DWORD flags, LPVOID env, LPCSTR cur_dir,
1163 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1165 BOOL retv = FALSE;
1166 HANDLE hFile = 0;
1167 const char *unixdir = NULL;
1168 DOS_FULL_NAME full_dir;
1169 char name[MAX_PATH];
1170 LPSTR tidy_cmdline;
1171 char *p;
1173 /* Process the AppName and/or CmdLine to get module name and path */
1175 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1177 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1178 return FALSE;
1179 if (hFile == INVALID_HANDLE_VALUE) goto done;
1181 /* Warn if unsupported features are used */
1183 if (flags & NORMAL_PRIORITY_CLASS)
1184 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1185 if (flags & IDLE_PRIORITY_CLASS)
1186 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1187 if (flags & HIGH_PRIORITY_CLASS)
1188 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1189 if (flags & REALTIME_PRIORITY_CLASS)
1190 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1191 if (flags & CREATE_NEW_PROCESS_GROUP)
1192 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1193 if (flags & CREATE_UNICODE_ENVIRONMENT)
1194 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1195 if (flags & CREATE_SEPARATE_WOW_VDM)
1196 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1197 if (flags & CREATE_SHARED_WOW_VDM)
1198 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1199 if (flags & CREATE_DEFAULT_ERROR_MODE)
1200 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1201 if (flags & CREATE_NO_WINDOW)
1202 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1203 if (flags & PROFILE_USER)
1204 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1205 if (flags & PROFILE_KERNEL)
1206 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1207 if (flags & PROFILE_SERVER)
1208 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1209 if (startup_info->lpDesktop)
1210 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1211 name, debugstr_a(startup_info->lpDesktop));
1212 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1213 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1214 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1215 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1216 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1217 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1218 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1219 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1221 if (cur_dir)
1223 UNICODE_STRING cur_dirW;
1224 RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1225 if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1226 unixdir = full_dir.long_name;
1227 RtlFreeUnicodeString(&cur_dirW);
1229 else
1231 WCHAR buf[MAX_PATH];
1232 if (GetCurrentDirectoryW(MAX_PATH, buf))
1234 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1238 info->hThread = info->hProcess = 0;
1239 info->dwProcessId = info->dwThreadId = 0;
1241 /* Determine executable type */
1243 if (!hFile) /* builtin exe */
1245 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1246 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1247 inherit, flags, startup_info, info, unixdir );
1248 goto done;
1251 switch( MODULE_GetBinaryType( hFile ))
1253 case BINARY_PE_EXE:
1254 TRACE( "starting %s as Win32 binary\n", debugstr_a(name) );
1255 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1256 inherit, flags, startup_info, info, unixdir );
1257 break;
1258 case BINARY_WIN16:
1259 case BINARY_DOS:
1260 TRACE( "starting %s as Win16/DOS binary\n", debugstr_a(name) );
1261 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1262 inherit, flags, startup_info, info, unixdir );
1263 break;
1264 case BINARY_OS216:
1265 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1266 SetLastError( ERROR_BAD_EXE_FORMAT );
1267 break;
1268 case BINARY_PE_DLL:
1269 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1270 SetLastError( ERROR_BAD_EXE_FORMAT );
1271 break;
1272 case BINARY_UNIX_LIB:
1273 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1274 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1275 inherit, flags, startup_info, info, unixdir );
1276 break;
1277 case BINARY_UNKNOWN:
1278 /* check for .com or .bat extension */
1279 if ((p = strrchr( name, '.' )))
1281 if (!FILE_strcasecmp( p, ".com" ))
1283 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1284 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1285 inherit, flags, startup_info, info, unixdir );
1286 break;
1288 if (!FILE_strcasecmp( p, ".bat" ))
1290 char comspec[MAX_PATH];
1291 if (GetEnvironmentVariableA("COMSPEC", comspec, sizeof(comspec)))
1293 char *newcmdline;
1294 if ((newcmdline = HeapAlloc( GetProcessHeap(), 0,
1295 strlen(comspec) + 4 + strlen(tidy_cmdline) + 1)))
1297 sprintf( newcmdline, "%s /c %s", comspec, tidy_cmdline);
1298 TRACE( "starting %s as batch binary: %s\n",
1299 debugstr_a(name), debugstr_a(newcmdline) );
1300 retv = CreateProcessA( comspec, newcmdline, process_attr, thread_attr,
1301 inherit, flags, env, cur_dir, startup_info, info );
1302 HeapFree( GetProcessHeap(), 0, newcmdline );
1303 break;
1308 /* fall through */
1309 case BINARY_UNIX_EXE:
1311 /* unknown file, try as unix executable */
1312 UNICODE_STRING nameW;
1313 DOS_FULL_NAME full_name;
1314 const char *unixfilename = name;
1316 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1318 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1319 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1320 RtlFreeUnicodeString(&nameW);
1321 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1323 break;
1325 CloseHandle( hFile );
1327 done:
1328 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1329 return retv;
1333 /**********************************************************************
1334 * CreateProcessW (KERNEL32.@)
1335 * NOTES
1336 * lpReserved is not converted
1338 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1339 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1340 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1341 LPPROCESS_INFORMATION info )
1343 BOOL ret;
1344 STARTUPINFOA StartupInfoA;
1346 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1347 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1348 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1350 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1351 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1352 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1354 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1356 if (startup_info->lpReserved)
1357 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1358 debugstr_w(startup_info->lpReserved));
1360 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1361 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1363 HeapFree( GetProcessHeap(), 0, cur_dirA );
1364 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1365 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1366 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1368 return ret;
1372 /***********************************************************************
1373 * ExitProcess (KERNEL32.@)
1375 void WINAPI ExitProcess( DWORD status )
1377 LdrShutdownProcess();
1378 SERVER_START_REQ( terminate_process )
1380 /* send the exit code to the server */
1381 req->handle = GetCurrentProcess();
1382 req->exit_code = status;
1383 wine_server_call( req );
1385 SERVER_END_REQ;
1386 exit( 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 * GetExitCodeProcess [KERNEL32.@]
1403 * Gets termination status of specified process
1405 * RETURNS
1406 * Success: TRUE
1407 * Failure: FALSE
1409 BOOL WINAPI GetExitCodeProcess(
1410 HANDLE hProcess, /* [in] handle to the process */
1411 LPDWORD lpExitCode) /* [out] address to receive termination status */
1413 BOOL ret;
1414 SERVER_START_REQ( get_process_info )
1416 req->handle = hProcess;
1417 ret = !wine_server_call_err( req );
1418 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1420 SERVER_END_REQ;
1421 return ret;
1425 /***********************************************************************
1426 * SetErrorMode (KERNEL32.@)
1428 UINT WINAPI SetErrorMode( UINT mode )
1430 UINT old = current_process.error_mode;
1431 current_process.error_mode = mode;
1432 return old;
1436 /***********************************************************************
1437 * GetTickCount (KERNEL32.@)
1439 * Returns the number of milliseconds, modulo 2^32, since the start
1440 * of the wineserver.
1442 DWORD WINAPI GetTickCount(void)
1444 struct timeval t;
1445 gettimeofday( &t, NULL );
1446 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1450 /**********************************************************************
1451 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1453 * Allocates a thread local storage index
1455 * RETURNS
1456 * Success: TLS Index
1457 * Failure: 0xFFFFFFFF
1459 DWORD WINAPI TlsAlloc( void )
1461 DWORD i, mask, ret = 0;
1462 DWORD *bits = current_process.tls_bits;
1463 RtlAcquirePebLock();
1464 if (*bits == 0xffffffff)
1466 bits++;
1467 ret = 32;
1468 if (*bits == 0xffffffff)
1470 RtlReleasePebLock();
1471 SetLastError( ERROR_NO_MORE_ITEMS );
1472 return 0xffffffff;
1475 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1476 *bits |= mask;
1477 RtlReleasePebLock();
1478 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1479 return ret + i;
1483 /**********************************************************************
1484 * TlsFree [KERNEL32.@] Releases a TLS index.
1486 * Releases a thread local storage index, making it available for reuse
1488 * RETURNS
1489 * Success: TRUE
1490 * Failure: FALSE
1492 BOOL WINAPI TlsFree(
1493 DWORD index) /* [in] TLS Index to free */
1495 DWORD mask = (1 << (index & 31));
1496 DWORD *bits = current_process.tls_bits;
1497 if (index >= 64)
1499 SetLastError( ERROR_INVALID_PARAMETER );
1500 return FALSE;
1502 if (index >= 32) bits++;
1503 RtlAcquirePebLock();
1504 if (!(*bits & mask)) /* already free? */
1506 RtlReleasePebLock();
1507 SetLastError( ERROR_INVALID_PARAMETER );
1508 return FALSE;
1510 *bits &= ~mask;
1511 NtCurrentTeb()->tls_array[index] = 0;
1512 /* FIXME: should zero all other thread values */
1513 RtlReleasePebLock();
1514 return TRUE;
1518 /**********************************************************************
1519 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1521 * RETURNS
1522 * Success: Value stored in calling thread's TLS slot for index
1523 * Failure: 0 and GetLastError returns NO_ERROR
1525 LPVOID WINAPI TlsGetValue(
1526 DWORD index) /* [in] TLS index to retrieve value for */
1528 if (index >= 64)
1530 SetLastError( ERROR_INVALID_PARAMETER );
1531 return NULL;
1533 SetLastError( ERROR_SUCCESS );
1534 return NtCurrentTeb()->tls_array[index];
1538 /**********************************************************************
1539 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1541 * RETURNS
1542 * Success: TRUE
1543 * Failure: FALSE
1545 BOOL WINAPI TlsSetValue(
1546 DWORD index, /* [in] TLS index to set value for */
1547 LPVOID value) /* [in] Value to be stored */
1549 if (index >= 64)
1551 SetLastError( ERROR_INVALID_PARAMETER );
1552 return FALSE;
1554 NtCurrentTeb()->tls_array[index] = value;
1555 return TRUE;