Fix the conversions of a command line to/from an argv array.
[wine.git] / scheduler / process.c
blob084561cb3e9ac4e18828edf2bff9eb7a4a05b5d2
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <ctype.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include "wine/winbase16.h"
16 #include "wine/exception.h"
17 #include "wine/library.h"
18 #include "drive.h"
19 #include "module.h"
20 #include "file.h"
21 #include "thread.h"
22 #include "winerror.h"
23 #include "wine/server.h"
24 #include "options.h"
25 #include "callback.h"
26 #include "debugtools.h"
28 DEFAULT_DEBUG_CHANNEL(process);
29 DECLARE_DEBUG_CHANNEL(relay);
30 DECLARE_DEBUG_CHANNEL(win32);
32 struct _ENVDB;
34 /* Win32 process database */
35 typedef struct _PDB
37 LONG header[2]; /* 00 Kernel object header */
38 HMODULE module; /* 08 Main exe module (NT) */
39 void *event; /* 0c Pointer to an event object (unused) */
40 DWORD exit_code; /* 10 Process exit code */
41 DWORD unknown2; /* 14 Unknown */
42 HANDLE heap; /* 18 Default process heap */
43 HANDLE mem_context; /* 1c Process memory context */
44 DWORD flags; /* 20 Flags */
45 void *pdb16; /* 24 DOS PSP */
46 WORD PSP_sel; /* 28 Selector to DOS PSP */
47 WORD imte; /* 2a IMTE for the process module */
48 WORD threads; /* 2c Number of threads */
49 WORD running_threads; /* 2e Number of running threads */
50 WORD free_lib_count; /* 30 Recursion depth of FreeLibrary calls */
51 WORD ring0_threads; /* 32 Number of ring 0 threads */
52 HANDLE system_heap; /* 34 System heap to allocate handles */
53 HTASK task; /* 38 Win16 task */
54 void *mem_map_files; /* 3c Pointer to mem-mapped files */
55 struct _ENVDB *env_db; /* 40 Environment database */
56 void *handle_table; /* 44 Handle table */
57 struct _PDB *parent; /* 48 Parent process */
58 void *modref_list; /* 4c MODREF list */
59 void *thread_list; /* 50 List of threads */
60 void *debuggee_CB; /* 54 Debuggee context block */
61 void *local_heap_free; /* 58 Head of local heap free list */
62 DWORD unknown4; /* 5c Unknown */
63 CRITICAL_SECTION crit_section; /* 60 Critical section */
64 DWORD unknown5[3]; /* 78 Unknown */
65 void *console; /* 84 Console */
66 DWORD tls_bits[2]; /* 88 TLS in-use bits */
67 DWORD process_dword; /* 90 Unknown */
68 struct _PDB *group; /* 94 Process group */
69 void *exe_modref; /* 98 MODREF for the process EXE */
70 void *top_filter; /* 9c Top exception filter */
71 DWORD priority; /* a0 Priority level */
72 HANDLE heap_list; /* a4 Head of process heap list */
73 void *heap_handles; /* a8 Head of heap handles list */
74 DWORD unknown6; /* ac Unknown */
75 void *console_provider; /* b0 Console provider (??) */
76 WORD env_selector; /* b4 Selector to process environment */
77 WORD error_mode; /* b6 Error mode */
78 HANDLE load_done_evt; /* b8 Event for process loading done */
79 void *UTState; /* bc Head of Univeral Thunk list */
80 DWORD unknown8; /* c0 Unknown (NT) */
81 LCID locale; /* c4 Locale to be queried by GetThreadLocale (NT) */
82 } PDB;
84 PDB current_process;
86 /* Process flags */
87 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
88 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
89 #define PDB32_DOS_PROC 0x0010 /* Dos process */
90 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
91 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
92 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
94 static char **main_exe_argv;
95 static char main_exe_name[MAX_PATH];
96 static char *main_exe_name_ptr = main_exe_name;
97 static HANDLE main_exe_file;
99 unsigned int server_startticks;
101 /* memory/environ.c */
102 extern struct _ENVDB *ENV_BuildEnvironment(void);
103 extern BOOL ENV_BuildCommandLine( char **argv );
104 extern STARTUPINFOA current_startupinfo;
106 /* scheduler/pthread.c */
107 extern void PTHREAD_init_done(void);
109 extern BOOL MAIN_MainInit(void);
112 /***********************************************************************
113 * PROCESS_CallUserSignalProc
115 * FIXME: Some of the signals aren't sent correctly!
117 * The exact meaning of the USER signals is undocumented, but this
118 * should cover the basic idea:
120 * USIG_DLL_UNLOAD_WIN16
121 * This is sent when a 16-bit module is unloaded.
123 * USIG_DLL_UNLOAD_WIN32
124 * This is sent when a 32-bit module is unloaded.
126 * USIG_DLL_UNLOAD_ORPHANS
127 * This is sent after the last Win3.1 module is unloaded,
128 * to allow removal of orphaned menus.
130 * USIG_FAULT_DIALOG_PUSH
131 * USIG_FAULT_DIALOG_POP
132 * These are called to allow USER to prepare for displaying a
133 * fault dialog, even though the fault might have happened while
134 * inside a USER critical section.
136 * USIG_THREAD_INIT
137 * This is called from the context of a new thread, as soon as it
138 * has started to run.
140 * USIG_THREAD_EXIT
141 * This is called, still in its context, just before a thread is
142 * about to terminate.
144 * USIG_PROCESS_CREATE
145 * This is called, in the parent process context, after a new process
146 * has been created.
148 * USIG_PROCESS_INIT
149 * This is called in the new process context, just after the main thread
150 * has started execution (after the main thread's USIG_THREAD_INIT has
151 * been sent).
153 * USIG_PROCESS_LOADED
154 * This is called after the executable file has been loaded into the
155 * new process context.
157 * USIG_PROCESS_RUNNING
158 * This is called immediately before the main entry point is called.
160 * USIG_PROCESS_EXIT
161 * This is called in the context of a process that is about to
162 * terminate (but before the last thread's USIG_THREAD_EXIT has
163 * been sent).
165 * USIG_PROCESS_DESTROY
166 * This is called after a process has terminated.
169 * The meaning of the dwFlags bits is as follows:
171 * USIG_FLAGS_WIN32
172 * Current process is 32-bit.
174 * USIG_FLAGS_GUI
175 * Current process is a (Win32) GUI process.
177 * USIG_FLAGS_FEEDBACK
178 * Current process needs 'feedback' (determined from the STARTUPINFO
179 * flags STARTF_FORCEONFEEDBACK / STARTF_FORCEOFFFEEDBACK).
181 * USIG_FLAGS_FAULT
182 * The signal is being sent due to a fault.
184 void PROCESS_CallUserSignalProc( UINT uCode, HMODULE16 hModule )
186 DWORD flags = current_process.flags;
187 DWORD startup_flags = current_startupinfo.dwFlags;
188 DWORD dwFlags = 0;
190 if (!Callout.UserSignalProc) return;
192 /* Determine dwFlags */
194 if ( !(flags & PDB32_WIN16_PROC) ) dwFlags |= USIG_FLAGS_WIN32;
196 if ( !(flags & PDB32_CONSOLE_PROC) ) dwFlags |= USIG_FLAGS_GUI;
198 if ( dwFlags & USIG_FLAGS_GUI )
200 /* Feedback defaults to ON */
201 if ( !(startup_flags & STARTF_FORCEOFFFEEDBACK) )
202 dwFlags |= USIG_FLAGS_FEEDBACK;
204 else
206 /* Feedback defaults to OFF */
207 if (startup_flags & STARTF_FORCEONFEEDBACK)
208 dwFlags |= USIG_FLAGS_FEEDBACK;
211 /* Call USER signal proc */
213 if ( uCode == USIG_THREAD_INIT || uCode == USIG_THREAD_EXIT )
214 Callout.UserSignalProc( uCode, GetCurrentThreadId(), dwFlags, hModule );
215 else
216 Callout.UserSignalProc( uCode, GetCurrentProcessId(), dwFlags, hModule );
220 /***********************************************************************
221 * set_console_handles
223 * Set the console handles to use stdin/stdout.
225 static void set_console_handles( HANDLE console )
227 wine_server_send_fd( 0 );
228 wine_server_send_fd( 1 );
230 SERVER_START_REQ( set_console_fd )
232 req->handle = console;
233 req->fd_in = 0;
234 req->fd_out = 1;
235 req->pid = 0;
236 SERVER_CALL();
238 SERVER_END_REQ;
242 /***********************************************************************
243 * process_init
245 * Main process initialisation code
247 static BOOL process_init( char *argv[] )
249 BOOL ret;
250 int create_flags = 0;
252 /* store the program name */
253 argv0 = argv[0];
254 main_exe_argv = argv;
256 /* Fill the initial process structure */
257 current_process.exit_code = STILL_ACTIVE;
258 current_process.threads = 1;
259 current_process.running_threads = 1;
260 current_process.ring0_threads = 1;
261 current_process.group = &current_process;
262 current_process.priority = 8; /* Normal */
264 /* Setup the server connection */
265 CLIENT_InitServer();
267 /* Retrieve startup info from the server */
268 SERVER_START_VAR_REQ( init_process, sizeof(main_exe_name)-1 )
270 req->ldt_copy = &wine_ldt_copy;
271 req->ppid = getppid();
272 if ((ret = !SERVER_CALL_ERR()))
274 size_t len = server_data_size( req );
275 memcpy( main_exe_name, server_data_ptr(req), len );
276 main_exe_name[len] = 0;
277 main_exe_file = req->exe_file;
278 create_flags = req->create_flags;
279 current_startupinfo.dwFlags = req->start_flags;
280 server_startticks = req->server_start;
281 current_startupinfo.wShowWindow = req->cmd_show;
282 current_startupinfo.hStdInput = req->hstdin;
283 current_startupinfo.hStdOutput = req->hstdout;
284 current_startupinfo.hStdError = req->hstderr;
287 SERVER_END_VAR_REQ;
288 if (!ret) return FALSE;
290 SetStdHandle( STD_INPUT_HANDLE, current_startupinfo.hStdInput );
291 SetStdHandle( STD_OUTPUT_HANDLE, current_startupinfo.hStdOutput );
292 SetStdHandle( STD_ERROR_HANDLE, current_startupinfo.hStdError );
293 if (create_flags & CREATE_NEW_CONSOLE)
294 set_console_handles( current_startupinfo.hStdOutput );
296 /* Create the process heap */
297 current_process.heap = HeapCreate( HEAP_GROWABLE, 0, 0 );
299 /* Now we can use the pthreads routines */
300 PTHREAD_init_done();
302 /* Copy the parent environment */
303 if (!(current_process.env_db = ENV_BuildEnvironment())) return FALSE;
305 /* Parse command line arguments */
306 OPTIONS_ParseOptions( argv );
308 return MAIN_MainInit();
312 /***********************************************************************
313 * start_process
315 * Startup routine of a new process. Runs on the new process stack.
317 static void start_process(void)
319 int debugged, console_app;
320 LPTHREAD_START_ROUTINE entry;
321 WINE_MODREF *wm;
323 /* use original argv[0] as name for the main module */
324 if (!main_exe_name[0])
326 if (!GetLongPathNameA( full_argv0, main_exe_name, sizeof(main_exe_name) ))
327 lstrcpynA( main_exe_name, full_argv0, sizeof(main_exe_name) );
330 /* Retrieve entry point address */
331 entry = (LPTHREAD_START_ROUTINE)((char*)current_process.module +
332 PE_HEADER(current_process.module)->OptionalHeader.AddressOfEntryPoint);
333 console_app = (PE_HEADER(current_process.module)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
334 if (console_app) current_process.flags |= PDB32_CONSOLE_PROC;
336 /* Signal the parent process to continue */
337 SERVER_START_REQ( init_process_done )
339 req->module = (void *)current_process.module;
340 req->entry = entry;
341 /* API requires a double indirection */
342 req->name = &main_exe_name_ptr;
343 req->exe_file = main_exe_file;
344 req->gui = !console_app;
345 SERVER_CALL();
346 debugged = req->debugged;
348 SERVER_END_REQ;
350 /* Install signal handlers; this cannot be done before, since we cannot
351 * send exceptions to the debugger before the create process event that
352 * is sent by REQ_INIT_PROCESS_DONE */
353 if (!SIGNAL_Init()) goto error;
355 /* create the main modref and load dependencies */
356 if (!(wm = PE_CreateModule( current_process.module, main_exe_name, 0, 0, FALSE )))
357 goto error;
358 wm->refCount++;
360 RtlAcquirePebLock();
361 PE_InitTls();
362 MODULE_DllProcessAttach( NULL, (LPVOID)1 );
363 RtlReleasePebLock();
365 /* Get pointers to USER routines called by KERNEL */
366 THUNK_InitCallout();
368 /* Note: The USIG_PROCESS_CREATE signal is supposed to be sent in the
369 * context of the parent process. Actually, the USER signal proc
370 * doesn't really care about that, but it *does* require that the
371 * startup parameters are correctly set up, so that GetProcessDword
372 * works. Furthermore, before calling the USER signal proc the
373 * 16-bit stack must be set up, which it is only after TASK_Create
374 * in the case of a 16-bit process. Thus, we send the signal here.
376 PROCESS_CallUserSignalProc( USIG_PROCESS_CREATE, 0 );
377 PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
378 PROCESS_CallUserSignalProc( USIG_PROCESS_INIT, 0 );
379 PROCESS_CallUserSignalProc( USIG_PROCESS_LOADED, 0 );
380 /* Call UserSignalProc ( USIG_PROCESS_RUNNING ... ) only for non-GUI win32 apps */
381 if (console_app) PROCESS_CallUserSignalProc( USIG_PROCESS_RUNNING, 0 );
383 if (TRACE_ON(relay))
384 DPRINTF( "%08lx:Starting process %s (entryproc=%p)\n",
385 GetCurrentThreadId(), main_exe_name, entry );
386 if (debugged) DbgBreakPoint();
387 /* FIXME: should use _PEB as parameter for NT 3.5 programs !
388 * Dunno about other OSs */
389 SetLastError(0); /* clear error code */
390 ExitThread( entry(NULL) );
392 error:
393 ExitProcess( GetLastError() );
397 /***********************************************************************
398 * open_winelib_app
400 * Try to open the Winelib app .so file based on argv[0] or WINEPRELOAD.
402 void *open_winelib_app( char *argv[] )
404 void *ret = NULL;
405 char *tmp;
406 const char *name;
407 char errStr[100];
409 if ((name = getenv( "WINEPRELOAD" )))
411 if (!(ret = wine_dll_load_main_exe( name, 0, errStr, sizeof(errStr) )))
413 MESSAGE( "%s: could not load '%s' as specified in the WINEPRELOAD environment variable: %s\n",
414 argv[0], name, errStr );
415 ExitProcess(1);
418 else
420 const char *argv0 = main_exe_name;
421 if (!*argv0)
423 /* if argv[0] is "wine", don't try to load anything */
424 argv0 = argv[0];
425 if (!(name = strrchr( argv0, '/' ))) name = argv0;
426 else name++;
427 if (!strcmp( name, "wine" )) return NULL;
430 /* now try argv[0] with ".so" appended */
431 if ((tmp = HeapAlloc( GetProcessHeap(), 0, strlen(argv0) + 4 )))
433 strcpy( tmp, argv0 );
434 strcat( tmp, ".so" );
435 /* search in PATH only if there was no '/' in argv[0] */
436 ret = wine_dll_load_main_exe( tmp, (name == argv0), errStr, sizeof(errStr) );
437 if (!ret && !argv[1])
439 /* if no argv[1], this will be better than displaying usage */
440 MESSAGE( "%s: could not load library '%s' as Winelib application: %s\n",
441 argv[0], tmp, errStr );
442 ExitProcess(1);
444 HeapFree( GetProcessHeap(), 0, tmp );
447 return ret;
450 /***********************************************************************
451 * PROCESS_InitWine
453 * Wine initialisation: load and start the main exe file.
455 void PROCESS_InitWine( int argc, char *argv[], LPSTR win16_exe_name, HANDLE *win16_exe_file )
457 DWORD stack_size = 0;
459 /* Initialize everything */
460 if (!process_init( argv )) exit(1);
462 if (open_winelib_app( argv )) goto found; /* try to open argv[0] as a winelib app */
464 main_exe_argv = ++argv; /* remove argv[0] (wine itself) */
466 if (!main_exe_name[0])
468 if (!argv[0]) OPTIONS_Usage();
470 /* open the exe file */
471 if (!SearchPathA( NULL, argv[0], ".exe", sizeof(main_exe_name), main_exe_name, NULL ) &&
472 !SearchPathA( NULL, argv[0], NULL, sizeof(main_exe_name), main_exe_name, NULL ))
474 MESSAGE( "%s: cannot find '%s'\n", argv0, argv[0] );
475 goto error;
479 if (!main_exe_file)
481 if ((main_exe_file = CreateFileA( main_exe_name, GENERIC_READ, FILE_SHARE_READ,
482 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
484 MESSAGE( "%s: cannot open '%s'\n", argv0, main_exe_name );
485 goto error;
489 /* first try Win32 format; this will fail if the file is not a PE binary */
490 if ((current_process.module = PE_LoadImage( main_exe_file, main_exe_name, 0 )))
492 if (PE_HEADER(current_process.module)->FileHeader.Characteristics & IMAGE_FILE_DLL)
493 ExitProcess( ERROR_BAD_EXE_FORMAT );
494 goto found;
497 /* it must be 16-bit or DOS format */
498 NtCurrentTeb()->tibflags &= ~TEBF_WIN32;
499 current_process.flags |= PDB32_WIN16_PROC;
500 strcpy( win16_exe_name, main_exe_name );
501 main_exe_name[0] = 0;
502 *win16_exe_file = main_exe_file;
503 main_exe_file = 0;
504 _EnterWin16Lock();
506 found:
507 /* build command line */
508 if (!ENV_BuildCommandLine( main_exe_argv )) goto error;
510 /* create 32-bit module for main exe */
511 if (!(current_process.module = BUILTIN32_LoadExeModule( current_process.module ))) goto error;
512 stack_size = PE_HEADER(current_process.module)->OptionalHeader.SizeOfStackReserve;
514 /* allocate main thread stack */
515 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
517 /* switch to the new stack */
518 SYSDEPS_SwitchToThreadStack( start_process );
520 error:
521 ExitProcess( GetLastError() );
525 /***********************************************************************
526 * build_argv
528 * Build an argv array from a command-line.
529 * The command-line is modified to insert nulls.
530 * 'reserved' is the number of args to reserve before the first one.
532 static char **build_argv( char *cmdline, int reserved )
534 int argc;
535 char** argv;
536 char *arg,*s,*d;
537 int in_quotes,bcount;
539 argc=reserved+1;
540 bcount=0;
541 in_quotes=0;
542 s=cmdline;
543 while (1) {
544 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
545 /* space */
546 argc++;
547 /* skip the remaining spaces */
548 while (*s==' ' || *s=='\t') {
549 s++;
551 if (*s=='\0')
552 break;
553 bcount=0;
554 continue;
555 } else if (*s=='\\') {
556 /* '\', count them */
557 bcount++;
558 } else if ((*s=='"') && ((bcount & 1)==0)) {
559 /* unescaped '"' */
560 in_quotes=!in_quotes;
561 bcount=0;
562 } else {
563 /* a regular character */
564 bcount=0;
566 s++;
568 argv=malloc(argc*sizeof(*argv));
569 if (!argv)
570 return NULL;
572 arg=d=s=cmdline;
573 bcount=0;
574 in_quotes=0;
575 argc=reserved;
576 while (*s) {
577 if ((*s==' ' || *s=='\t') && !in_quotes) {
578 /* Close the argument and copy it */
579 *d=0;
580 argv[argc++]=arg;
582 /* skip the remaining spaces */
583 do {
584 s++;
585 } while (*s==' ' || *s=='\t');
587 /* Start with a new argument */
588 arg=d=s;
589 bcount=0;
590 } else if (*s=='\\') {
591 /* '\\' */
592 *d++=*s++;
593 bcount++;
594 } else if (*s=='"') {
595 /* '"' */
596 if ((bcount & 1)==0) {
597 /* Preceeded by an even number of '\', this is half that
598 * number of '\', plus a '"' which we discard.
600 d-=bcount/2;
601 s++;
602 in_quotes=!in_quotes;
603 } else {
604 /* Preceeded by an odd number of '\', this is half that
605 * number of '\' followed by a '"'
607 d=d-bcount/2-1;
608 *d++='"';
609 s++;
611 bcount=0;
612 } else {
613 /* a regular character */
614 *d++=*s++;
615 bcount=0;
618 if (*arg) {
619 *d='\0';
620 argv[argc++]=arg;
622 argv[argc]=NULL;
624 return argv;
628 /***********************************************************************
629 * build_envp
631 * Build the environment of a new child process.
633 static char **build_envp( const char *env, const char *extra_env )
635 const char *p;
636 char **envp;
637 int count = 0;
639 if (extra_env) for (p = extra_env; *p; count++) p += strlen(p) + 1;
640 for (p = env; *p; count++) p += strlen(p) + 1;
641 count += 3;
643 if ((envp = malloc( count * sizeof(*envp) )))
645 extern char **environ;
646 char **envptr = envp;
647 char **unixptr = environ;
648 /* first the extra strings */
649 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = (char *)p;
650 /* then put PATH, HOME and WINEPREFIX from the unix env */
651 for (unixptr = environ; unixptr && *unixptr; unixptr++)
652 if (!memcmp( *unixptr, "PATH=", 5 ) ||
653 !memcmp( *unixptr, "HOME=", 5 ) ||
654 !memcmp( *unixptr, "WINEPREFIX=", 11 )) *envptr++ = *unixptr;
655 /* now put the Windows environment strings */
656 for (p = env; *p; p += strlen(p) + 1)
658 if (memcmp( p, "PATH=", 5 ) &&
659 memcmp( p, "HOME=", 5 ) &&
660 memcmp( p, "WINEPRELOAD=", 12 ) &&
661 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = (char *)p;
663 *envptr = 0;
665 return envp;
669 /***********************************************************************
670 * exec_wine_binary
672 * Locate the Wine binary to exec for a new Win32 process.
674 static void exec_wine_binary( char **argv, char **envp )
676 const char *path, *pos, *ptr;
678 /* first, try for a WINELOADER environment variable */
679 argv[0] = getenv("WINELOADER");
680 if (argv[0])
681 execve( argv[0], argv, envp );
683 /* next, try bin directory */
684 argv[0] = BINDIR "/wine";
685 execve( argv[0], argv, envp );
687 /* now try the path of argv0 of the current binary */
688 if (!(argv[0] = malloc( strlen(full_argv0) + 6 ))) return;
689 if ((ptr = strrchr( full_argv0, '/' )))
691 memcpy( argv[0], full_argv0, ptr - full_argv0 );
692 strcpy( argv[0] + (ptr - full_argv0), "/wine" );
693 execve( argv[0], argv, envp );
695 free( argv[0] );
697 /* now search in the Unix path */
698 if ((path = getenv( "PATH" )))
700 if (!(argv[0] = malloc( strlen(path) + 6 ))) return;
701 pos = path;
702 for (;;)
704 while (*pos == ':') pos++;
705 if (!*pos) break;
706 if (!(ptr = strchr( pos, ':' ))) ptr = pos + strlen(pos);
707 memcpy( argv[0], pos, ptr - pos );
708 strcpy( argv[0] + (ptr - pos), "/wine" );
709 execve( argv[0], argv, envp );
710 pos = ptr;
713 free( argv[0] );
715 /* finally try the current directory */
716 argv[0] = "./wine";
717 execve( argv[0], argv, envp );
721 /***********************************************************************
722 * fork_and_exec
724 * Fork and exec a new Unix process, checking for errors.
726 static int fork_and_exec( const char *filename, char *cmdline,
727 const char *env, const char *newdir )
729 int fd[2];
730 int pid, err;
731 char *extra_env = NULL;
733 if (!env)
735 env = GetEnvironmentStringsA();
736 extra_env = DRIVE_BuildEnv();
739 if (pipe(fd) == -1)
741 FILE_SetDosError();
742 return -1;
744 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
745 if (!(pid = fork())) /* child */
747 char **argv = build_argv( cmdline, filename ? 0 : 2 );
748 char **envp = build_envp( env, extra_env );
749 close( fd[0] );
751 if (newdir) chdir(newdir);
753 if (argv && envp)
755 if (!filename)
757 argv[1] = "--";
758 exec_wine_binary( argv, envp );
760 else execve( filename, argv, envp );
762 err = errno;
763 write( fd[1], &err, sizeof(err) );
764 _exit(1);
766 close( fd[1] );
767 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
769 errno = err;
770 pid = -1;
772 if (pid == -1) FILE_SetDosError();
773 close( fd[0] );
774 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
775 return pid;
779 /***********************************************************************
780 * PROCESS_Create
782 * Create a new process. If hFile is a valid handle we have an exe
783 * file, and we exec a new copy of wine to load it; otherwise we
784 * simply exec the specified filename as a Unix process.
786 BOOL PROCESS_Create( HANDLE hFile, LPCSTR filename, LPSTR cmd_line, LPCSTR env,
787 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
788 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
789 LPPROCESS_INFORMATION info, LPCSTR lpCurrentDirectory )
791 BOOL ret;
792 int pid;
793 const char *unixfilename = NULL;
794 const char *unixdir = NULL;
795 DOS_FULL_NAME full_dir, full_name;
796 HANDLE load_done_evt = 0;
797 HANDLE process_info;
799 info->hThread = info->hProcess = 0;
801 if (lpCurrentDirectory)
803 if (DOSFS_GetFullName( lpCurrentDirectory, TRUE, &full_dir ))
804 unixdir = full_dir.long_name;
806 else
808 char buf[MAX_PATH];
809 if (GetCurrentDirectoryA(sizeof(buf),buf))
811 if (DOSFS_GetFullName( buf, TRUE, &full_dir ))
812 unixdir = full_dir.long_name;
816 /* create the process on the server side */
818 SERVER_START_VAR_REQ( new_process, MAX_PATH )
820 req->inherit_all = inherit;
821 req->create_flags = flags;
822 req->start_flags = startup->dwFlags;
823 req->exe_file = hFile;
824 if (startup->dwFlags & STARTF_USESTDHANDLES)
826 req->hstdin = startup->hStdInput;
827 req->hstdout = startup->hStdOutput;
828 req->hstderr = startup->hStdError;
830 else
832 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
833 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
834 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
836 req->cmd_show = startup->wShowWindow;
838 if (!hFile) /* unix process */
840 unixfilename = filename;
841 if (DOSFS_GetFullName( filename, TRUE, &full_name ))
842 unixfilename = full_name.long_name;
843 lstrcpynA( server_data_ptr(req), unixfilename, MAX_PATH );
845 else /* new wine process */
847 if (!GetLongPathNameA( filename, server_data_ptr(req), MAX_PATH ))
848 lstrcpynA( server_data_ptr(req), filename, MAX_PATH );
850 ret = !SERVER_CALL_ERR();
851 process_info = req->info;
853 SERVER_END_VAR_REQ;
854 if (!ret) return FALSE;
856 /* fork and execute */
858 pid = fork_and_exec( unixfilename, cmd_line, env, unixdir );
860 /* wait for the new process info to be ready */
862 ret = FALSE;
863 if ((pid != -1) && (WaitForSingleObject( process_info, 2000 ) == STATUS_WAIT_0))
865 SERVER_START_REQ( get_new_process_info )
867 req->info = process_info;
868 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
869 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
870 if ((ret = !SERVER_CALL_ERR()))
872 info->dwProcessId = (DWORD)req->pid;
873 info->dwThreadId = (DWORD)req->tid;
874 info->hProcess = req->phandle;
875 info->hThread = req->thandle;
876 load_done_evt = req->event;
879 SERVER_END_REQ;
881 CloseHandle( process_info );
882 if (!ret) goto error;
884 /* Wait until process is initialized (or initialization failed) */
885 if (load_done_evt)
887 DWORD res;
888 HANDLE handles[2];
890 handles[0] = info->hProcess;
891 handles[1] = load_done_evt;
892 res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE );
893 CloseHandle( load_done_evt );
894 if (res == STATUS_WAIT_0) /* the process died */
896 DWORD exitcode;
897 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
898 CloseHandle( info->hThread );
899 CloseHandle( info->hProcess );
900 return FALSE;
903 return TRUE;
905 error:
906 if (load_done_evt) CloseHandle( load_done_evt );
907 if (info->hThread) CloseHandle( info->hThread );
908 if (info->hProcess) CloseHandle( info->hProcess );
909 return FALSE;
913 /***********************************************************************
914 * ExitProcess (KERNEL32.@)
916 void WINAPI ExitProcess( DWORD status )
918 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
919 SERVER_START_REQ( terminate_process )
921 /* send the exit code to the server */
922 req->handle = GetCurrentProcess();
923 req->exit_code = status;
924 SERVER_CALL();
926 SERVER_END_REQ;
927 exit( status );
930 /***********************************************************************
931 * ExitProcess (KERNEL.466)
933 void WINAPI ExitProcess16( WORD status )
935 DWORD count;
936 ReleaseThunkLock( &count );
937 ExitProcess( status );
940 /******************************************************************************
941 * TerminateProcess (KERNEL32.@)
943 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
945 NTSTATUS status = NtTerminateProcess( handle, exit_code );
946 if (status) SetLastError( RtlNtStatusToDosError(status) );
947 return !status;
951 /***********************************************************************
952 * GetProcessDword (KERNEL.485)
953 * GetProcessDword (KERNEL32.18)
954 * 'Of course you cannot directly access Windows internal structures'
956 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
958 DWORD x, y;
960 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
962 if (dwProcessID && dwProcessID != GetCurrentProcessId())
964 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
965 return 0;
968 switch ( offset )
970 case GPD_APP_COMPAT_FLAGS:
971 return GetAppCompatFlags16(0);
973 case GPD_LOAD_DONE_EVENT:
974 return current_process.load_done_evt;
976 case GPD_HINSTANCE16:
977 return GetTaskDS16();
979 case GPD_WINDOWS_VERSION:
980 return GetExeVersion16();
982 case GPD_THDB:
983 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
985 case GPD_PDB:
986 return (DWORD)&current_process;
988 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
989 return current_startupinfo.hStdOutput;
991 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
992 return current_startupinfo.hStdInput;
994 case GPD_STARTF_SHOWWINDOW:
995 return current_startupinfo.wShowWindow;
997 case GPD_STARTF_SIZE:
998 x = current_startupinfo.dwXSize;
999 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1000 y = current_startupinfo.dwYSize;
1001 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1002 return MAKELONG( x, y );
1004 case GPD_STARTF_POSITION:
1005 x = current_startupinfo.dwX;
1006 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
1007 y = current_startupinfo.dwY;
1008 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
1009 return MAKELONG( x, y );
1011 case GPD_STARTF_FLAGS:
1012 return current_startupinfo.dwFlags;
1014 case GPD_PARENT:
1015 return 0;
1017 case GPD_FLAGS:
1018 return current_process.flags;
1020 case GPD_USERDATA:
1021 return current_process.process_dword;
1023 default:
1024 ERR_(win32)("Unknown offset %d\n", offset );
1025 return 0;
1029 /***********************************************************************
1030 * SetProcessDword (KERNEL.484)
1031 * 'Of course you cannot directly access Windows internal structures'
1033 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
1035 TRACE_(win32)("(%ld, %d)\n", dwProcessID, offset );
1037 if (dwProcessID && dwProcessID != GetCurrentProcessId())
1039 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
1040 return;
1043 switch ( offset )
1045 case GPD_APP_COMPAT_FLAGS:
1046 case GPD_LOAD_DONE_EVENT:
1047 case GPD_HINSTANCE16:
1048 case GPD_WINDOWS_VERSION:
1049 case GPD_THDB:
1050 case GPD_PDB:
1051 case GPD_STARTF_SHELLDATA:
1052 case GPD_STARTF_HOTKEY:
1053 case GPD_STARTF_SHOWWINDOW:
1054 case GPD_STARTF_SIZE:
1055 case GPD_STARTF_POSITION:
1056 case GPD_STARTF_FLAGS:
1057 case GPD_PARENT:
1058 case GPD_FLAGS:
1059 ERR_(win32)("Not allowed to modify offset %d\n", offset );
1060 break;
1062 case GPD_USERDATA:
1063 current_process.process_dword = value;
1064 break;
1066 default:
1067 ERR_(win32)("Unknown offset %d\n", offset );
1068 break;
1073 /*********************************************************************
1074 * OpenProcess (KERNEL32.@)
1076 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
1078 HANDLE ret = 0;
1079 SERVER_START_REQ( open_process )
1081 req->pid = (void *)id;
1082 req->access = access;
1083 req->inherit = inherit;
1084 if (!SERVER_CALL_ERR()) ret = req->handle;
1086 SERVER_END_REQ;
1087 return ret;
1090 /*********************************************************************
1091 * MapProcessHandle (KERNEL.483)
1093 DWORD WINAPI MapProcessHandle( HANDLE handle )
1095 DWORD ret = 0;
1096 SERVER_START_REQ( get_process_info )
1098 req->handle = handle;
1099 if (!SERVER_CALL_ERR()) ret = (DWORD)req->pid;
1101 SERVER_END_REQ;
1102 return ret;
1105 /***********************************************************************
1106 * SetPriorityClass (KERNEL32.@)
1108 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
1110 BOOL ret;
1111 SERVER_START_REQ( set_process_info )
1113 req->handle = hprocess;
1114 req->priority = priorityclass;
1115 req->mask = SET_PROCESS_INFO_PRIORITY;
1116 ret = !SERVER_CALL_ERR();
1118 SERVER_END_REQ;
1119 return ret;
1123 /***********************************************************************
1124 * GetPriorityClass (KERNEL32.@)
1126 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
1128 DWORD ret = 0;
1129 SERVER_START_REQ( get_process_info )
1131 req->handle = hprocess;
1132 if (!SERVER_CALL_ERR()) ret = req->priority;
1134 SERVER_END_REQ;
1135 return ret;
1139 /***********************************************************************
1140 * SetProcessAffinityMask (KERNEL32.@)
1142 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
1144 BOOL ret;
1145 SERVER_START_REQ( set_process_info )
1147 req->handle = hProcess;
1148 req->affinity = affmask;
1149 req->mask = SET_PROCESS_INFO_AFFINITY;
1150 ret = !SERVER_CALL_ERR();
1152 SERVER_END_REQ;
1153 return ret;
1156 /**********************************************************************
1157 * GetProcessAffinityMask (KERNEL32.@)
1159 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
1160 LPDWORD lpProcessAffinityMask,
1161 LPDWORD lpSystemAffinityMask )
1163 BOOL ret = FALSE;
1164 SERVER_START_REQ( get_process_info )
1166 req->handle = hProcess;
1167 if (!SERVER_CALL_ERR())
1169 if (lpProcessAffinityMask) *lpProcessAffinityMask = req->process_affinity;
1170 if (lpSystemAffinityMask) *lpSystemAffinityMask = req->system_affinity;
1171 ret = TRUE;
1174 SERVER_END_REQ;
1175 return ret;
1179 /***********************************************************************
1180 * GetProcessVersion (KERNEL32.@)
1182 DWORD WINAPI GetProcessVersion( DWORD processid )
1184 IMAGE_NT_HEADERS *nt;
1186 if (processid && processid != GetCurrentProcessId())
1188 FIXME("should use ReadProcessMemory\n");
1189 return 0;
1191 if ((nt = RtlImageNtHeader( current_process.module )))
1192 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
1193 nt->OptionalHeader.MinorSubsystemVersion);
1194 return 0;
1197 /***********************************************************************
1198 * GetProcessFlags (KERNEL32.@)
1200 DWORD WINAPI GetProcessFlags( DWORD processid )
1202 if (processid && processid != GetCurrentProcessId()) return 0;
1203 return current_process.flags;
1207 /***********************************************************************
1208 * SetProcessWorkingSetSize [KERNEL32.@]
1209 * Sets the min/max working set sizes for a specified process.
1211 * PARAMS
1212 * hProcess [I] Handle to the process of interest
1213 * minset [I] Specifies minimum working set size
1214 * maxset [I] Specifies maximum working set size
1216 * RETURNS STD
1218 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess,DWORD minset,
1219 DWORD maxset)
1221 FIXME("(0x%08x,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
1222 if(( minset == (DWORD)-1) && (maxset == (DWORD)-1)) {
1223 /* Trim the working set to zero */
1224 /* Swap the process out of physical RAM */
1226 return TRUE;
1229 /***********************************************************************
1230 * GetProcessWorkingSetSize (KERNEL32.@)
1232 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess,LPDWORD minset,
1233 LPDWORD maxset)
1235 FIXME("(0x%08x,%p,%p): stub\n",hProcess,minset,maxset);
1236 /* 32 MB working set size */
1237 if (minset) *minset = 32*1024*1024;
1238 if (maxset) *maxset = 32*1024*1024;
1239 return TRUE;
1242 /***********************************************************************
1243 * SetProcessShutdownParameters (KERNEL32.@)
1245 * CHANGED - James Sutherland (JamesSutherland@gmx.de)
1246 * Now tracks changes made (but does not act on these changes)
1248 static DWORD shutdown_flags = 0;
1249 static DWORD shutdown_priority = 0x280;
1251 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
1253 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
1254 shutdown_flags = flags;
1255 shutdown_priority = level;
1256 return TRUE;
1260 /***********************************************************************
1261 * GetProcessShutdownParameters (KERNEL32.@)
1264 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
1266 *lpdwLevel = shutdown_priority;
1267 *lpdwFlags = shutdown_flags;
1268 return TRUE;
1272 /***********************************************************************
1273 * SetProcessPriorityBoost (KERNEL32.@)
1275 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
1277 FIXME("(%d,%d): stub\n",hprocess,disableboost);
1278 /* Say we can do it. I doubt the program will notice that we don't. */
1279 return TRUE;
1283 /***********************************************************************
1284 * ReadProcessMemory (KERNEL32.@)
1286 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, DWORD size,
1287 LPDWORD bytes_read )
1289 unsigned int offset = (unsigned int)addr % sizeof(int);
1290 unsigned int pos = 0, len, max;
1291 int res;
1293 if (bytes_read) *bytes_read = size;
1295 /* first time, read total length to check for permissions */
1296 len = (size + offset + sizeof(int) - 1) / sizeof(int);
1297 max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1299 for (;;)
1301 SERVER_START_VAR_REQ( read_process_memory, max )
1303 req->handle = process;
1304 req->addr = (char *)addr + pos - offset;
1305 req->len = len;
1306 if (!(res = SERVER_CALL_ERR()))
1308 size_t result = server_data_size( req );
1309 if (result > size + offset) result = size + offset;
1310 memcpy( (char *)buffer + pos, server_data_ptr(req) + offset, result - offset );
1311 size -= result - offset;
1312 pos += result - offset;
1315 SERVER_END_VAR_REQ;
1316 if (res)
1318 if (bytes_read) *bytes_read = 0;
1319 return FALSE;
1321 if (!size) return TRUE;
1322 max = min( REQUEST_MAX_VAR_SIZE, size );
1323 len = (max + sizeof(int) - 1) / sizeof(int);
1324 offset = 0;
1329 /***********************************************************************
1330 * WriteProcessMemory (KERNEL32.@)
1332 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPVOID buffer, DWORD size,
1333 LPDWORD bytes_written )
1335 unsigned int first_offset, last_offset;
1336 unsigned int pos = 0, len, max, first_mask, last_mask;
1337 int res;
1339 if (!size)
1341 SetLastError( ERROR_INVALID_PARAMETER );
1342 return FALSE;
1344 if (bytes_written) *bytes_written = size;
1346 /* compute the mask for the first int */
1347 first_mask = ~0;
1348 first_offset = (unsigned int)addr % sizeof(int);
1349 memset( &first_mask, 0, first_offset );
1351 /* compute the mask for the last int */
1352 last_offset = (size + first_offset) % sizeof(int);
1353 last_mask = 0;
1354 memset( &last_mask, 0xff, last_offset ? last_offset : sizeof(int) );
1356 /* for the first request, use the total length */
1357 len = (size + first_offset + sizeof(int) - 1) / sizeof(int);
1358 max = min( REQUEST_MAX_VAR_SIZE, len * sizeof(int) );
1360 for (;;)
1362 SERVER_START_VAR_REQ( write_process_memory, max )
1364 req->handle = process;
1365 req->addr = (char *)addr - first_offset + pos;
1366 req->len = len;
1367 req->first_mask = (!pos) ? first_mask : ~0;
1368 if (size + first_offset <= max) /* last round */
1370 req->last_mask = last_mask;
1371 max = size + first_offset;
1373 else req->last_mask = ~0;
1375 memcpy( (char *)server_data_ptr(req) + first_offset, (char *)buffer + pos,
1376 max - first_offset );
1377 if (!(res = SERVER_CALL_ERR()))
1379 pos += max - first_offset;
1380 size -= max - first_offset;
1383 SERVER_END_VAR_REQ;
1384 if (res)
1386 if (bytes_written) *bytes_written = 0;
1387 return FALSE;
1389 if (!size) return TRUE;
1390 first_offset = 0;
1391 len = min( size + sizeof(int) - 1, REQUEST_MAX_VAR_SIZE ) / sizeof(int);
1392 max = len * sizeof(int);
1397 /***********************************************************************
1398 * RegisterServiceProcess (KERNEL.491)
1399 * RegisterServiceProcess (KERNEL32.@)
1401 * A service process calls this function to ensure that it continues to run
1402 * even after a user logged off.
1404 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
1406 /* I don't think that Wine needs to do anything in that function */
1407 return 1; /* success */
1410 /***********************************************************************
1411 * GetExitCodeProcess [KERNEL32.@]
1413 * Gets termination status of specified process
1415 * RETURNS
1416 * Success: TRUE
1417 * Failure: FALSE
1419 BOOL WINAPI GetExitCodeProcess(
1420 HANDLE hProcess, /* [in] handle to the process */
1421 LPDWORD lpExitCode) /* [out] address to receive termination status */
1423 BOOL ret;
1424 SERVER_START_REQ( get_process_info )
1426 req->handle = hProcess;
1427 ret = !SERVER_CALL_ERR();
1428 if (ret && lpExitCode) *lpExitCode = req->exit_code;
1430 SERVER_END_REQ;
1431 return ret;
1435 /***********************************************************************
1436 * SetErrorMode (KERNEL32.@)
1438 UINT WINAPI SetErrorMode( UINT mode )
1440 UINT old = current_process.error_mode;
1441 current_process.error_mode = mode;
1442 return old;
1446 /**************************************************************************
1447 * SetFileApisToOEM (KERNEL32.@)
1449 VOID WINAPI SetFileApisToOEM(void)
1451 current_process.flags |= PDB32_FILE_APIS_OEM;
1455 /**************************************************************************
1456 * SetFileApisToANSI (KERNEL32.@)
1458 VOID WINAPI SetFileApisToANSI(void)
1460 current_process.flags &= ~PDB32_FILE_APIS_OEM;
1464 /******************************************************************************
1465 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
1467 * RETURNS
1468 * TRUE: Set of file functions is using ANSI code page
1469 * FALSE: Set of file functions is using OEM code page
1471 BOOL WINAPI AreFileApisANSI(void)
1473 return !(current_process.flags & PDB32_FILE_APIS_OEM);
1477 /**********************************************************************
1478 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1480 * Allocates a thread local storage index
1482 * RETURNS
1483 * Success: TLS Index
1484 * Failure: 0xFFFFFFFF
1486 DWORD WINAPI TlsAlloc( void )
1488 DWORD i, mask, ret = 0;
1489 DWORD *bits = current_process.tls_bits;
1490 RtlAcquirePebLock();
1491 if (*bits == 0xffffffff)
1493 bits++;
1494 ret = 32;
1495 if (*bits == 0xffffffff)
1497 RtlReleasePebLock();
1498 SetLastError( ERROR_NO_MORE_ITEMS );
1499 return 0xffffffff;
1502 for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
1503 *bits |= mask;
1504 RtlReleasePebLock();
1505 return ret + i;
1509 /**********************************************************************
1510 * TlsFree [KERNEL32.@] Releases a TLS index.
1512 * Releases a thread local storage index, making it available for reuse
1514 * RETURNS
1515 * Success: TRUE
1516 * Failure: FALSE
1518 BOOL WINAPI TlsFree(
1519 DWORD index) /* [in] TLS Index to free */
1521 DWORD mask = (1 << (index & 31));
1522 DWORD *bits = current_process.tls_bits;
1523 if (index >= 64)
1525 SetLastError( ERROR_INVALID_PARAMETER );
1526 return FALSE;
1528 if (index >= 32) bits++;
1529 RtlAcquirePebLock();
1530 if (!(*bits & mask)) /* already free? */
1532 RtlReleasePebLock();
1533 SetLastError( ERROR_INVALID_PARAMETER );
1534 return FALSE;
1536 *bits &= ~mask;
1537 NtCurrentTeb()->tls_array[index] = 0;
1538 /* FIXME: should zero all other thread values */
1539 RtlReleasePebLock();
1540 return TRUE;
1544 /**********************************************************************
1545 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1547 * RETURNS
1548 * Success: Value stored in calling thread's TLS slot for index
1549 * Failure: 0 and GetLastError returns NO_ERROR
1551 LPVOID WINAPI TlsGetValue(
1552 DWORD index) /* [in] TLS index to retrieve value for */
1554 if (index >= 64)
1556 SetLastError( ERROR_INVALID_PARAMETER );
1557 return NULL;
1559 SetLastError( ERROR_SUCCESS );
1560 return NtCurrentTeb()->tls_array[index];
1564 /**********************************************************************
1565 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1567 * RETURNS
1568 * Success: TRUE
1569 * Failure: FALSE
1571 BOOL WINAPI TlsSetValue(
1572 DWORD index, /* [in] TLS index to set value for */
1573 LPVOID value) /* [in] Value to be stored */
1575 if (index >= 64)
1577 SetLastError( ERROR_INVALID_PARAMETER );
1578 return FALSE;
1580 NtCurrentTeb()->tls_array[index] = value;
1581 return TRUE;
1585 /***********************************************************************
1586 * GetCurrentProcess (KERNEL32.@)
1588 #undef GetCurrentProcess
1589 HANDLE WINAPI GetCurrentProcess(void)
1591 return 0xffffffff;