Regression fixes for Nt{Read|Write}File:
[wine/multimedia.git] / scheduler / process.c
blob88b5201f9a09b9c07f7e5afa4a1ac158c72bec33
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 if (!process_pmts.hStdInput)
345 process_pmts.hStdInput = INVALID_HANDLE_VALUE;
346 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdInput)))
347 process_pmts.hStdInput = console_handle_map(process_pmts.hStdInput);
348 if (!process_pmts.hStdOutput)
349 process_pmts.hStdOutput = INVALID_HANDLE_VALUE;
350 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdOutput)))
351 process_pmts.hStdOutput = console_handle_map(process_pmts.hStdOutput);
352 if (!process_pmts.hStdError)
353 process_pmts.hStdError = INVALID_HANDLE_VALUE;
354 else if (VerifyConsoleIoHandle(console_handle_map(process_pmts.hStdError)))
355 process_pmts.hStdError = console_handle_map(process_pmts.hStdError);
358 /* Now we can use the pthreads routines */
359 PTHREAD_init_done();
361 /* Copy the parent environment */
362 if (!init_user_process_pmts( info_size, main_exe_name, sizeof(main_exe_name) ))
363 return FALSE;
365 /* Parse command line arguments */
366 OPTIONS_ParseOptions( !info_size ? argv : NULL );
368 /* <hack: to be changed later on> */
369 process_pmts.CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
370 process_pmts.CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
371 process_pmts.CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, process_pmts.CurrentDirectoryName.MaximumLength);
372 process_pmts.CurrentDirectoryName.Buffer[0] = 'C';
373 process_pmts.CurrentDirectoryName.Buffer[1] = ':';
374 process_pmts.CurrentDirectoryName.Buffer[2] = '\\';
375 process_pmts.CurrentDirectoryName.Buffer[3] = '\0';
376 /* </hack: to be changed later on> */
378 /* initialise DOS drives */
379 if (!DRIVE_Init()) return FALSE;
381 /* initialise DOS directories */
382 if (!DIR_Init()) return FALSE;
384 /* registry initialisation */
385 SHELL_LoadRegistry();
387 /* global boot finished, the rest is process-local */
388 CLIENT_BootDone( TRACE_ON(server) );
389 if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY_InitDebugLists();
391 return TRUE;
395 /***********************************************************************
396 * start_process
398 * Startup routine of a new process. Runs on the new process stack.
400 static void start_process( void *arg )
402 __TRY
404 LPTHREAD_START_ROUTINE entry;
405 HANDLE main_file = main_exe_file;
406 IMAGE_NT_HEADERS *nt;
407 PEB *peb = NtCurrentTeb()->Peb;
409 if (main_file)
411 UINT drive_type = GetDriveTypeA( main_exe_name );
412 /* don't keep the file handle open on removable media */
413 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) main_file = 0;
416 /* Retrieve entry point address */
417 nt = RtlImageNtHeader( peb->ImageBaseAddress );
418 entry = (LPTHREAD_START_ROUTINE)((char*)peb->ImageBaseAddress +
419 nt->OptionalHeader.AddressOfEntryPoint);
421 /* Install signal handlers; this cannot be done before, since we cannot
422 * send exceptions to the debugger before the create process event that
423 * is sent by REQ_INIT_PROCESS_DONE.
424 * We do need the handlers in place by the time the request is over, so
425 * we set them up here. If we segfault between here and the server call
426 * something is very wrong... */
427 if (!SIGNAL_Init()) goto error;
429 /* Signal the parent process to continue */
430 SERVER_START_REQ( init_process_done )
432 req->module = peb->ImageBaseAddress;
433 req->module_size = nt->OptionalHeader.SizeOfImage;
434 req->entry = entry;
435 /* API requires a double indirection */
436 req->name = &main_exe_name_ptr;
437 req->exe_file = main_file;
438 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
439 wine_server_add_data( req, main_exe_name, strlen(main_exe_name) );
440 wine_server_call( req );
441 peb->BeingDebugged = reply->debugged;
443 SERVER_END_REQ;
445 /* create the main modref and load dependencies */
446 if (!PE_CreateModule( peb->ImageBaseAddress, main_exe_name, 0, 0, FALSE )) goto error;
448 if (main_exe_file) CloseHandle( main_exe_file ); /* we no longer need it */
450 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
452 if (TRACE_ON(relay))
453 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n",
454 GetCurrentThreadId(), main_exe_name, entry );
455 if (peb->BeingDebugged) DbgBreakPoint();
456 SetLastError(0); /* clear error code */
457 ExitThread( entry( NtCurrentTeb()->Peb ) );
459 error:
460 ExitProcess( GetLastError() );
462 __EXCEPT(UnhandledExceptionFilter)
464 TerminateThread( GetCurrentThread(), GetExceptionCode() );
466 __ENDTRY
470 /***********************************************************************
471 * __wine_process_init
473 * Wine initialisation: load and start the main exe file.
475 void __wine_process_init( int argc, char *argv[] )
477 char error[1024], *p;
478 DWORD stack_size = 0;
479 int file_exists;
481 /* Initialize everything */
482 if (!process_init( argv )) exit(1);
484 argv++; /* remove argv[0] (wine itself) */
486 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
487 debugstr_a(main_exe_name), main_exe_file, debugstr_a(argv[0]) );
489 if (!main_exe_name[0])
491 if (!argv[0]) OPTIONS_Usage();
493 if (!find_exe_file( argv[0], main_exe_name, sizeof(main_exe_name), &main_exe_file ))
495 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
496 ExitProcess(1);
498 if (main_exe_file == INVALID_HANDLE_VALUE)
500 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
501 ExitProcess(1);
505 if (!main_exe_file) /* no file handle -> Winelib app */
507 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
508 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
509 goto found;
510 MESSAGE( "%s: cannot open builtin library for '%s': %s\n", argv0, main_exe_name, error );
511 ExitProcess(1);
513 VERSION_Init( main_exe_name );
515 switch( MODULE_GetBinaryType( main_exe_file ))
517 case BINARY_PE_EXE:
518 TRACE( "starting Win32 binary %s\n", debugstr_a(main_exe_name) );
519 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 ))) goto found;
520 MESSAGE( "%s: could not load '%s' as Win32 binary\n", argv0, main_exe_name );
521 ExitProcess(1);
522 case BINARY_PE_DLL:
523 MESSAGE( "%s: '%s' is a DLL, not an executable\n", argv0, main_exe_name );
524 ExitProcess(1);
525 case BINARY_UNKNOWN:
526 /* check for .com extension */
527 if (!(p = strrchr( main_exe_name, '.' )) || FILE_strcasecmp( p, ".com" ))
529 MESSAGE( "%s: cannot determine executable type for '%s'\n", argv0, main_exe_name );
530 ExitProcess(1);
532 /* fall through */
533 case BINARY_WIN16:
534 case BINARY_DOS:
535 TRACE( "starting Win16/DOS binary %s\n", debugstr_a(main_exe_name) );
536 CloseHandle( main_exe_file );
537 main_exe_file = 0;
538 argv--;
539 argv[0] = "winevdm.exe";
540 if (open_builtin_exe_file( "winevdm.exe", error, sizeof(error), 0, &file_exists ))
541 goto found;
542 MESSAGE( "%s: trying to run '%s', cannot open builtin library for 'winevdm.exe': %s\n",
543 argv0, main_exe_name, error );
544 ExitProcess(1);
545 case BINARY_OS216:
546 MESSAGE( "%s: '%s' is an OS/2 binary, not supported\n", argv0, main_exe_name );
547 ExitProcess(1);
548 case BINARY_UNIX_EXE:
549 MESSAGE( "%s: '%s' is a Unix binary, not supported\n", argv0, main_exe_name );
550 ExitProcess(1);
551 case BINARY_UNIX_LIB:
553 DOS_FULL_NAME full_name;
554 const char *name = main_exe_name;
555 UNICODE_STRING nameW;
557 TRACE( "starting Winelib app %s\n", debugstr_a(main_exe_name) );
558 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
559 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) name = full_name.long_name;
560 RtlFreeUnicodeString(&nameW);
561 CloseHandle( main_exe_file );
562 main_exe_file = 0;
563 if (wine_dlopen( name, RTLD_NOW, error, sizeof(error) ))
565 if ((p = strrchr( main_exe_name, '.' )) && !strcmp( p, ".so" )) *p = 0;
566 goto found;
568 MESSAGE( "%s: could not load '%s': %s\n", argv0, main_exe_name, error );
569 ExitProcess(1);
573 found:
574 /* build command line */
575 if (!build_command_line( argv )) goto error;
577 /* create 32-bit module for main exe */
578 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
579 stack_size = RtlImageNtHeader(current_process.module)->OptionalHeader.SizeOfStackReserve;
581 /* allocate main thread stack */
582 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
584 /* switch to the new stack */
585 SYSDEPS_SwitchToThreadStack( start_process, NULL );
587 error:
588 ExitProcess( GetLastError() );
592 /***********************************************************************
593 * build_argv
595 * Build an argv array from a command-line.
596 * The command-line is modified to insert nulls.
597 * 'reserved' is the number of args to reserve before the first one.
599 static char **build_argv( char *cmdline, int reserved )
601 int argc;
602 char** argv;
603 char *arg,*s,*d;
604 int in_quotes,bcount;
606 argc=reserved+1;
607 bcount=0;
608 in_quotes=0;
609 s=cmdline;
610 while (1) {
611 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
612 /* space */
613 argc++;
614 /* skip the remaining spaces */
615 while (*s==' ' || *s=='\t') {
616 s++;
618 if (*s=='\0')
619 break;
620 bcount=0;
621 continue;
622 } else if (*s=='\\') {
623 /* '\', count them */
624 bcount++;
625 } else if ((*s=='"') && ((bcount & 1)==0)) {
626 /* unescaped '"' */
627 in_quotes=!in_quotes;
628 bcount=0;
629 } else {
630 /* a regular character */
631 bcount=0;
633 s++;
635 argv=malloc(argc*sizeof(*argv));
636 if (!argv)
637 return NULL;
639 arg=d=s=cmdline;
640 bcount=0;
641 in_quotes=0;
642 argc=reserved;
643 while (*s) {
644 if ((*s==' ' || *s=='\t') && !in_quotes) {
645 /* Close the argument and copy it */
646 *d=0;
647 argv[argc++]=arg;
649 /* skip the remaining spaces */
650 do {
651 s++;
652 } while (*s==' ' || *s=='\t');
654 /* Start with a new argument */
655 arg=d=s;
656 bcount=0;
657 } else if (*s=='\\') {
658 /* '\\' */
659 *d++=*s++;
660 bcount++;
661 } else if (*s=='"') {
662 /* '"' */
663 if ((bcount & 1)==0) {
664 /* Preceeded by an even number of '\', this is half that
665 * number of '\', plus a '"' which we discard.
667 d-=bcount/2;
668 s++;
669 in_quotes=!in_quotes;
670 } else {
671 /* Preceeded by an odd number of '\', this is half that
672 * number of '\' followed by a '"'
674 d=d-bcount/2-1;
675 *d++='"';
676 s++;
678 bcount=0;
679 } else {
680 /* a regular character */
681 *d++=*s++;
682 bcount=0;
685 if (*arg) {
686 *d='\0';
687 argv[argc++]=arg;
689 argv[argc]=NULL;
691 return argv;
695 /***********************************************************************
696 * build_envp
698 * Build the environment of a new child process.
700 static char **build_envp( const char *env, const char *extra_env )
702 const char *p;
703 char **envp;
704 int count = 0;
706 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
707 for (p = env; *p; count++) p += strlen(p) + 1;
708 count += 3;
710 if ((envp = malloc( count * sizeof(*envp) )))
712 extern char **environ;
713 char **envptr = envp;
714 char **unixptr = environ;
715 /* first the extra strings */
716 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
717 /* then put PATH, HOME and WINEPREFIX from the unix env */
718 for (unixptr = environ; unixptr && *unixptr; unixptr++)
719 if (!memcmp( *unixptr, "PATH=", 5 ) ||
720 !memcmp( *unixptr, "HOME=", 5 ) ||
721 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
722 /* now put the Windows environment strings */
723 for (p = env; *p; p += strlen(p) + 1)
725 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
727 char *winepath = malloc( strlen(p) + 5 );
728 strcpy( winepath, "WINE" );
729 strcpy( winepath + 4, p );
730 *envptr++ = winepath;
732 else if (memcmp( p, "HOME=", 5 ) &&
733 memcmp( p, "WINEPATH=", 9 ) &&
734 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
736 *envptr = 0;
738 return envp;
742 /***********************************************************************
743 * exec_wine_binary
745 * Locate the Wine binary to exec for a new Win32 process.
747 static void exec_wine_binary( char **argv, char **envp )
749 const char *path, *pos, *ptr;
751 /* first, try for a WINELOADER environment variable */
752 argv[0] = getenv("WINELOADER");
753 if (argv[0])
754 execve( argv[0], argv, envp );
756 /* next, try bin directory */
757 argv[0] = BINDIR "/wine";
758 execve( argv[0], argv, envp );
760 /* now try the path of argv0 of the current binary */
761 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
762 if ((ptr = strrchr( full_argv0, '/' )))
764 memcpy( argv[0], full_argv0, ptr - full_argv0 );
765 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
766 execve( argv[0], argv, envp );
768 free( argv[0] );
770 /* now search in the Unix path */
771 if ((path = getenv( "PATH" )))
773 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
774 pos = path;
775 for (;;)
777 while (*pos == ':') pos++;
778 if (!*pos) break;
779 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
780 memcpy( argv[0], pos, ptr - pos );
781 strcpy( argv[0] + (ptr - pos), "/wine" );
782 execve( argv[0], argv, envp );
783 pos = ptr;
786 free( argv[0] );
790 /***********************************************************************
791 * fork_and_exec
793 * Fork and exec a new Unix binary, checking for errors.
795 static int fork_and_exec( const char *filename, char *cmdline,
796 const char *env, const char *newdir )
798 int fd[2];
799 int pid, err;
801 if (!env) env = GetEnvironmentStringsA();
803 if (pipe(fd) == -1)
805 FILE_SetDosError();
806 return -1;
808 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
809 if (!(pid = fork())) /* child */
811 char **argv = build_argv( cmdline, 0 );
812 char **envp = build_envp( env, NULL );
813 close( fd[0] );
815 /* Reset signals that we previously set to SIG_IGN */
816 signal( SIGPIPE, SIG_DFL );
817 signal( SIGCHLD, SIG_DFL );
819 if (newdir) chdir(newdir);
821 if (argv && envp) execve( filename, argv, envp );
822 err = errno;
823 write( fd[1], &err, sizeof(err) );
824 _exit(1);
826 close( fd[1] );
827 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
829 errno = err;
830 pid = -1;
832 if (pid == -1) FILE_SetDosError();
833 close( fd[0] );
834 return pid;
838 /***********************************************************************
839 * create_process
841 * Create a new process. If hFile is a valid handle we have an exe
842 * file, otherwise it is a Winelib app.
844 static BOOL create_process( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
845 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
846 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
847 LPPROCESS_INFORMATION info, LPCSTR unixdir )
849 BOOL ret, success = FALSE;
850 HANDLE process_info;
851 startup_info_t startup_info;
852 char *extra_env = NULL;
853 int startfd[2];
854 int execfd[2];
855 pid_t pid;
856 int err;
857 char dummy = 0;
859 if (!env)
861 env = GetEnvironmentStringsA();
862 extra_env = DRIVE_BuildEnv();
865 /* create the synchronization pipes */
867 if (pipe( startfd ) == -1)
869 FILE_SetDosError();
870 return FALSE;
872 if (pipe( execfd ) == -1)
874 close( startfd[0] );
875 close( startfd[1] );
876 FILE_SetDosError();
877 return FALSE;
879 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
881 /* create the child process */
883 if (!(pid = fork())) /* child */
885 char **argv = build_argv( cmd_line, 1 );
886 char **envp = build_envp( env, extra_env );
888 close( startfd[1] );
889 close( execfd[0] );
891 /* wait for parent to tell us to start */
892 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
894 close( startfd[0] );
895 /* Reset signals that we previously set to SIG_IGN */
896 signal( SIGPIPE, SIG_DFL );
897 signal( SIGCHLD, SIG_DFL );
899 if (unixdir) chdir(unixdir);
901 if (argv && envp) exec_wine_binary( argv, envp );
903 err = errno;
904 write( execfd[1], &err, sizeof(err) );
905 _exit(1);
908 /* this is the parent */
910 close( startfd[0] );
911 close( execfd[1] );
912 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
913 if (pid == -1)
915 close( startfd[1] );
916 close( execfd[0] );
917 FILE_SetDosError();
918 return FALSE;
921 /* fill the startup info structure */
923 startup_info.size = sizeof(startup_info);
924 /* startup_info.filename_len is set below */
925 startup_info.cmdline_len = cmd_line ? strlen(cmd_line) : 0;
926 startup_info.desktop_len = startup->lpDesktop ? strlen(startup->lpDesktop) : 0;
927 startup_info.title_len = startup->lpTitle ? strlen(startup->lpTitle) : 0;
928 startup_info.x = startup->dwX;
929 startup_info.y = startup->dwY;
930 startup_info.cx = startup->dwXSize;
931 startup_info.cy = startup->dwYSize;
932 startup_info.x_chars = startup->dwXCountChars;
933 startup_info.y_chars = startup->dwYCountChars;
934 startup_info.attribute = startup->dwFillAttribute;
935 startup_info.cmd_show = startup->wShowWindow;
936 startup_info.flags = startup->dwFlags;
938 /* create the process on the server side */
940 SERVER_START_REQ( new_process )
942 char buf[MAX_PATH];
943 LPCSTR nameptr;
945 req->inherit_all = inherit;
946 req->create_flags = flags;
947 req->use_handles = (startup->dwFlags & STARTF_USESTDHANDLES) != 0;
948 req->unix_pid = pid;
949 req->exe_file = hFile;
950 if (startup->dwFlags & STARTF_USESTDHANDLES)
952 req->hstdin = startup->hStdInput;
953 req->hstdout = startup->hStdOutput;
954 req->hstderr = startup->hStdError;
956 else
958 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
959 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
960 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
963 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
965 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
966 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
967 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
968 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
970 else
972 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
973 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
974 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
977 if (GetLongPathNameA( filename, buf, MAX_PATH ))
978 nameptr = buf;
979 else
980 nameptr = filename;
982 startup_info.filename_len = strlen(nameptr);
983 wine_server_add_data( req, &startup_info, sizeof(startup_info) );
984 wine_server_add_data( req, nameptr, startup_info.filename_len );
985 wine_server_add_data( req, cmd_line, startup_info.cmdline_len );
986 wine_server_add_data( req, startup->lpDesktop, startup_info.desktop_len );
987 wine_server_add_data( req, startup->lpTitle, startup_info.title_len );
989 ret = !wine_server_call_err( req );
990 process_info = reply->info;
992 SERVER_END_REQ;
994 if (!ret)
996 close( startfd[1] );
997 close( execfd[0] );
998 return FALSE;
1001 /* tell child to start and wait for it to exec */
1003 write( startfd[1], &dummy, 1 );
1004 close( startfd[1] );
1006 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1008 errno = err;
1009 FILE_SetDosError();
1010 close( execfd[0] );
1011 CloseHandle( process_info );
1012 return FALSE;
1015 /* wait for the new process info to be ready */
1017 WaitForSingleObject( process_info, INFINITE );
1018 SERVER_START_REQ( get_new_process_info )
1020 req->info = process_info;
1021 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1022 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1023 if ((ret = !wine_server_call_err( req )))
1025 info->dwProcessId = (DWORD)reply->pid;
1026 info->dwThreadId = (DWORD)reply->tid;
1027 info->hProcess = reply->phandle;
1028 info->hThread = reply->thandle;
1029 success = reply->success;
1032 SERVER_END_REQ;
1034 if (ret && !success) /* new process failed to start */
1036 DWORD exitcode;
1037 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1038 CloseHandle( info->hThread );
1039 CloseHandle( info->hProcess );
1040 ret = FALSE;
1042 CloseHandle( process_info );
1043 return ret;
1047 /***********************************************************************
1048 * create_vdm_process
1050 * Create a new VDM process for a 16-bit or DOS application.
1052 static BOOL create_vdm_process( LPCSTR filename, LPSTR cmd_line, LPCSTR env,
1053 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1054 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
1055 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1057 BOOL ret;
1058 LPSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + strlen(cmd_line) + 30 );
1060 if (!new_cmd_line)
1062 SetLastError( ERROR_OUTOFMEMORY );
1063 return FALSE;
1065 sprintf( new_cmd_line, "winevdm.exe --app-name \"%s\" %s", filename, cmd_line );
1066 ret = create_process( 0, "winevdm.exe", new_cmd_line, env, psa, tsa, inherit,
1067 flags, startup, info, unixdir );
1068 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1069 return ret;
1073 /*************************************************************************
1074 * get_file_name
1076 * Helper for CreateProcess: retrieve the file name to load from the
1077 * app name and command line. Store the file name in buffer, and
1078 * return a possibly modified command line.
1079 * Also returns a handle to the opened file if it's a Windows binary.
1081 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer,
1082 int buflen, HANDLE *handle )
1084 char *name, *pos, *ret = NULL;
1085 const char *p;
1087 /* if we have an app name, everything is easy */
1089 if (appname)
1091 /* use the unmodified app name as file name */
1092 lstrcpynA( buffer, appname, buflen );
1093 *handle = open_exe_file( buffer );
1094 if (!(ret = cmdline) || !cmdline[0])
1096 /* no command-line, create one */
1097 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
1098 sprintf( ret, "\"%s\"", appname );
1100 return ret;
1103 if (!cmdline)
1105 SetLastError( ERROR_INVALID_PARAMETER );
1106 return NULL;
1109 /* first check for a quoted file name */
1111 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
1113 int len = p - cmdline - 1;
1114 /* extract the quoted portion as file name */
1115 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
1116 memcpy( name, cmdline + 1, len );
1117 name[len] = 0;
1119 if (find_exe_file( name, buffer, buflen, handle ))
1120 ret = cmdline; /* no change necessary */
1121 goto done;
1124 /* now try the command-line word by word */
1126 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1127 pos = name;
1128 p = cmdline;
1130 while (*p)
1132 do *pos++ = *p++; while (*p && *p != ' ');
1133 *pos = 0;
1134 if (find_exe_file( name, buffer, buflen, handle ))
1136 ret = cmdline;
1137 break;
1141 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1143 /* now build a new command-line with quotes */
1145 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1146 sprintf( ret, "\"%s\"%s", name, p );
1148 done:
1149 HeapFree( GetProcessHeap(), 0, name );
1150 return ret;
1154 /**********************************************************************
1155 * CreateProcessA (KERNEL32.@)
1157 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1158 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1159 DWORD flags, LPVOID env, LPCSTR cur_dir,
1160 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1162 BOOL retv = FALSE;
1163 HANDLE hFile = 0;
1164 const char *unixdir = NULL;
1165 DOS_FULL_NAME full_dir;
1166 char name[MAX_PATH];
1167 LPSTR tidy_cmdline;
1168 char *p;
1170 /* Process the AppName and/or CmdLine to get module name and path */
1172 TRACE("app %s cmdline %s\n", debugstr_a(app_name), debugstr_a(cmd_line) );
1174 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1175 return FALSE;
1176 if (hFile == INVALID_HANDLE_VALUE) goto done;
1178 /* Warn if unsupported features are used */
1180 if (flags & NORMAL_PRIORITY_CLASS)
1181 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1182 if (flags & IDLE_PRIORITY_CLASS)
1183 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1184 if (flags & HIGH_PRIORITY_CLASS)
1185 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1186 if (flags & REALTIME_PRIORITY_CLASS)
1187 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1188 if (flags & CREATE_NEW_PROCESS_GROUP)
1189 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1190 if (flags & CREATE_UNICODE_ENVIRONMENT)
1191 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1192 if (flags & CREATE_SEPARATE_WOW_VDM)
1193 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1194 if (flags & CREATE_SHARED_WOW_VDM)
1195 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1196 if (flags & CREATE_DEFAULT_ERROR_MODE)
1197 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1198 if (flags & CREATE_NO_WINDOW)
1199 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1200 if (flags & PROFILE_USER)
1201 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1202 if (flags & PROFILE_KERNEL)
1203 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1204 if (flags & PROFILE_SERVER)
1205 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1206 if (startup_info->lpDesktop)
1207 FIXME("(%s,...): startup_info->lpDesktop %s ignored\n",
1208 name, debugstr_a(startup_info->lpDesktop));
1209 if (startup_info->dwFlags & STARTF_RUNFULLSCREEN)
1210 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1211 if (startup_info->dwFlags & STARTF_FORCEONFEEDBACK)
1212 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1213 if (startup_info->dwFlags & STARTF_FORCEOFFFEEDBACK)
1214 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1215 if (startup_info->dwFlags & STARTF_USEHOTKEY)
1216 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1218 if (cur_dir)
1220 UNICODE_STRING cur_dirW;
1221 RtlCreateUnicodeStringFromAsciiz(&cur_dirW, cur_dir);
1222 if (DOSFS_GetFullName( cur_dirW.Buffer, TRUE, &full_dir ))
1223 unixdir = full_dir.long_name;
1224 RtlFreeUnicodeString(&cur_dirW);
1226 else
1228 WCHAR buf[MAX_PATH];
1229 if (GetCurrentDirectoryW(MAX_PATH, buf))
1231 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1235 info->hThread = info->hProcess = 0;
1236 info->dwProcessId = info->dwThreadId = 0;
1238 /* Determine executable type */
1240 if (!hFile) /* builtin exe */
1242 TRACE( "starting %s as Winelib app\n", debugstr_a(name) );
1243 retv = create_process( 0, name, tidy_cmdline, env, process_attr, thread_attr,
1244 inherit, flags, startup_info, info, unixdir );
1245 goto done;
1248 switch( MODULE_GetBinaryType( hFile ))
1250 case BINARY_PE_EXE:
1251 TRACE( "starting %s as Win32 binary\n", debugstr_a(name) );
1252 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1253 inherit, flags, startup_info, info, unixdir );
1254 break;
1255 case BINARY_WIN16:
1256 case BINARY_DOS:
1257 TRACE( "starting %s as Win16/DOS binary\n", debugstr_a(name) );
1258 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1259 inherit, flags, startup_info, info, unixdir );
1260 break;
1261 case BINARY_OS216:
1262 FIXME( "%s is OS/2 binary, not supported\n", debugstr_a(name) );
1263 SetLastError( ERROR_BAD_EXE_FORMAT );
1264 break;
1265 case BINARY_PE_DLL:
1266 TRACE( "not starting %s since it is a dll\n", debugstr_a(name) );
1267 SetLastError( ERROR_BAD_EXE_FORMAT );
1268 break;
1269 case BINARY_UNIX_LIB:
1270 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_a(name) );
1271 retv = create_process( hFile, name, tidy_cmdline, env, process_attr, thread_attr,
1272 inherit, flags, startup_info, info, unixdir );
1273 break;
1274 case BINARY_UNKNOWN:
1275 /* check for .com or .bat extension */
1276 if ((p = strrchr( name, '.' )))
1278 if (!FILE_strcasecmp( p, ".com" ))
1280 TRACE( "starting %s as DOS binary\n", debugstr_a(name) );
1281 retv = create_vdm_process( name, tidy_cmdline, env, process_attr, thread_attr,
1282 inherit, flags, startup_info, info, unixdir );
1283 break;
1285 if (!FILE_strcasecmp( p, ".bat" ))
1287 char comspec[MAX_PATH];
1288 if (GetEnvironmentVariableA("COMSPEC", comspec, sizeof(comspec)))
1290 char *newcmdline;
1291 if ((newcmdline = HeapAlloc( GetProcessHeap(), 0,
1292 strlen(comspec) + 4 + strlen(tidy_cmdline) + 1)))
1294 sprintf( newcmdline, "%s /c %s", comspec, tidy_cmdline);
1295 TRACE( "starting %s as batch binary: %s\n",
1296 debugstr_a(name), debugstr_a(newcmdline) );
1297 retv = CreateProcessA( comspec, newcmdline, process_attr, thread_attr,
1298 inherit, flags, env, cur_dir, startup_info, info );
1299 HeapFree( GetProcessHeap(), 0, newcmdline );
1300 break;
1305 /* fall through */
1306 case BINARY_UNIX_EXE:
1308 /* unknown file, try as unix executable */
1309 UNICODE_STRING nameW;
1310 DOS_FULL_NAME full_name;
1311 const char *unixfilename = name;
1313 TRACE( "starting %s as Unix binary\n", debugstr_a(name) );
1315 RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1316 if (DOSFS_GetFullName( nameW.Buffer, TRUE, &full_name )) unixfilename = full_name.long_name;
1317 RtlFreeUnicodeString(&nameW);
1318 retv = (fork_and_exec( unixfilename, tidy_cmdline, env, unixdir ) != -1);
1320 break;
1322 CloseHandle( hFile );
1324 done:
1325 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1326 return retv;
1330 /**********************************************************************
1331 * CreateProcessW (KERNEL32.@)
1332 * NOTES
1333 * lpReserved is not converted
1335 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1336 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1337 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1338 LPPROCESS_INFORMATION info )
1340 BOOL ret;
1341 STARTUPINFOA StartupInfoA;
1343 LPSTR app_nameA = HEAP_strdupWtoA (GetProcessHeap(),0,app_name);
1344 LPSTR cmd_lineA = HEAP_strdupWtoA (GetProcessHeap(),0,cmd_line);
1345 LPSTR cur_dirA = HEAP_strdupWtoA (GetProcessHeap(),0,cur_dir);
1347 memcpy (&StartupInfoA, startup_info, sizeof(STARTUPINFOA));
1348 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpDesktop);
1349 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,startup_info->lpTitle);
1351 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(app_name), debugstr_w(cmd_line));
1353 if (startup_info->lpReserved)
1354 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n",
1355 debugstr_w(startup_info->lpReserved));
1357 ret = CreateProcessA( app_nameA, cmd_lineA, process_attr, thread_attr,
1358 inherit, flags, env, cur_dirA, &StartupInfoA, info );
1360 HeapFree( GetProcessHeap(), 0, cur_dirA );
1361 HeapFree( GetProcessHeap(), 0, cmd_lineA );
1362 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1363 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1365 return ret;
1369 /***********************************************************************
1370 * ExitProcess (KERNEL32.@)
1372 void WINAPI ExitProcess( DWORD status )
1374 LdrShutdownProcess();
1375 SERVER_START_REQ( terminate_process )
1377 /* send the exit code to the server */
1378 req->handle = GetCurrentProcess();
1379 req->exit_code = status;
1380 wine_server_call( req );
1382 SERVER_END_REQ;
1383 exit( status );
1386 /******************************************************************************
1387 * TerminateProcess (KERNEL32.@)
1389 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1391 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1392 if (status) SetLastError( RtlNtStatusToDosError(status) );
1393 return !status;
1397 /***********************************************************************
1398 * GetExitCodeProcess [KERNEL32.@]
1400 * Gets termination status of specified process
1402 * RETURNS
1403 * Success: TRUE
1404 * Failure: FALSE
1406 BOOL WINAPI GetExitCodeProcess(
1407 HANDLE hProcess, /* [in] handle to the process */
1408 LPDWORD lpExitCode) /* [out] address to receive termination status */
1410 BOOL ret;
1411 SERVER_START_REQ( get_process_info )
1413 req->handle = hProcess;
1414 ret = !wine_server_call_err( req );
1415 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1417 SERVER_END_REQ;
1418 return ret;
1422 /***********************************************************************
1423 * SetErrorMode (KERNEL32.@)
1425 UINT WINAPI SetErrorMode( UINT mode )
1427 UINT old = current_process.error_mode;
1428 current_process.error_mode = mode;
1429 return old;
1433 /***********************************************************************
1434 * GetTickCount (KERNEL32.@)
1436 * Returns the number of milliseconds, modulo 2^32, since the start
1437 * of the wineserver.
1439 DWORD WINAPI GetTickCount(void)
1441 struct timeval t;
1442 gettimeofday( &t, NULL );
1443 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
1447 /**********************************************************************
1448 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1450 * Allocates a thread local storage index
1452 * RETURNS
1453 * Success: TLS Index
1454 * Failure: 0xFFFFFFFF
1456 DWORD WINAPI TlsAlloc( void )
1458 DWORD i, mask, ret = 0;
1459 DWORD *bits = current_process.tls_bits;
1460 RtlAcquirePebLock();
1461 if (*bits == 0xffffffff)
1463 bits++;
1464 ret = 32;
1465 if (*bits == 0xffffffff)
1467 RtlReleasePebLock();
1468 SetLastError( ERROR_NO_MORE_ITEMS );
1469 return 0xffffffff;
1472 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1473 *bits |= mask;
1474 RtlReleasePebLock();
1475 NtCurrentTeb()->tls_array[ret+i] = 0; /* clear the value */
1476 return ret + i;
1480 /**********************************************************************
1481 * TlsFree [KERNEL32.@] Releases a TLS index.
1483 * Releases a thread local storage index, making it available for reuse
1485 * RETURNS
1486 * Success: TRUE
1487 * Failure: FALSE
1489 BOOL WINAPI TlsFree(
1490 DWORD index) /* [in] TLS Index to free */
1492 DWORD mask = (1 << (index & 31));
1493 DWORD *bits = current_process.tls_bits;
1494 if (index >= 64)
1496 SetLastError( ERROR_INVALID_PARAMETER );
1497 return FALSE;
1499 if (index >= 32) bits++;
1500 RtlAcquirePebLock();
1501 if (!(*bits & mask)) /* already free? */
1503 RtlReleasePebLock();
1504 SetLastError( ERROR_INVALID_PARAMETER );
1505 return FALSE;
1507 *bits &= ~mask;
1508 NtCurrentTeb()->tls_array[index] = 0;
1509 /* FIXME: should zero all other thread values */
1510 RtlReleasePebLock();
1511 return TRUE;
1515 /**********************************************************************
1516 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1518 * RETURNS
1519 * Success: Value stored in calling thread's TLS slot for index
1520 * Failure: 0 and GetLastError returns NO_ERROR
1522 LPVOID WINAPI TlsGetValue(
1523 DWORD index) /* [in] TLS index to retrieve value for */
1525 if (index >= 64)
1527 SetLastError( ERROR_INVALID_PARAMETER );
1528 return NULL;
1530 SetLastError( ERROR_SUCCESS );
1531 return NtCurrentTeb()->tls_array[index];
1535 /**********************************************************************
1536 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1538 * RETURNS
1539 * Success: TRUE
1540 * Failure: FALSE
1542 BOOL WINAPI TlsSetValue(
1543 DWORD index, /* [in] TLS index to set value for */
1544 LPVOID value) /* [in] Value to be stored */
1546 if (index >= 64)
1548 SetLastError( ERROR_INVALID_PARAMETER );
1549 return FALSE;
1551 NtCurrentTeb()->tls_array[index] = value;
1552 return TRUE;