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
22 #include "wine/port.h"
25 #include <sys/types.h>
26 #ifdef HAVE_SYS_MMAN_H
29 #ifdef HAVE_SYS_TIMES_H
30 #include <sys/times.h>
33 #define NONAMELESSUNION
35 #define WIN32_NO_STATUS
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);
46 WINE_DECLARE_DEBUG_CHANNEL(relay);
48 /* info passed to a starting thread */
51 struct wine_pthread_thread_info pthread_info;
52 PRTL_THREAD_START_ROUTINE entry_point;
56 static PEB_LDR_DATA ldr;
57 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
58 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
59 static RTL_BITMAP tls_bitmap;
60 static RTL_BITMAP tls_expansion_bitmap;
61 static LIST_ENTRY tls_links;
62 static size_t sigstack_total_size;
63 static ULONG sigstack_zero_bits;
65 struct wine_pthread_functions pthread_functions = { NULL };
68 static RTL_CRITICAL_SECTION ldt_section;
69 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
72 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
73 0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
75 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
76 static sigset_t ldt_sigset;
78 /***********************************************************************
79 * locking for LDT routines
81 static void ldt_lock(void)
85 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
86 RtlEnterCriticalSection( &ldt_section );
87 if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
90 static void ldt_unlock(void)
92 if (ldt_section.RecursionCount == 1)
94 sigset_t sigset = ldt_sigset;
95 RtlLeaveCriticalSection( &ldt_section );
96 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
98 else RtlLeaveCriticalSection( &ldt_section );
102 /***********************************************************************
105 static inline NTSTATUS init_teb( TEB *teb )
107 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
108 struct ntdll_thread_regs *thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
110 teb->Tib.ExceptionList = (void *)~0UL;
111 teb->Tib.StackBase = (void *)~0UL;
112 teb->Tib.Self = &teb->Tib;
113 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
114 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
116 if (!(thread_regs->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
117 thread_data->request_fd = -1;
118 thread_data->reply_fd = -1;
119 thread_data->wait_fd[0] = -1;
120 thread_data->wait_fd[1] = -1;
122 return STATUS_SUCCESS;
126 /***********************************************************************
129 * Make sure the unicode string doesn't point beyond the end pointer
131 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
133 if ((char *)str->Buffer >= end_ptr)
135 str->Length = str->MaximumLength = 0;
139 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
141 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
143 if (str->Length >= str->MaximumLength)
145 if (str->MaximumLength >= sizeof(WCHAR))
146 str->Length = str->MaximumLength - sizeof(WCHAR);
148 str->Length = str->MaximumLength = 0;
153 /***********************************************************************
154 * init_user_process_params
156 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
158 static NTSTATUS init_user_process_params( SIZE_T info_size, HANDLE *exe_file )
163 RTL_USER_PROCESS_PARAMETERS *params = NULL;
165 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &info_size,
166 MEM_COMMIT, PAGE_READWRITE );
167 if (status != STATUS_SUCCESS) return status;
169 params->AllocationSize = info_size;
170 NtCurrentTeb()->Peb->ProcessParameters = params;
172 SERVER_START_REQ( get_startup_info )
174 wine_server_set_reply( req, params, info_size );
175 if (!(status = wine_server_call( req )))
177 info_size = wine_server_reply_size( reply );
178 *exe_file = reply->exe_file;
179 params->hStdInput = reply->hstdin;
180 params->hStdOutput = reply->hstdout;
181 params->hStdError = reply->hstderr;
185 if (status != STATUS_SUCCESS) return status;
187 if (params->Size > info_size) params->Size = info_size;
189 /* make sure the strings are valid */
190 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
191 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
192 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
193 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
194 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
195 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
196 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
197 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
199 /* environment needs to be a separate memory block */
200 env_size = info_size - params->Size;
201 if (!env_size) env_size = 1;
203 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
204 MEM_COMMIT, PAGE_READWRITE );
205 if (status != STATUS_SUCCESS) return status;
206 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
207 params->Environment = ptr;
209 RtlNormalizeProcessParams( params );
214 /***********************************************************************
217 * Setup the initial thread.
219 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
221 HANDLE thread_init(void)
226 SIZE_T size, info_size;
228 struct ntdll_thread_data *thread_data;
229 struct ntdll_thread_regs *thread_regs;
230 struct wine_pthread_thread_info thread_info;
231 static struct debug_info debug_info; /* debug info for initial thread */
235 /* reserve space for shared user data */
237 addr = (void *)0x7ffe0000;
239 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE, PAGE_READONLY );
241 /* allocate and initialize the PEB */
245 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
246 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
249 peb->NumberOfProcessors = 1;
250 peb->ProcessParameters = ¶ms;
251 peb->TlsBitmap = &tls_bitmap;
252 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
254 params.CurrentDirectory.DosPath.Buffer = current_dir;
255 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
256 params.wShowWindow = 1; /* SW_SHOWNORMAL */
257 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
258 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
259 sizeof(peb->TlsExpansionBitmapBits) * 8 );
260 InitializeListHead( &ldr.InLoadOrderModuleList );
261 InitializeListHead( &ldr.InMemoryOrderModuleList );
262 InitializeListHead( &ldr.InInitializationOrderModuleList );
263 InitializeListHead( &tls_links );
265 /* allocate and initialize the initial TEB */
267 sigstack_total_size = get_signal_stack_total_size();
268 while (1 << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
269 assert( 1 << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
270 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
271 thread_info.teb_size = sigstack_total_size;
274 size = sigstack_total_size;
275 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
276 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
279 thread_info.teb_size = size;
281 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
282 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
283 thread_data->debug_info = &debug_info;
284 InsertHeadList( &tls_links, &teb->TlsLinks );
286 thread_info.stack_base = NULL;
287 thread_info.stack_size = 0;
288 thread_info.teb_base = teb;
289 thread_info.teb_sel = thread_regs->fs;
290 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
291 pthread_functions.init_current_teb( &thread_info );
292 pthread_functions.init_thread( &thread_info );
293 virtual_init_threading();
295 debug_info.str_pos = debug_info.strings;
296 debug_info.out_pos = debug_info.output;
299 /* setup the server connection */
300 server_init_process();
301 info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
303 /* create the process heap */
304 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
306 MESSAGE( "wine: failed to create the process heap\n" );
310 /* allocate user parameters */
313 init_user_process_params( info_size, &exe_file );
317 /* This is wine specific: we have no parent (we're started from unix)
318 * so, create a simple console with bare handles to unix stdio
320 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
321 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
322 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
325 /* initialize LDT locking */
326 wine_ldt_init_locking( ldt_lock, ldt_unlock );
331 typedef LONG (WINAPI *PUNHANDLED_EXCEPTION_FILTER)(PEXCEPTION_POINTERS);
332 static PUNHANDLED_EXCEPTION_FILTER get_unhandled_exception_filter(void)
334 static PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter;
335 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
336 UNICODE_STRING module_name;
337 ANSI_STRING func_name;
338 HMODULE kernel32_handle;
340 if (unhandled_exception_filter) return unhandled_exception_filter;
342 RtlInitUnicodeString(&module_name, kernel32W);
343 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
345 if (LdrGetDllHandle( 0, 0, &module_name, &kernel32_handle ) == STATUS_SUCCESS)
346 LdrGetProcedureAddress( kernel32_handle, &func_name, 0,
347 (void **)&unhandled_exception_filter );
349 return unhandled_exception_filter;
352 /***********************************************************************
355 * Hack to make things compatible with the thread procedures used by kernel32.CreateThread.
357 static void DECLSPEC_NORETURN call_thread_func( PRTL_THREAD_START_ROUTINE rtl_func, void *arg )
359 LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)rtl_func;
363 MODULE_DllThreadAttach( NULL );
366 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
368 exit_code = func( arg );
370 /* send the exit code to the server */
371 SERVER_START_REQ( terminate_thread )
373 req->handle = GetCurrentThread();
374 req->exit_code = exit_code;
375 wine_server_call( req );
382 LdrShutdownProcess();
388 server_exit_thread( exit_code );
393 /***********************************************************************
396 * Startup routine for a newly created thread.
398 static void start_thread( struct wine_pthread_thread_info *info )
400 TEB *teb = info->teb_base;
401 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
402 struct startup_info *startup_info = (struct startup_info *)info;
403 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
404 void *arg = startup_info->entry_arg;
405 struct debug_info debug_info;
406 SIZE_T size, page_size = getpagesize();
408 debug_info.str_pos = debug_info.strings;
409 debug_info.out_pos = debug_info.output;
410 thread_data->debug_info = &debug_info;
412 pthread_functions.init_current_teb( info );
414 server_init_thread( info->pid, info->tid, func );
415 pthread_functions.init_thread( info );
417 /* allocate a memory view for the stack */
418 size = info->stack_size;
419 teb->DeallocationStack = info->stack_base;
420 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
421 &size, MEM_SYSTEM, PAGE_READWRITE );
422 /* limit is lower than base since the stack grows down */
423 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
424 teb->Tib.StackLimit = (char *)info->stack_base + page_size;
426 /* setup the guard page */
428 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, PAGE_NOACCESS, NULL );
430 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
433 InsertHeadList( &tls_links, &teb->TlsLinks );
436 /* NOTE: Windows does not have an exception handler around the call to
437 * the thread attach. We do for ease of debugging */
438 if (get_unhandled_exception_filter())
442 call_thread_func( func, arg );
444 __EXCEPT(get_unhandled_exception_filter())
446 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
451 call_thread_func( func, arg );
455 /***********************************************************************
456 * RtlCreateUserThread (NTDLL.@)
458 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
459 BOOLEAN suspended, PVOID stack_addr,
460 SIZE_T stack_reserve, SIZE_T stack_commit,
461 PRTL_THREAD_START_ROUTINE start, void *param,
462 HANDLE *handle_ptr, CLIENT_ID *id )
465 struct ntdll_thread_data *thread_data;
466 struct ntdll_thread_regs *thread_regs = NULL;
467 struct startup_info *info = NULL;
474 SIZE_T size, page_size = getpagesize();
476 if (process != NtCurrentProcess())
481 call.create_thread.type = APC_CREATE_THREAD;
482 call.create_thread.func = start;
483 call.create_thread.arg = param;
484 call.create_thread.reserve = stack_reserve;
485 call.create_thread.commit = stack_commit;
486 call.create_thread.suspend = suspended;
487 status = NTDLL_queue_process_apc( process, &call, &result );
488 if (status != STATUS_SUCCESS) return status;
490 if (result.create_thread.status == STATUS_SUCCESS)
492 if (id) id->UniqueThread = (HANDLE)result.create_thread.tid;
493 if (handle_ptr) *handle_ptr = result.create_thread.handle;
494 else NtClose( result.create_thread.handle );
496 return result.create_thread.status;
499 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
500 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
501 wine_server_send_fd( request_pipe[0] );
503 SERVER_START_REQ( new_thread )
505 req->access = THREAD_ALL_ACCESS;
506 req->attributes = 0; /* FIXME */
507 req->suspend = suspended;
508 req->request_fd = request_pipe[0];
509 if (!(status = wine_server_call( req )))
511 handle = reply->handle;
514 close( request_pipe[0] );
520 close( request_pipe[1] );
524 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
527 size = sigstack_total_size;
528 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
529 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
532 teb->Peb = NtCurrentTeb()->Peb;
533 info = (struct startup_info *)(teb + 1);
534 info->pthread_info.teb_size = size;
535 if ((status = init_teb( teb ))) goto error;
537 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
538 teb->ClientId.UniqueThread = (HANDLE)tid;
540 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
541 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
542 thread_data->request_fd = request_pipe[1];
544 info->pthread_info.teb_base = teb;
545 info->pthread_info.teb_sel = thread_regs->fs;
547 /* inherit debug registers from parent thread */
548 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
549 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
550 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
551 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
552 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
553 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
555 if (!stack_reserve || !stack_commit)
557 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
558 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
559 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
561 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
562 stack_reserve += page_size; /* for the guard page */
563 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
564 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
566 info->pthread_info.stack_base = NULL;
567 info->pthread_info.stack_size = stack_reserve;
568 info->pthread_info.entry = start_thread;
569 info->entry_point = start;
570 info->entry_arg = param;
572 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
574 status = STATUS_NO_MEMORY;
577 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
579 if (id) id->UniqueThread = (HANDLE)tid;
580 if (handle_ptr) *handle_ptr = handle;
581 else NtClose( handle );
583 return STATUS_SUCCESS;
586 if (thread_regs) wine_ldt_free_fs( thread_regs->fs );
590 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
592 if (handle) NtClose( handle );
593 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
594 close( request_pipe[1] );
599 /***********************************************************************
600 * RtlExitUserThread (NTDLL.@)
602 void WINAPI RtlExitUserThread( ULONG status )
605 server_exit_thread( status );
609 /***********************************************************************
610 * NtOpenThread (NTDLL.@)
611 * ZwOpenThread (NTDLL.@)
613 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
614 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
618 SERVER_START_REQ( open_thread )
620 req->tid = (thread_id_t)id->UniqueThread;
621 req->access = access;
622 req->attributes = attr ? attr->Attributes : 0;
623 ret = wine_server_call( req );
624 *handle = reply->handle;
631 /******************************************************************************
632 * NtSuspendThread (NTDLL.@)
633 * ZwSuspendThread (NTDLL.@)
635 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
639 SERVER_START_REQ( suspend_thread )
641 req->handle = handle;
642 if (!(ret = wine_server_call( req ))) *count = reply->count;
649 /******************************************************************************
650 * NtResumeThread (NTDLL.@)
651 * ZwResumeThread (NTDLL.@)
653 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
657 SERVER_START_REQ( resume_thread )
659 req->handle = handle;
660 if (!(ret = wine_server_call( req ))) *count = reply->count;
667 /******************************************************************************
668 * NtAlertResumeThread (NTDLL.@)
669 * ZwAlertResumeThread (NTDLL.@)
671 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
673 FIXME( "stub: should alert thread %p\n", handle );
674 return NtResumeThread( handle, count );
678 /******************************************************************************
679 * NtAlertThread (NTDLL.@)
680 * ZwAlertThread (NTDLL.@)
682 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
684 FIXME( "stub: %p\n", handle );
685 return STATUS_NOT_IMPLEMENTED;
689 /******************************************************************************
690 * NtTerminateThread (NTDLL.@)
691 * ZwTerminateThread (NTDLL.@)
693 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
698 SERVER_START_REQ( terminate_thread )
700 req->handle = handle;
701 req->exit_code = exit_code;
702 ret = wine_server_call( req );
703 self = !ret && reply->self;
710 if (last) exit( exit_code );
711 else server_abort_thread( exit_code );
717 /******************************************************************************
718 * NtQueueApcThread (NTDLL.@)
720 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
721 ULONG_PTR arg2, ULONG_PTR arg3 )
724 SERVER_START_REQ( queue_apc )
726 req->thread = handle;
729 req->call.type = APC_USER;
730 req->call.user.func = func;
731 req->call.user.args[0] = arg1;
732 req->call.user.args[1] = arg2;
733 req->call.user.args[2] = arg3;
735 else req->call.type = APC_NONE; /* wake up only */
736 ret = wine_server_call( req );
743 /***********************************************************************
744 * NtSetContextThread (NTDLL.@)
745 * ZwSetContextThread (NTDLL.@)
747 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
754 /* on i386 debug registers always require a server call */
755 self = (handle == GetCurrentThread());
756 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
758 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
759 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
760 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
761 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
767 SERVER_START_REQ( set_thread_context )
769 req->handle = handle;
770 req->flags = context->ContextFlags;
772 wine_server_add_data( req, context, sizeof(*context) );
773 ret = wine_server_call( req );
778 if (ret == STATUS_PENDING)
780 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
782 for (i = 0; i < 100; i++)
784 SERVER_START_REQ( set_thread_context )
786 req->handle = handle;
787 req->flags = context->ContextFlags;
789 wine_server_add_data( req, context, sizeof(*context) );
790 ret = wine_server_call( req );
793 if (ret != STATUS_PENDING) break;
796 NtResumeThread( handle, &dummy );
798 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
804 if (self) set_cpu_context( context );
805 return STATUS_SUCCESS;
809 /* copy a context structure according to the flags */
810 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
813 flags &= ~CONTEXT_i386; /* get rid of CPU id */
814 if (flags & CONTEXT_INTEGER)
823 if (flags & CONTEXT_CONTROL)
828 to->SegCs = from->SegCs;
829 to->SegSs = from->SegSs;
830 to->EFlags = from->EFlags;
832 if (flags & CONTEXT_SEGMENTS)
834 to->SegDs = from->SegDs;
835 to->SegEs = from->SegEs;
836 to->SegFs = from->SegFs;
837 to->SegGs = from->SegGs;
839 if (flags & CONTEXT_DEBUG_REGISTERS)
848 if (flags & CONTEXT_FLOATING_POINT)
850 to->FloatSave = from->FloatSave;
852 #elif defined(__x86_64__)
853 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
854 if (flags & CONTEXT_CONTROL)
859 to->SegCs = from->SegCs;
860 to->SegSs = from->SegSs;
861 to->EFlags = from->EFlags;
862 to->MxCsr = from->MxCsr;
864 if (flags & CONTEXT_INTEGER)
881 if (flags & CONTEXT_SEGMENTS)
883 to->SegDs = from->SegDs;
884 to->SegEs = from->SegEs;
885 to->SegFs = from->SegFs;
886 to->SegGs = from->SegGs;
888 if (flags & CONTEXT_FLOATING_POINT)
890 to->u.FltSave = from->u.FltSave;
892 if (flags & CONTEXT_DEBUG_REGISTERS)
901 #elif defined(__sparc__)
902 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
903 if (flags & CONTEXT_CONTROL)
912 if (flags & CONTEXT_INTEGER)
947 if (flags & CONTEXT_FLOATING_POINT)
951 #elif defined(__powerpc__)
953 if (flags & CONTEXT_CONTROL)
959 if (flags & CONTEXT_INTEGER)
961 to->Gpr0 = from->Gpr0;
962 to->Gpr1 = from->Gpr1;
963 to->Gpr2 = from->Gpr2;
964 to->Gpr3 = from->Gpr3;
965 to->Gpr4 = from->Gpr4;
966 to->Gpr5 = from->Gpr5;
967 to->Gpr6 = from->Gpr6;
968 to->Gpr7 = from->Gpr7;
969 to->Gpr8 = from->Gpr8;
970 to->Gpr9 = from->Gpr9;
971 to->Gpr10 = from->Gpr10;
972 to->Gpr11 = from->Gpr11;
973 to->Gpr12 = from->Gpr12;
974 to->Gpr13 = from->Gpr13;
975 to->Gpr14 = from->Gpr14;
976 to->Gpr15 = from->Gpr15;
977 to->Gpr16 = from->Gpr16;
978 to->Gpr17 = from->Gpr17;
979 to->Gpr18 = from->Gpr18;
980 to->Gpr19 = from->Gpr19;
981 to->Gpr20 = from->Gpr20;
982 to->Gpr21 = from->Gpr21;
983 to->Gpr22 = from->Gpr22;
984 to->Gpr23 = from->Gpr23;
985 to->Gpr24 = from->Gpr24;
986 to->Gpr25 = from->Gpr25;
987 to->Gpr26 = from->Gpr26;
988 to->Gpr27 = from->Gpr27;
989 to->Gpr28 = from->Gpr28;
990 to->Gpr29 = from->Gpr29;
991 to->Gpr30 = from->Gpr30;
992 to->Gpr31 = from->Gpr31;
996 if (flags & CONTEXT_FLOATING_POINT)
998 to->Fpr0 = from->Fpr0;
999 to->Fpr1 = from->Fpr1;
1000 to->Fpr2 = from->Fpr2;
1001 to->Fpr3 = from->Fpr3;
1002 to->Fpr4 = from->Fpr4;
1003 to->Fpr5 = from->Fpr5;
1004 to->Fpr6 = from->Fpr6;
1005 to->Fpr7 = from->Fpr7;
1006 to->Fpr8 = from->Fpr8;
1007 to->Fpr9 = from->Fpr9;
1008 to->Fpr10 = from->Fpr10;
1009 to->Fpr11 = from->Fpr11;
1010 to->Fpr12 = from->Fpr12;
1011 to->Fpr13 = from->Fpr13;
1012 to->Fpr14 = from->Fpr14;
1013 to->Fpr15 = from->Fpr15;
1014 to->Fpr16 = from->Fpr16;
1015 to->Fpr17 = from->Fpr17;
1016 to->Fpr18 = from->Fpr18;
1017 to->Fpr19 = from->Fpr19;
1018 to->Fpr20 = from->Fpr20;
1019 to->Fpr21 = from->Fpr21;
1020 to->Fpr22 = from->Fpr22;
1021 to->Fpr23 = from->Fpr23;
1022 to->Fpr24 = from->Fpr24;
1023 to->Fpr25 = from->Fpr25;
1024 to->Fpr26 = from->Fpr26;
1025 to->Fpr27 = from->Fpr27;
1026 to->Fpr28 = from->Fpr28;
1027 to->Fpr29 = from->Fpr29;
1028 to->Fpr30 = from->Fpr30;
1029 to->Fpr31 = from->Fpr31;
1030 to->Fpscr = from->Fpscr;
1033 #error You must implement context copying for your CPU
1038 /***********************************************************************
1039 * NtGetContextThread (NTDLL.@)
1040 * ZwGetContextThread (NTDLL.@)
1042 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
1047 DWORD needed_flags = context->ContextFlags;
1048 BOOL self = (handle == GetCurrentThread());
1051 /* on i386 debug registers always require a server call */
1052 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
1057 SERVER_START_REQ( get_thread_context )
1059 req->handle = handle;
1060 req->flags = context->ContextFlags;
1062 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1063 ret = wine_server_call( req );
1068 if (ret == STATUS_PENDING)
1070 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
1072 for (i = 0; i < 100; i++)
1074 SERVER_START_REQ( get_thread_context )
1076 req->handle = handle;
1077 req->flags = context->ContextFlags;
1079 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1080 ret = wine_server_call( req );
1083 if (ret != STATUS_PENDING) break;
1086 NtResumeThread( handle, &dummy );
1088 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1090 if (ret) return ret;
1091 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1092 needed_flags &= ~ctx.ContextFlags;
1099 get_cpu_context( &ctx );
1100 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1103 /* update the cached version of the debug registers */
1104 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1106 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1107 regs->dr0 = context->Dr0;
1108 regs->dr1 = context->Dr1;
1109 regs->dr2 = context->Dr2;
1110 regs->dr3 = context->Dr3;
1111 regs->dr6 = context->Dr6;
1112 regs->dr7 = context->Dr7;
1116 return STATUS_SUCCESS;
1120 /******************************************************************************
1121 * NtQueryInformationThread (NTDLL.@)
1122 * ZwQueryInformationThread (NTDLL.@)
1124 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1125 void *data, ULONG length, ULONG *ret_len )
1131 case ThreadBasicInformation:
1133 THREAD_BASIC_INFORMATION info;
1135 SERVER_START_REQ( get_thread_info )
1137 req->handle = handle;
1139 if (!(status = wine_server_call( req )))
1141 info.ExitStatus = reply->exit_code;
1142 info.TebBaseAddress = reply->teb;
1143 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
1144 info.ClientId.UniqueThread = (HANDLE)reply->tid;
1145 info.AffinityMask = reply->affinity;
1146 info.Priority = reply->priority;
1147 info.BasePriority = reply->priority; /* FIXME */
1151 if (status == STATUS_SUCCESS)
1153 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1154 if (ret_len) *ret_len = min( length, sizeof(info) );
1160 KERNEL_USER_TIMES kusrt;
1161 /* We need to do a server call to get the creation time or exit time */
1162 /* This works on any thread */
1163 SERVER_START_REQ( get_thread_info )
1165 req->handle = handle;
1167 status = wine_server_call( req );
1168 if (status == STATUS_SUCCESS)
1170 NTDLL_from_server_abstime( &kusrt.CreateTime, &reply->creation_time );
1171 NTDLL_from_server_abstime( &kusrt.ExitTime, &reply->exit_time );
1175 if (status == STATUS_SUCCESS)
1177 /* We call times(2) for kernel time or user time */
1178 /* We can only (portably) do this for the current thread */
1179 if (handle == GetCurrentThread())
1181 struct tms time_buf;
1182 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1185 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1186 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1190 kusrt.KernelTime.QuadPart = 0;
1191 kusrt.UserTime.QuadPart = 0;
1192 FIXME("Cannot get kerneltime or usertime of other threads\n");
1194 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1195 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1199 case ThreadDescriptorTableEntry:
1202 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1203 if (length < sizeof(*tdi))
1204 status = STATUS_INFO_LENGTH_MISMATCH;
1205 else if (!(tdi->Selector & 4)) /* GDT selector */
1207 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1208 status = STATUS_SUCCESS;
1209 if (!sel) /* null selector */
1210 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1213 tdi->Entry.BaseLow = 0;
1214 tdi->Entry.HighWord.Bits.BaseMid = 0;
1215 tdi->Entry.HighWord.Bits.BaseHi = 0;
1216 tdi->Entry.LimitLow = 0xffff;
1217 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1218 tdi->Entry.HighWord.Bits.Dpl = 3;
1219 tdi->Entry.HighWord.Bits.Sys = 0;
1220 tdi->Entry.HighWord.Bits.Pres = 1;
1221 tdi->Entry.HighWord.Bits.Granularity = 1;
1222 tdi->Entry.HighWord.Bits.Default_Big = 1;
1223 tdi->Entry.HighWord.Bits.Type = 0x12;
1224 /* it has to be one of the system GDT selectors */
1225 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1227 if (sel == (wine_get_cs() & ~3))
1228 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1229 else status = STATUS_ACCESS_DENIED;
1235 SERVER_START_REQ( get_selector_entry )
1237 req->handle = handle;
1238 req->entry = tdi->Selector >> 3;
1239 status = wine_server_call( req );
1242 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1243 status = STATUS_ACCESS_VIOLATION;
1246 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1247 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1248 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1254 if (status == STATUS_SUCCESS && ret_len)
1255 /* yes, that's a bit strange, but it's the way it is */
1256 *ret_len = sizeof(LDT_ENTRY);
1258 status = STATUS_NOT_IMPLEMENTED;
1262 case ThreadAmILastThread:
1264 SERVER_START_REQ(get_thread_info)
1266 req->handle = handle;
1268 status = wine_server_call( req );
1269 if (status == STATUS_SUCCESS)
1271 BOOLEAN last = reply->last;
1272 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1273 if (ret_len) *ret_len = min( length, sizeof(last) );
1279 case ThreadPriority:
1280 case ThreadBasePriority:
1281 case ThreadAffinityMask:
1282 case ThreadImpersonationToken:
1283 case ThreadEnableAlignmentFaultFixup:
1284 case ThreadEventPair_Reusable:
1285 case ThreadQuerySetWin32StartAddress:
1286 case ThreadZeroTlsCell:
1287 case ThreadPerformanceCount:
1288 case ThreadIdealProcessor:
1289 case ThreadPriorityBoost:
1290 case ThreadSetTlsArrayAddress:
1291 case ThreadIsIoPending:
1293 FIXME( "info class %d not supported yet\n", class );
1294 return STATUS_NOT_IMPLEMENTED;
1299 /******************************************************************************
1300 * NtSetInformationThread (NTDLL.@)
1301 * ZwSetInformationThread (NTDLL.@)
1303 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1304 LPCVOID data, ULONG length )
1309 case ThreadZeroTlsCell:
1310 if (handle == GetCurrentThread())
1315 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1316 index = *(const DWORD *)data;
1317 if (index < TLS_MINIMUM_AVAILABLE)
1319 RtlAcquirePebLock();
1320 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1322 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1323 teb->TlsSlots[index] = 0;
1325 RtlReleasePebLock();
1329 index -= TLS_MINIMUM_AVAILABLE;
1330 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1331 return STATUS_INVALID_PARAMETER;
1332 RtlAcquirePebLock();
1333 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1335 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1336 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1338 RtlReleasePebLock();
1340 return STATUS_SUCCESS;
1342 FIXME( "ZeroTlsCell not supported on other threads\n" );
1343 return STATUS_NOT_IMPLEMENTED;
1345 case ThreadImpersonationToken:
1347 const HANDLE *phToken = data;
1348 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1349 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1350 SERVER_START_REQ( set_thread_info )
1352 req->handle = handle;
1353 req->token = *phToken;
1354 req->mask = SET_THREAD_INFO_TOKEN;
1355 status = wine_server_call( req );
1360 case ThreadBasePriority:
1362 const DWORD *pprio = data;
1363 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1364 SERVER_START_REQ( set_thread_info )
1366 req->handle = handle;
1367 req->priority = *pprio;
1368 req->mask = SET_THREAD_INFO_PRIORITY;
1369 status = wine_server_call( req );
1374 case ThreadAffinityMask:
1376 const DWORD *paff = data;
1377 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1378 SERVER_START_REQ( set_thread_info )
1380 req->handle = handle;
1381 req->affinity = *paff;
1382 req->mask = SET_THREAD_INFO_AFFINITY;
1383 status = wine_server_call( req );
1388 case ThreadBasicInformation:
1390 case ThreadPriority:
1391 case ThreadDescriptorTableEntry:
1392 case ThreadEnableAlignmentFaultFixup:
1393 case ThreadEventPair_Reusable:
1394 case ThreadQuerySetWin32StartAddress:
1395 case ThreadPerformanceCount:
1396 case ThreadAmILastThread:
1397 case ThreadIdealProcessor:
1398 case ThreadPriorityBoost:
1399 case ThreadSetTlsArrayAddress:
1400 case ThreadIsIoPending:
1402 FIXME( "info class %d not supported yet\n", class );
1403 return STATUS_NOT_IMPLEMENTED;
1408 /**********************************************************************
1409 * NtCurrentTeb (NTDLL.@)
1411 #if defined(__i386__) && defined(__GNUC__)
1413 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
1415 #elif defined(__i386__) && defined(_MSC_VER)
1417 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1421 /**********************************************************************/
1423 TEB * WINAPI NtCurrentTeb(void)
1425 return pthread_functions.get_current_teb();
1428 #endif /* __i386__ */