ntdll: Move the LDT section to ntdll and make it an uninterruptible section.
[wine/multimedia.git] / dlls / ntdll / thread.c
blob4d9919584904217c39dd624797109dd774d569e7
1 /*
2 * NT threads support
4 * Copyright 1996, 2003 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <sys/types.h>
26 #ifdef HAVE_SYS_MMAN_H
27 #include <sys/mman.h>
28 #endif
29 #ifdef HAVE_SYS_TIMES_H
30 #include <sys/times.h>
31 #endif
33 #define NONAMELESSUNION
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "thread.h"
37 #include "winternl.h"
38 #include "wine/library.h"
39 #include "wine/server.h"
40 #include "wine/pthread.h"
41 #include "wine/debug.h"
42 #include "ntdll_misc.h"
43 #include "wine/exception.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(thread);
47 /* info passed to a starting thread */
48 struct startup_info
50 struct wine_pthread_thread_info pthread_info;
51 PRTL_THREAD_START_ROUTINE entry_point;
52 void *entry_arg;
55 static PEB_LDR_DATA ldr;
56 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
57 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
58 static RTL_BITMAP tls_bitmap;
59 static RTL_BITMAP tls_expansion_bitmap;
60 static LIST_ENTRY tls_links;
61 static size_t sigstack_total_size;
62 static ULONG sigstack_zero_bits;
64 struct wine_pthread_functions pthread_functions = { NULL };
67 static RTL_CRITICAL_SECTION ldt_section;
68 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
70 0, 0, &ldt_section,
71 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
72 0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
74 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
75 static sigset_t ldt_sigset;
77 /***********************************************************************
78 * locking for LDT routines
80 static void ldt_lock(void)
82 sigset_t sigset;
84 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
85 RtlEnterCriticalSection( &ldt_section );
86 if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
89 static void ldt_unlock(void)
91 if (ldt_section.RecursionCount == 1)
93 sigset_t sigset = ldt_sigset;
94 RtlLeaveCriticalSection( &ldt_section );
95 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
97 else RtlLeaveCriticalSection( &ldt_section );
101 /***********************************************************************
102 * init_teb
104 static inline NTSTATUS init_teb( TEB *teb )
106 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
107 struct ntdll_thread_regs *thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
109 teb->Tib.ExceptionList = (void *)~0UL;
110 teb->Tib.StackBase = (void *)~0UL;
111 teb->Tib.Self = &teb->Tib;
112 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
113 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
115 if (!(thread_regs->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
116 thread_data->request_fd = -1;
117 thread_data->reply_fd = -1;
118 thread_data->wait_fd[0] = -1;
119 thread_data->wait_fd[1] = -1;
121 return STATUS_SUCCESS;
125 /***********************************************************************
126 * fix_unicode_string
128 * Make sure the unicode string doesn't point beyond the end pointer
130 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
132 if ((char *)str->Buffer >= end_ptr)
134 str->Length = str->MaximumLength = 0;
135 str->Buffer = NULL;
136 return;
138 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
140 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
142 if (str->Length >= str->MaximumLength)
144 if (str->MaximumLength >= sizeof(WCHAR))
145 str->Length = str->MaximumLength - sizeof(WCHAR);
146 else
147 str->Length = str->MaximumLength = 0;
152 /***********************************************************************
153 * init_user_process_params
155 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
157 static NTSTATUS init_user_process_params( SIZE_T info_size, HANDLE *exe_file )
159 void *ptr;
160 SIZE_T env_size;
161 NTSTATUS status;
162 RTL_USER_PROCESS_PARAMETERS *params = NULL;
164 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &info_size,
165 MEM_COMMIT, PAGE_READWRITE );
166 if (status != STATUS_SUCCESS) return status;
168 params->AllocationSize = info_size;
169 NtCurrentTeb()->Peb->ProcessParameters = params;
171 SERVER_START_REQ( get_startup_info )
173 wine_server_set_reply( req, params, info_size );
174 if (!(status = wine_server_call( req )))
176 info_size = wine_server_reply_size( reply );
177 *exe_file = reply->exe_file;
178 params->hStdInput = reply->hstdin;
179 params->hStdOutput = reply->hstdout;
180 params->hStdError = reply->hstderr;
183 SERVER_END_REQ;
184 if (status != STATUS_SUCCESS) return status;
186 if (params->Size > info_size) params->Size = info_size;
188 /* make sure the strings are valid */
189 fix_unicode_string( &params->CurrentDirectory.DosPath, (char *)info_size );
190 fix_unicode_string( &params->DllPath, (char *)info_size );
191 fix_unicode_string( &params->ImagePathName, (char *)info_size );
192 fix_unicode_string( &params->CommandLine, (char *)info_size );
193 fix_unicode_string( &params->WindowTitle, (char *)info_size );
194 fix_unicode_string( &params->Desktop, (char *)info_size );
195 fix_unicode_string( &params->ShellInfo, (char *)info_size );
196 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
198 /* environment needs to be a separate memory block */
199 env_size = info_size - params->Size;
200 if (!env_size) env_size = 1;
201 ptr = NULL;
202 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
203 MEM_COMMIT, PAGE_READWRITE );
204 if (status != STATUS_SUCCESS) return status;
205 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
206 params->Environment = ptr;
208 RtlNormalizeProcessParams( params );
209 return status;
213 /***********************************************************************
214 * thread_init
216 * Setup the initial thread.
218 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
220 HANDLE thread_init(void)
222 PEB *peb;
223 TEB *teb;
224 void *addr;
225 SIZE_T size, info_size;
226 HANDLE exe_file = 0;
227 struct ntdll_thread_data *thread_data;
228 struct ntdll_thread_regs *thread_regs;
229 struct wine_pthread_thread_info thread_info;
230 static struct debug_info debug_info; /* debug info for initial thread */
232 virtual_init();
234 /* reserve space for shared user data */
236 addr = (void *)0x7ffe0000;
237 size = 0x10000;
238 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE, PAGE_READONLY );
240 /* allocate and initialize the PEB */
242 addr = NULL;
243 size = sizeof(*peb);
244 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
245 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
246 peb = addr;
248 peb->NumberOfProcessors = 1;
249 peb->ProcessParameters = &params;
250 peb->TlsBitmap = &tls_bitmap;
251 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
252 peb->LdrData = &ldr;
253 params.CurrentDirectory.DosPath.Buffer = current_dir;
254 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
255 params.wShowWindow = 1; /* SW_SHOWNORMAL */
256 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
257 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
258 sizeof(peb->TlsExpansionBitmapBits) * 8 );
259 InitializeListHead( &ldr.InLoadOrderModuleList );
260 InitializeListHead( &ldr.InMemoryOrderModuleList );
261 InitializeListHead( &ldr.InInitializationOrderModuleList );
262 InitializeListHead( &tls_links );
264 /* allocate and initialize the initial TEB */
266 sigstack_total_size = get_signal_stack_total_size();
267 while (1 << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
268 assert( 1 << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
269 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
270 thread_info.teb_size = sigstack_total_size;
272 addr = NULL;
273 size = sigstack_total_size;
274 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
275 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
276 teb = addr;
277 teb->Peb = peb;
278 thread_info.teb_size = size;
279 init_teb( teb );
280 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
281 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
282 thread_data->debug_info = &debug_info;
283 InsertHeadList( &tls_links, &teb->TlsLinks );
285 thread_info.stack_base = NULL;
286 thread_info.stack_size = 0;
287 thread_info.teb_base = teb;
288 thread_info.teb_sel = thread_regs->fs;
289 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
290 pthread_functions.init_current_teb( &thread_info );
291 pthread_functions.init_thread( &thread_info );
292 virtual_init_threading();
294 debug_info.str_pos = debug_info.strings;
295 debug_info.out_pos = debug_info.output;
296 debug_init();
298 /* setup the server connection */
299 server_init_process();
300 info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
302 /* create the process heap */
303 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
305 MESSAGE( "wine: failed to create the process heap\n" );
306 exit(1);
309 /* allocate user parameters */
310 if (info_size)
312 init_user_process_params( info_size, &exe_file );
314 else
316 /* This is wine specific: we have no parent (we're started from unix)
317 * so, create a simple console with bare handles to unix stdio
319 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, &params.hStdInput );
320 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
321 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
324 /* initialize LDT locking */
325 wine_ldt_init_locking( ldt_lock, ldt_unlock );
327 return exe_file;
330 typedef LONG (WINAPI *PUNHANDLED_EXCEPTION_FILTER)(PEXCEPTION_POINTERS);
331 static PUNHANDLED_EXCEPTION_FILTER get_unhandled_exception_filter(void)
333 static PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter;
334 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
335 UNICODE_STRING module_name;
336 ANSI_STRING func_name;
337 HMODULE kernel32_handle;
339 if (unhandled_exception_filter) return unhandled_exception_filter;
341 RtlInitUnicodeString(&module_name, kernel32W);
342 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
344 if (LdrGetDllHandle( 0, 0, &module_name, &kernel32_handle ) == STATUS_SUCCESS)
345 LdrGetProcedureAddress( kernel32_handle, &func_name, 0,
346 (void **)&unhandled_exception_filter );
348 return unhandled_exception_filter;
351 /***********************************************************************
352 * start_thread
354 * Startup routine for a newly created thread.
356 static void start_thread( struct wine_pthread_thread_info *info )
358 TEB *teb = info->teb_base;
359 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
360 struct startup_info *startup_info = (struct startup_info *)info;
361 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
362 void *arg = startup_info->entry_arg;
363 struct debug_info debug_info;
364 SIZE_T size, page_size = getpagesize();
366 debug_info.str_pos = debug_info.strings;
367 debug_info.out_pos = debug_info.output;
368 thread_data->debug_info = &debug_info;
370 pthread_functions.init_current_teb( info );
371 SIGNAL_Init();
372 server_init_thread( info->pid, info->tid, func );
373 pthread_functions.init_thread( info );
375 /* allocate a memory view for the stack */
376 size = info->stack_size;
377 teb->DeallocationStack = info->stack_base;
378 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
379 &size, MEM_SYSTEM, PAGE_READWRITE );
380 /* limit is lower than base since the stack grows down */
381 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
382 teb->Tib.StackLimit = (char *)info->stack_base + page_size;
384 /* setup the guard page */
385 size = page_size;
386 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, PAGE_NOACCESS, NULL );
388 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
390 RtlAcquirePebLock();
391 InsertHeadList( &tls_links, &teb->TlsLinks );
392 RtlReleasePebLock();
394 /* NOTE: Windows does not have an exception handler around the call to
395 * the thread attach. We do for ease of debugging */
396 if (get_unhandled_exception_filter())
398 __TRY
400 MODULE_DllThreadAttach( NULL );
402 __EXCEPT(get_unhandled_exception_filter())
404 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
406 __ENDTRY
408 else
409 MODULE_DllThreadAttach( NULL );
411 func( arg );
415 /***********************************************************************
416 * RtlCreateUserThread (NTDLL.@)
418 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
419 BOOLEAN suspended, PVOID stack_addr,
420 SIZE_T stack_reserve, SIZE_T stack_commit,
421 PRTL_THREAD_START_ROUTINE start, void *param,
422 HANDLE *handle_ptr, CLIENT_ID *id )
424 sigset_t sigset;
425 struct ntdll_thread_data *thread_data;
426 struct ntdll_thread_regs *thread_regs = NULL;
427 struct startup_info *info = NULL;
428 void *addr = NULL;
429 HANDLE handle = 0;
430 TEB *teb;
431 DWORD tid = 0;
432 int request_pipe[2];
433 NTSTATUS status;
434 SIZE_T size, page_size = getpagesize();
436 if( ! is_current_process( process ) )
438 ERR("Unsupported on other process\n");
439 return STATUS_ACCESS_DENIED;
442 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
443 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
444 wine_server_send_fd( request_pipe[0] );
446 SERVER_START_REQ( new_thread )
448 req->access = THREAD_ALL_ACCESS;
449 req->attributes = 0; /* FIXME */
450 req->suspend = suspended;
451 req->request_fd = request_pipe[0];
452 if (!(status = wine_server_call( req )))
454 handle = reply->handle;
455 tid = reply->tid;
457 close( request_pipe[0] );
459 SERVER_END_REQ;
461 if (status)
463 close( request_pipe[1] );
464 return status;
467 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
469 addr = NULL;
470 size = sigstack_total_size;
471 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
472 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
473 goto error;
474 teb = addr;
475 teb->Peb = NtCurrentTeb()->Peb;
476 info = (struct startup_info *)(teb + 1);
477 info->pthread_info.teb_size = size;
478 if ((status = init_teb( teb ))) goto error;
480 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
481 teb->ClientId.UniqueThread = (HANDLE)tid;
483 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
484 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
485 thread_data->request_fd = request_pipe[1];
487 info->pthread_info.teb_base = teb;
488 info->pthread_info.teb_sel = thread_regs->fs;
490 /* inherit debug registers from parent thread */
491 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
492 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
493 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
494 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
495 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
496 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
498 if (!stack_reserve || !stack_commit)
500 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
501 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
502 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
504 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
505 stack_reserve += page_size; /* for the guard page */
506 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
507 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
509 info->pthread_info.stack_base = NULL;
510 info->pthread_info.stack_size = stack_reserve;
511 info->pthread_info.entry = start_thread;
512 info->entry_point = start;
513 info->entry_arg = param;
515 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
517 status = STATUS_NO_MEMORY;
518 goto error;
520 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
522 if (id) id->UniqueThread = (HANDLE)tid;
523 if (handle_ptr) *handle_ptr = handle;
524 else NtClose( handle );
526 return STATUS_SUCCESS;
528 error:
529 if (thread_regs) wine_ldt_free_fs( thread_regs->fs );
530 if (addr)
532 SIZE_T size = 0;
533 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
535 if (handle) NtClose( handle );
536 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
537 close( request_pipe[1] );
538 return status;
542 /***********************************************************************
543 * RtlExitUserThread (NTDLL.@)
545 void WINAPI RtlExitUserThread( ULONG status )
547 LdrShutdownThread();
548 server_exit_thread( status );
552 /***********************************************************************
553 * NtOpenThread (NTDLL.@)
554 * ZwOpenThread (NTDLL.@)
556 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
557 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
559 NTSTATUS ret;
561 SERVER_START_REQ( open_thread )
563 req->tid = (thread_id_t)id->UniqueThread;
564 req->access = access;
565 req->attributes = attr ? attr->Attributes : 0;
566 ret = wine_server_call( req );
567 *handle = reply->handle;
569 SERVER_END_REQ;
570 return ret;
574 /******************************************************************************
575 * NtSuspendThread (NTDLL.@)
576 * ZwSuspendThread (NTDLL.@)
578 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
580 NTSTATUS ret;
582 SERVER_START_REQ( suspend_thread )
584 req->handle = handle;
585 if (!(ret = wine_server_call( req ))) *count = reply->count;
587 SERVER_END_REQ;
588 return ret;
592 /******************************************************************************
593 * NtResumeThread (NTDLL.@)
594 * ZwResumeThread (NTDLL.@)
596 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
598 NTSTATUS ret;
600 SERVER_START_REQ( resume_thread )
602 req->handle = handle;
603 if (!(ret = wine_server_call( req ))) *count = reply->count;
605 SERVER_END_REQ;
606 return ret;
610 /******************************************************************************
611 * NtAlertResumeThread (NTDLL.@)
612 * ZwAlertResumeThread (NTDLL.@)
614 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
616 FIXME( "stub: should alert thread %p\n", handle );
617 return NtResumeThread( handle, count );
621 /******************************************************************************
622 * NtAlertThread (NTDLL.@)
623 * ZwAlertThread (NTDLL.@)
625 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
627 FIXME( "stub: %p\n", handle );
628 return STATUS_NOT_IMPLEMENTED;
632 /******************************************************************************
633 * NtTerminateThread (NTDLL.@)
634 * ZwTerminateThread (NTDLL.@)
636 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
638 NTSTATUS ret;
639 BOOL self, last;
641 SERVER_START_REQ( terminate_thread )
643 req->handle = handle;
644 req->exit_code = exit_code;
645 ret = wine_server_call( req );
646 self = !ret && reply->self;
647 last = reply->last;
649 SERVER_END_REQ;
651 if (self)
653 if (last) exit( exit_code );
654 else server_abort_thread( exit_code );
656 return ret;
660 /******************************************************************************
661 * NtQueueApcThread (NTDLL.@)
663 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
664 ULONG_PTR arg2, ULONG_PTR arg3 )
666 NTSTATUS ret;
667 SERVER_START_REQ( queue_apc )
669 req->thread = handle;
670 if (func)
672 req->call.type = APC_USER;
673 req->call.user.func = func;
674 req->call.user.args[0] = arg1;
675 req->call.user.args[1] = arg2;
676 req->call.user.args[2] = arg3;
678 else req->call.type = APC_NONE; /* wake up only */
679 ret = wine_server_call( req );
681 SERVER_END_REQ;
682 return ret;
686 /***********************************************************************
687 * NtSetContextThread (NTDLL.@)
688 * ZwSetContextThread (NTDLL.@)
690 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
692 NTSTATUS ret;
693 DWORD dummy, i;
694 BOOL self = FALSE;
696 #ifdef __i386__
697 /* on i386 debug registers always require a server call */
698 self = (handle == GetCurrentThread());
699 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
701 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
702 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
703 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
704 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
706 #endif
708 if (!self)
710 SERVER_START_REQ( set_thread_context )
712 req->handle = handle;
713 req->flags = context->ContextFlags;
714 req->suspend = 0;
715 wine_server_add_data( req, context, sizeof(*context) );
716 ret = wine_server_call( req );
717 self = reply->self;
719 SERVER_END_REQ;
721 if (ret == STATUS_PENDING)
723 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
725 for (i = 0; i < 100; i++)
727 SERVER_START_REQ( set_thread_context )
729 req->handle = handle;
730 req->flags = context->ContextFlags;
731 req->suspend = 0;
732 wine_server_add_data( req, context, sizeof(*context) );
733 ret = wine_server_call( req );
735 SERVER_END_REQ;
736 if (ret != STATUS_PENDING) break;
737 NtYieldExecution();
739 NtResumeThread( handle, &dummy );
741 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
744 if (ret) return ret;
747 if (self) set_cpu_context( context );
748 return STATUS_SUCCESS;
752 /* copy a context structure according to the flags */
753 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
755 #ifdef __i386__
756 flags &= ~CONTEXT_i386; /* get rid of CPU id */
757 if (flags & CONTEXT_INTEGER)
759 to->Eax = from->Eax;
760 to->Ebx = from->Ebx;
761 to->Ecx = from->Ecx;
762 to->Edx = from->Edx;
763 to->Esi = from->Esi;
764 to->Edi = from->Edi;
766 if (flags & CONTEXT_CONTROL)
768 to->Ebp = from->Ebp;
769 to->Esp = from->Esp;
770 to->Eip = from->Eip;
771 to->SegCs = from->SegCs;
772 to->SegSs = from->SegSs;
773 to->EFlags = from->EFlags;
775 if (flags & CONTEXT_SEGMENTS)
777 to->SegDs = from->SegDs;
778 to->SegEs = from->SegEs;
779 to->SegFs = from->SegFs;
780 to->SegGs = from->SegGs;
782 if (flags & CONTEXT_DEBUG_REGISTERS)
784 to->Dr0 = from->Dr0;
785 to->Dr1 = from->Dr1;
786 to->Dr2 = from->Dr2;
787 to->Dr3 = from->Dr3;
788 to->Dr6 = from->Dr6;
789 to->Dr7 = from->Dr7;
791 if (flags & CONTEXT_FLOATING_POINT)
793 to->FloatSave = from->FloatSave;
795 #elif defined(__x86_64__)
796 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
797 if (flags & CONTEXT_CONTROL)
799 to->Rbp = from->Rbp;
800 to->Rip = from->Rip;
801 to->Rsp = from->Rsp;
802 to->SegCs = from->SegCs;
803 to->SegSs = from->SegSs;
804 to->EFlags = from->EFlags;
805 to->MxCsr = from->MxCsr;
807 if (flags & CONTEXT_INTEGER)
809 to->Rax = from->Rax;
810 to->Rcx = from->Rcx;
811 to->Rdx = from->Rdx;
812 to->Rbx = from->Rbx;
813 to->Rsi = from->Rsi;
814 to->Rdi = from->Rdi;
815 to->R8 = from->R8;
816 to->R9 = from->R9;
817 to->R10 = from->R10;
818 to->R11 = from->R11;
819 to->R12 = from->R12;
820 to->R13 = from->R13;
821 to->R14 = from->R14;
822 to->R15 = from->R15;
824 if (flags & CONTEXT_SEGMENTS)
826 to->SegDs = from->SegDs;
827 to->SegEs = from->SegEs;
828 to->SegFs = from->SegFs;
829 to->SegGs = from->SegGs;
831 if (flags & CONTEXT_FLOATING_POINT)
833 to->u.FltSave = from->u.FltSave;
835 if (flags & CONTEXT_DEBUG_REGISTERS)
837 to->Dr0 = from->Dr0;
838 to->Dr1 = from->Dr1;
839 to->Dr2 = from->Dr2;
840 to->Dr3 = from->Dr3;
841 to->Dr6 = from->Dr6;
842 to->Dr7 = from->Dr7;
844 #elif defined(__sparc__)
845 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
846 if (flags & CONTEXT_CONTROL)
848 to->psr = from->psr;
849 to->pc = from->pc;
850 to->npc = from->npc;
851 to->y = from->y;
852 to->wim = from->wim;
853 to->tbr = from->tbr;
855 if (flags & CONTEXT_INTEGER)
857 to->g0 = from->g0;
858 to->g1 = from->g1;
859 to->g2 = from->g2;
860 to->g3 = from->g3;
861 to->g4 = from->g4;
862 to->g5 = from->g5;
863 to->g6 = from->g6;
864 to->g7 = from->g7;
865 to->o0 = from->o0;
866 to->o1 = from->o1;
867 to->o2 = from->o2;
868 to->o3 = from->o3;
869 to->o4 = from->o4;
870 to->o5 = from->o5;
871 to->o6 = from->o6;
872 to->o7 = from->o7;
873 to->l0 = from->l0;
874 to->l1 = from->l1;
875 to->l2 = from->l2;
876 to->l3 = from->l3;
877 to->l4 = from->l4;
878 to->l5 = from->l5;
879 to->l6 = from->l6;
880 to->l7 = from->l7;
881 to->i0 = from->i0;
882 to->i1 = from->i1;
883 to->i2 = from->i2;
884 to->i3 = from->i3;
885 to->i4 = from->i4;
886 to->i5 = from->i5;
887 to->i6 = from->i6;
888 to->i7 = from->i7;
890 if (flags & CONTEXT_FLOATING_POINT)
892 /* FIXME */
894 #elif defined(__powerpc__)
895 /* Has no CPU id */
896 if (flags & CONTEXT_CONTROL)
898 to->Msr = from->Msr;
899 to->Ctr = from->Ctr;
900 to->Iar = from->Iar;
902 if (flags & CONTEXT_INTEGER)
904 to->Gpr0 = from->Gpr0;
905 to->Gpr1 = from->Gpr1;
906 to->Gpr2 = from->Gpr2;
907 to->Gpr3 = from->Gpr3;
908 to->Gpr4 = from->Gpr4;
909 to->Gpr5 = from->Gpr5;
910 to->Gpr6 = from->Gpr6;
911 to->Gpr7 = from->Gpr7;
912 to->Gpr8 = from->Gpr8;
913 to->Gpr9 = from->Gpr9;
914 to->Gpr10 = from->Gpr10;
915 to->Gpr11 = from->Gpr11;
916 to->Gpr12 = from->Gpr12;
917 to->Gpr13 = from->Gpr13;
918 to->Gpr14 = from->Gpr14;
919 to->Gpr15 = from->Gpr15;
920 to->Gpr16 = from->Gpr16;
921 to->Gpr17 = from->Gpr17;
922 to->Gpr18 = from->Gpr18;
923 to->Gpr19 = from->Gpr19;
924 to->Gpr20 = from->Gpr20;
925 to->Gpr21 = from->Gpr21;
926 to->Gpr22 = from->Gpr22;
927 to->Gpr23 = from->Gpr23;
928 to->Gpr24 = from->Gpr24;
929 to->Gpr25 = from->Gpr25;
930 to->Gpr26 = from->Gpr26;
931 to->Gpr27 = from->Gpr27;
932 to->Gpr28 = from->Gpr28;
933 to->Gpr29 = from->Gpr29;
934 to->Gpr30 = from->Gpr30;
935 to->Gpr31 = from->Gpr31;
936 to->Xer = from->Xer;
937 to->Cr = from->Cr;
939 if (flags & CONTEXT_FLOATING_POINT)
941 to->Fpr0 = from->Fpr0;
942 to->Fpr1 = from->Fpr1;
943 to->Fpr2 = from->Fpr2;
944 to->Fpr3 = from->Fpr3;
945 to->Fpr4 = from->Fpr4;
946 to->Fpr5 = from->Fpr5;
947 to->Fpr6 = from->Fpr6;
948 to->Fpr7 = from->Fpr7;
949 to->Fpr8 = from->Fpr8;
950 to->Fpr9 = from->Fpr9;
951 to->Fpr10 = from->Fpr10;
952 to->Fpr11 = from->Fpr11;
953 to->Fpr12 = from->Fpr12;
954 to->Fpr13 = from->Fpr13;
955 to->Fpr14 = from->Fpr14;
956 to->Fpr15 = from->Fpr15;
957 to->Fpr16 = from->Fpr16;
958 to->Fpr17 = from->Fpr17;
959 to->Fpr18 = from->Fpr18;
960 to->Fpr19 = from->Fpr19;
961 to->Fpr20 = from->Fpr20;
962 to->Fpr21 = from->Fpr21;
963 to->Fpr22 = from->Fpr22;
964 to->Fpr23 = from->Fpr23;
965 to->Fpr24 = from->Fpr24;
966 to->Fpr25 = from->Fpr25;
967 to->Fpr26 = from->Fpr26;
968 to->Fpr27 = from->Fpr27;
969 to->Fpr28 = from->Fpr28;
970 to->Fpr29 = from->Fpr29;
971 to->Fpr30 = from->Fpr30;
972 to->Fpr31 = from->Fpr31;
973 to->Fpscr = from->Fpscr;
975 #else
976 #error You must implement context copying for your CPU
977 #endif
981 /***********************************************************************
982 * NtGetContextThread (NTDLL.@)
983 * ZwGetContextThread (NTDLL.@)
985 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
987 NTSTATUS ret;
988 CONTEXT ctx;
989 DWORD dummy, i;
990 DWORD needed_flags = context->ContextFlags;
991 BOOL self = (handle == GetCurrentThread());
993 #ifdef __i386__
994 /* on i386 debug registers always require a server call */
995 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
996 #endif
998 if (!self)
1000 SERVER_START_REQ( get_thread_context )
1002 req->handle = handle;
1003 req->flags = context->ContextFlags;
1004 req->suspend = 0;
1005 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1006 ret = wine_server_call( req );
1007 self = reply->self;
1009 SERVER_END_REQ;
1011 if (ret == STATUS_PENDING)
1013 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
1015 for (i = 0; i < 100; i++)
1017 SERVER_START_REQ( get_thread_context )
1019 req->handle = handle;
1020 req->flags = context->ContextFlags;
1021 req->suspend = 0;
1022 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1023 ret = wine_server_call( req );
1025 SERVER_END_REQ;
1026 if (ret != STATUS_PENDING) break;
1027 NtYieldExecution();
1029 NtResumeThread( handle, &dummy );
1031 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1033 if (ret) return ret;
1034 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1035 needed_flags &= ~ctx.ContextFlags;
1038 if (self)
1040 if (needed_flags)
1042 get_cpu_context( &ctx );
1043 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1045 #ifdef __i386__
1046 /* update the cached version of the debug registers */
1047 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1049 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1050 regs->dr0 = context->Dr0;
1051 regs->dr1 = context->Dr1;
1052 regs->dr2 = context->Dr2;
1053 regs->dr3 = context->Dr3;
1054 regs->dr6 = context->Dr6;
1055 regs->dr7 = context->Dr7;
1057 #endif
1059 return STATUS_SUCCESS;
1063 /******************************************************************************
1064 * NtQueryInformationThread (NTDLL.@)
1065 * ZwQueryInformationThread (NTDLL.@)
1067 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1068 void *data, ULONG length, ULONG *ret_len )
1070 NTSTATUS status;
1072 switch(class)
1074 case ThreadBasicInformation:
1076 THREAD_BASIC_INFORMATION info;
1078 SERVER_START_REQ( get_thread_info )
1080 req->handle = handle;
1081 req->tid_in = 0;
1082 if (!(status = wine_server_call( req )))
1084 info.ExitStatus = reply->exit_code;
1085 info.TebBaseAddress = reply->teb;
1086 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
1087 info.ClientId.UniqueThread = (HANDLE)reply->tid;
1088 info.AffinityMask = reply->affinity;
1089 info.Priority = reply->priority;
1090 info.BasePriority = reply->priority; /* FIXME */
1093 SERVER_END_REQ;
1094 if (status == STATUS_SUCCESS)
1096 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1097 if (ret_len) *ret_len = min( length, sizeof(info) );
1100 return status;
1101 case ThreadTimes:
1103 KERNEL_USER_TIMES kusrt;
1104 /* We need to do a server call to get the creation time or exit time */
1105 /* This works on any thread */
1106 SERVER_START_REQ( get_thread_info )
1108 req->handle = handle;
1109 req->tid_in = 0;
1110 status = wine_server_call( req );
1111 if (status == STATUS_SUCCESS)
1113 NTDLL_from_server_abstime( &kusrt.CreateTime, &reply->creation_time );
1114 NTDLL_from_server_abstime( &kusrt.ExitTime, &reply->exit_time );
1117 SERVER_END_REQ;
1118 if (status == STATUS_SUCCESS)
1120 /* We call times(2) for kernel time or user time */
1121 /* We can only (portably) do this for the current thread */
1122 if (handle == GetCurrentThread())
1124 struct tms time_buf;
1125 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1127 times(&time_buf);
1128 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1129 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1131 else
1133 kusrt.KernelTime.QuadPart = 0;
1134 kusrt.UserTime.QuadPart = 0;
1135 FIXME("Cannot get kerneltime or usertime of other threads\n");
1137 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1138 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1141 return status;
1142 case ThreadDescriptorTableEntry:
1144 #ifdef __i386__
1145 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1146 if (length < sizeof(*tdi))
1147 status = STATUS_INFO_LENGTH_MISMATCH;
1148 else if (!(tdi->Selector & 4)) /* GDT selector */
1150 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1151 status = STATUS_SUCCESS;
1152 if (!sel) /* null selector */
1153 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1154 else
1156 tdi->Entry.BaseLow = 0;
1157 tdi->Entry.HighWord.Bits.BaseMid = 0;
1158 tdi->Entry.HighWord.Bits.BaseHi = 0;
1159 tdi->Entry.LimitLow = 0xffff;
1160 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1161 tdi->Entry.HighWord.Bits.Dpl = 3;
1162 tdi->Entry.HighWord.Bits.Sys = 0;
1163 tdi->Entry.HighWord.Bits.Pres = 1;
1164 tdi->Entry.HighWord.Bits.Granularity = 1;
1165 tdi->Entry.HighWord.Bits.Default_Big = 1;
1166 tdi->Entry.HighWord.Bits.Type = 0x12;
1167 /* it has to be one of the system GDT selectors */
1168 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1170 if (sel == (wine_get_cs() & ~3))
1171 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1172 else status = STATUS_ACCESS_DENIED;
1176 else
1178 SERVER_START_REQ( get_selector_entry )
1180 req->handle = handle;
1181 req->entry = tdi->Selector >> 3;
1182 status = wine_server_call( req );
1183 if (!status)
1185 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1186 status = STATUS_ACCESS_VIOLATION;
1187 else
1189 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1190 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1191 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1195 SERVER_END_REQ;
1197 if (status == STATUS_SUCCESS && ret_len)
1198 /* yes, that's a bit strange, but it's the way it is */
1199 *ret_len = sizeof(LDT_ENTRY);
1200 #else
1201 status = STATUS_NOT_IMPLEMENTED;
1202 #endif
1203 return status;
1205 case ThreadAmILastThread:
1207 SERVER_START_REQ(get_thread_info)
1209 req->handle = handle;
1210 req->tid_in = 0;
1211 status = wine_server_call( req );
1212 if (status == STATUS_SUCCESS)
1214 BOOLEAN last = reply->last;
1215 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1216 if (ret_len) *ret_len = min( length, sizeof(last) );
1219 SERVER_END_REQ;
1220 return status;
1222 case ThreadPriority:
1223 case ThreadBasePriority:
1224 case ThreadAffinityMask:
1225 case ThreadImpersonationToken:
1226 case ThreadEnableAlignmentFaultFixup:
1227 case ThreadEventPair_Reusable:
1228 case ThreadQuerySetWin32StartAddress:
1229 case ThreadZeroTlsCell:
1230 case ThreadPerformanceCount:
1231 case ThreadIdealProcessor:
1232 case ThreadPriorityBoost:
1233 case ThreadSetTlsArrayAddress:
1234 case ThreadIsIoPending:
1235 default:
1236 FIXME( "info class %d not supported yet\n", class );
1237 return STATUS_NOT_IMPLEMENTED;
1242 /******************************************************************************
1243 * NtSetInformationThread (NTDLL.@)
1244 * ZwSetInformationThread (NTDLL.@)
1246 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1247 LPCVOID data, ULONG length )
1249 NTSTATUS status;
1250 switch(class)
1252 case ThreadZeroTlsCell:
1253 if (handle == GetCurrentThread())
1255 LIST_ENTRY *entry;
1256 DWORD index;
1258 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1259 index = *(const DWORD *)data;
1260 if (index < TLS_MINIMUM_AVAILABLE)
1262 RtlAcquirePebLock();
1263 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1265 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1266 teb->TlsSlots[index] = 0;
1268 RtlReleasePebLock();
1270 else
1272 index -= TLS_MINIMUM_AVAILABLE;
1273 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1274 return STATUS_INVALID_PARAMETER;
1275 RtlAcquirePebLock();
1276 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1278 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1279 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1281 RtlReleasePebLock();
1283 return STATUS_SUCCESS;
1285 FIXME( "ZeroTlsCell not supported on other threads\n" );
1286 return STATUS_NOT_IMPLEMENTED;
1288 case ThreadImpersonationToken:
1290 const HANDLE *phToken = data;
1291 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1292 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1293 SERVER_START_REQ( set_thread_info )
1295 req->handle = handle;
1296 req->token = *phToken;
1297 req->mask = SET_THREAD_INFO_TOKEN;
1298 status = wine_server_call( req );
1300 SERVER_END_REQ;
1302 return status;
1303 case ThreadBasePriority:
1305 const DWORD *pprio = data;
1306 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1307 SERVER_START_REQ( set_thread_info )
1309 req->handle = handle;
1310 req->priority = *pprio;
1311 req->mask = SET_THREAD_INFO_PRIORITY;
1312 status = wine_server_call( req );
1314 SERVER_END_REQ;
1316 return status;
1317 case ThreadAffinityMask:
1319 const DWORD *paff = data;
1320 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1321 SERVER_START_REQ( set_thread_info )
1323 req->handle = handle;
1324 req->affinity = *paff;
1325 req->mask = SET_THREAD_INFO_AFFINITY;
1326 status = wine_server_call( req );
1328 SERVER_END_REQ;
1330 return status;
1331 case ThreadBasicInformation:
1332 case ThreadTimes:
1333 case ThreadPriority:
1334 case ThreadDescriptorTableEntry:
1335 case ThreadEnableAlignmentFaultFixup:
1336 case ThreadEventPair_Reusable:
1337 case ThreadQuerySetWin32StartAddress:
1338 case ThreadPerformanceCount:
1339 case ThreadAmILastThread:
1340 case ThreadIdealProcessor:
1341 case ThreadPriorityBoost:
1342 case ThreadSetTlsArrayAddress:
1343 case ThreadIsIoPending:
1344 default:
1345 FIXME( "info class %d not supported yet\n", class );
1346 return STATUS_NOT_IMPLEMENTED;
1351 /**********************************************************************
1352 * NtCurrentTeb (NTDLL.@)
1354 #if defined(__i386__) && defined(__GNUC__)
1356 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
1358 #elif defined(__i386__) && defined(_MSC_VER)
1360 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1362 #else
1364 /**********************************************************************/
1366 TEB * WINAPI NtCurrentTeb(void)
1368 return pthread_functions.get_current_teb();
1371 #endif /* __i386__ */