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( ! is_current_process( process ) )
478 ERR("Unsupported on other process\n");
479 return STATUS_ACCESS_DENIED;
482 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
483 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
484 wine_server_send_fd( request_pipe[0] );
486 SERVER_START_REQ( new_thread )
488 req->access = THREAD_ALL_ACCESS;
489 req->attributes = 0; /* FIXME */
490 req->suspend = suspended;
491 req->request_fd = request_pipe[0];
492 if (!(status = wine_server_call( req )))
494 handle = reply->handle;
497 close( request_pipe[0] );
503 close( request_pipe[1] );
507 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
510 size = sigstack_total_size;
511 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
512 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
515 teb->Peb = NtCurrentTeb()->Peb;
516 info = (struct startup_info *)(teb + 1);
517 info->pthread_info.teb_size = size;
518 if ((status = init_teb( teb ))) goto error;
520 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
521 teb->ClientId.UniqueThread = (HANDLE)tid;
523 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
524 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
525 thread_data->request_fd = request_pipe[1];
527 info->pthread_info.teb_base = teb;
528 info->pthread_info.teb_sel = thread_regs->fs;
530 /* inherit debug registers from parent thread */
531 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
532 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
533 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
534 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
535 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
536 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
538 if (!stack_reserve || !stack_commit)
540 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
541 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
542 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
544 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
545 stack_reserve += page_size; /* for the guard page */
546 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
547 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
549 info->pthread_info.stack_base = NULL;
550 info->pthread_info.stack_size = stack_reserve;
551 info->pthread_info.entry = start_thread;
552 info->entry_point = start;
553 info->entry_arg = param;
555 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
557 status = STATUS_NO_MEMORY;
560 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
562 if (id) id->UniqueThread = (HANDLE)tid;
563 if (handle_ptr) *handle_ptr = handle;
564 else NtClose( handle );
566 return STATUS_SUCCESS;
569 if (thread_regs) wine_ldt_free_fs( thread_regs->fs );
573 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
575 if (handle) NtClose( handle );
576 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
577 close( request_pipe[1] );
582 /***********************************************************************
583 * RtlExitUserThread (NTDLL.@)
585 void WINAPI RtlExitUserThread( ULONG status )
588 server_exit_thread( status );
592 /***********************************************************************
593 * NtOpenThread (NTDLL.@)
594 * ZwOpenThread (NTDLL.@)
596 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
597 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
601 SERVER_START_REQ( open_thread )
603 req->tid = (thread_id_t)id->UniqueThread;
604 req->access = access;
605 req->attributes = attr ? attr->Attributes : 0;
606 ret = wine_server_call( req );
607 *handle = reply->handle;
614 /******************************************************************************
615 * NtSuspendThread (NTDLL.@)
616 * ZwSuspendThread (NTDLL.@)
618 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
622 SERVER_START_REQ( suspend_thread )
624 req->handle = handle;
625 if (!(ret = wine_server_call( req ))) *count = reply->count;
632 /******************************************************************************
633 * NtResumeThread (NTDLL.@)
634 * ZwResumeThread (NTDLL.@)
636 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
640 SERVER_START_REQ( resume_thread )
642 req->handle = handle;
643 if (!(ret = wine_server_call( req ))) *count = reply->count;
650 /******************************************************************************
651 * NtAlertResumeThread (NTDLL.@)
652 * ZwAlertResumeThread (NTDLL.@)
654 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
656 FIXME( "stub: should alert thread %p\n", handle );
657 return NtResumeThread( handle, count );
661 /******************************************************************************
662 * NtAlertThread (NTDLL.@)
663 * ZwAlertThread (NTDLL.@)
665 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
667 FIXME( "stub: %p\n", handle );
668 return STATUS_NOT_IMPLEMENTED;
672 /******************************************************************************
673 * NtTerminateThread (NTDLL.@)
674 * ZwTerminateThread (NTDLL.@)
676 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
681 SERVER_START_REQ( terminate_thread )
683 req->handle = handle;
684 req->exit_code = exit_code;
685 ret = wine_server_call( req );
686 self = !ret && reply->self;
693 if (last) exit( exit_code );
694 else server_abort_thread( exit_code );
700 /******************************************************************************
701 * NtQueueApcThread (NTDLL.@)
703 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
704 ULONG_PTR arg2, ULONG_PTR arg3 )
707 SERVER_START_REQ( queue_apc )
709 req->thread = handle;
712 req->call.type = APC_USER;
713 req->call.user.func = func;
714 req->call.user.args[0] = arg1;
715 req->call.user.args[1] = arg2;
716 req->call.user.args[2] = arg3;
718 else req->call.type = APC_NONE; /* wake up only */
719 ret = wine_server_call( req );
726 /***********************************************************************
727 * NtSetContextThread (NTDLL.@)
728 * ZwSetContextThread (NTDLL.@)
730 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
737 /* on i386 debug registers always require a server call */
738 self = (handle == GetCurrentThread());
739 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
741 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
742 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
743 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
744 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
750 SERVER_START_REQ( set_thread_context )
752 req->handle = handle;
753 req->flags = context->ContextFlags;
755 wine_server_add_data( req, context, sizeof(*context) );
756 ret = wine_server_call( req );
761 if (ret == STATUS_PENDING)
763 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
765 for (i = 0; i < 100; i++)
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 );
776 if (ret != STATUS_PENDING) break;
779 NtResumeThread( handle, &dummy );
781 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
787 if (self) set_cpu_context( context );
788 return STATUS_SUCCESS;
792 /* copy a context structure according to the flags */
793 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
796 flags &= ~CONTEXT_i386; /* get rid of CPU id */
797 if (flags & CONTEXT_INTEGER)
806 if (flags & CONTEXT_CONTROL)
811 to->SegCs = from->SegCs;
812 to->SegSs = from->SegSs;
813 to->EFlags = from->EFlags;
815 if (flags & CONTEXT_SEGMENTS)
817 to->SegDs = from->SegDs;
818 to->SegEs = from->SegEs;
819 to->SegFs = from->SegFs;
820 to->SegGs = from->SegGs;
822 if (flags & CONTEXT_DEBUG_REGISTERS)
831 if (flags & CONTEXT_FLOATING_POINT)
833 to->FloatSave = from->FloatSave;
835 #elif defined(__x86_64__)
836 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
837 if (flags & CONTEXT_CONTROL)
842 to->SegCs = from->SegCs;
843 to->SegSs = from->SegSs;
844 to->EFlags = from->EFlags;
845 to->MxCsr = from->MxCsr;
847 if (flags & CONTEXT_INTEGER)
864 if (flags & CONTEXT_SEGMENTS)
866 to->SegDs = from->SegDs;
867 to->SegEs = from->SegEs;
868 to->SegFs = from->SegFs;
869 to->SegGs = from->SegGs;
871 if (flags & CONTEXT_FLOATING_POINT)
873 to->u.FltSave = from->u.FltSave;
875 if (flags & CONTEXT_DEBUG_REGISTERS)
884 #elif defined(__sparc__)
885 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
886 if (flags & CONTEXT_CONTROL)
895 if (flags & CONTEXT_INTEGER)
930 if (flags & CONTEXT_FLOATING_POINT)
934 #elif defined(__powerpc__)
936 if (flags & CONTEXT_CONTROL)
942 if (flags & CONTEXT_INTEGER)
944 to->Gpr0 = from->Gpr0;
945 to->Gpr1 = from->Gpr1;
946 to->Gpr2 = from->Gpr2;
947 to->Gpr3 = from->Gpr3;
948 to->Gpr4 = from->Gpr4;
949 to->Gpr5 = from->Gpr5;
950 to->Gpr6 = from->Gpr6;
951 to->Gpr7 = from->Gpr7;
952 to->Gpr8 = from->Gpr8;
953 to->Gpr9 = from->Gpr9;
954 to->Gpr10 = from->Gpr10;
955 to->Gpr11 = from->Gpr11;
956 to->Gpr12 = from->Gpr12;
957 to->Gpr13 = from->Gpr13;
958 to->Gpr14 = from->Gpr14;
959 to->Gpr15 = from->Gpr15;
960 to->Gpr16 = from->Gpr16;
961 to->Gpr17 = from->Gpr17;
962 to->Gpr18 = from->Gpr18;
963 to->Gpr19 = from->Gpr19;
964 to->Gpr20 = from->Gpr20;
965 to->Gpr21 = from->Gpr21;
966 to->Gpr22 = from->Gpr22;
967 to->Gpr23 = from->Gpr23;
968 to->Gpr24 = from->Gpr24;
969 to->Gpr25 = from->Gpr25;
970 to->Gpr26 = from->Gpr26;
971 to->Gpr27 = from->Gpr27;
972 to->Gpr28 = from->Gpr28;
973 to->Gpr29 = from->Gpr29;
974 to->Gpr30 = from->Gpr30;
975 to->Gpr31 = from->Gpr31;
979 if (flags & CONTEXT_FLOATING_POINT)
981 to->Fpr0 = from->Fpr0;
982 to->Fpr1 = from->Fpr1;
983 to->Fpr2 = from->Fpr2;
984 to->Fpr3 = from->Fpr3;
985 to->Fpr4 = from->Fpr4;
986 to->Fpr5 = from->Fpr5;
987 to->Fpr6 = from->Fpr6;
988 to->Fpr7 = from->Fpr7;
989 to->Fpr8 = from->Fpr8;
990 to->Fpr9 = from->Fpr9;
991 to->Fpr10 = from->Fpr10;
992 to->Fpr11 = from->Fpr11;
993 to->Fpr12 = from->Fpr12;
994 to->Fpr13 = from->Fpr13;
995 to->Fpr14 = from->Fpr14;
996 to->Fpr15 = from->Fpr15;
997 to->Fpr16 = from->Fpr16;
998 to->Fpr17 = from->Fpr17;
999 to->Fpr18 = from->Fpr18;
1000 to->Fpr19 = from->Fpr19;
1001 to->Fpr20 = from->Fpr20;
1002 to->Fpr21 = from->Fpr21;
1003 to->Fpr22 = from->Fpr22;
1004 to->Fpr23 = from->Fpr23;
1005 to->Fpr24 = from->Fpr24;
1006 to->Fpr25 = from->Fpr25;
1007 to->Fpr26 = from->Fpr26;
1008 to->Fpr27 = from->Fpr27;
1009 to->Fpr28 = from->Fpr28;
1010 to->Fpr29 = from->Fpr29;
1011 to->Fpr30 = from->Fpr30;
1012 to->Fpr31 = from->Fpr31;
1013 to->Fpscr = from->Fpscr;
1016 #error You must implement context copying for your CPU
1021 /***********************************************************************
1022 * NtGetContextThread (NTDLL.@)
1023 * ZwGetContextThread (NTDLL.@)
1025 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
1030 DWORD needed_flags = context->ContextFlags;
1031 BOOL self = (handle == GetCurrentThread());
1034 /* on i386 debug registers always require a server call */
1035 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
1040 SERVER_START_REQ( get_thread_context )
1042 req->handle = handle;
1043 req->flags = context->ContextFlags;
1045 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1046 ret = wine_server_call( req );
1051 if (ret == STATUS_PENDING)
1053 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
1055 for (i = 0; i < 100; i++)
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 );
1066 if (ret != STATUS_PENDING) break;
1069 NtResumeThread( handle, &dummy );
1071 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1073 if (ret) return ret;
1074 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1075 needed_flags &= ~ctx.ContextFlags;
1082 get_cpu_context( &ctx );
1083 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1086 /* update the cached version of the debug registers */
1087 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1089 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1090 regs->dr0 = context->Dr0;
1091 regs->dr1 = context->Dr1;
1092 regs->dr2 = context->Dr2;
1093 regs->dr3 = context->Dr3;
1094 regs->dr6 = context->Dr6;
1095 regs->dr7 = context->Dr7;
1099 return STATUS_SUCCESS;
1103 /******************************************************************************
1104 * NtQueryInformationThread (NTDLL.@)
1105 * ZwQueryInformationThread (NTDLL.@)
1107 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1108 void *data, ULONG length, ULONG *ret_len )
1114 case ThreadBasicInformation:
1116 THREAD_BASIC_INFORMATION info;
1118 SERVER_START_REQ( get_thread_info )
1120 req->handle = handle;
1122 if (!(status = wine_server_call( req )))
1124 info.ExitStatus = reply->exit_code;
1125 info.TebBaseAddress = reply->teb;
1126 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
1127 info.ClientId.UniqueThread = (HANDLE)reply->tid;
1128 info.AffinityMask = reply->affinity;
1129 info.Priority = reply->priority;
1130 info.BasePriority = reply->priority; /* FIXME */
1134 if (status == STATUS_SUCCESS)
1136 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1137 if (ret_len) *ret_len = min( length, sizeof(info) );
1143 KERNEL_USER_TIMES kusrt;
1144 /* We need to do a server call to get the creation time or exit time */
1145 /* This works on any thread */
1146 SERVER_START_REQ( get_thread_info )
1148 req->handle = handle;
1150 status = wine_server_call( req );
1151 if (status == STATUS_SUCCESS)
1153 NTDLL_from_server_abstime( &kusrt.CreateTime, &reply->creation_time );
1154 NTDLL_from_server_abstime( &kusrt.ExitTime, &reply->exit_time );
1158 if (status == STATUS_SUCCESS)
1160 /* We call times(2) for kernel time or user time */
1161 /* We can only (portably) do this for the current thread */
1162 if (handle == GetCurrentThread())
1164 struct tms time_buf;
1165 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1168 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1169 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1173 kusrt.KernelTime.QuadPart = 0;
1174 kusrt.UserTime.QuadPart = 0;
1175 FIXME("Cannot get kerneltime or usertime of other threads\n");
1177 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1178 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1182 case ThreadDescriptorTableEntry:
1185 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1186 if (length < sizeof(*tdi))
1187 status = STATUS_INFO_LENGTH_MISMATCH;
1188 else if (!(tdi->Selector & 4)) /* GDT selector */
1190 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1191 status = STATUS_SUCCESS;
1192 if (!sel) /* null selector */
1193 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1196 tdi->Entry.BaseLow = 0;
1197 tdi->Entry.HighWord.Bits.BaseMid = 0;
1198 tdi->Entry.HighWord.Bits.BaseHi = 0;
1199 tdi->Entry.LimitLow = 0xffff;
1200 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1201 tdi->Entry.HighWord.Bits.Dpl = 3;
1202 tdi->Entry.HighWord.Bits.Sys = 0;
1203 tdi->Entry.HighWord.Bits.Pres = 1;
1204 tdi->Entry.HighWord.Bits.Granularity = 1;
1205 tdi->Entry.HighWord.Bits.Default_Big = 1;
1206 tdi->Entry.HighWord.Bits.Type = 0x12;
1207 /* it has to be one of the system GDT selectors */
1208 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1210 if (sel == (wine_get_cs() & ~3))
1211 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1212 else status = STATUS_ACCESS_DENIED;
1218 SERVER_START_REQ( get_selector_entry )
1220 req->handle = handle;
1221 req->entry = tdi->Selector >> 3;
1222 status = wine_server_call( req );
1225 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1226 status = STATUS_ACCESS_VIOLATION;
1229 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1230 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1231 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1237 if (status == STATUS_SUCCESS && ret_len)
1238 /* yes, that's a bit strange, but it's the way it is */
1239 *ret_len = sizeof(LDT_ENTRY);
1241 status = STATUS_NOT_IMPLEMENTED;
1245 case ThreadAmILastThread:
1247 SERVER_START_REQ(get_thread_info)
1249 req->handle = handle;
1251 status = wine_server_call( req );
1252 if (status == STATUS_SUCCESS)
1254 BOOLEAN last = reply->last;
1255 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1256 if (ret_len) *ret_len = min( length, sizeof(last) );
1262 case ThreadPriority:
1263 case ThreadBasePriority:
1264 case ThreadAffinityMask:
1265 case ThreadImpersonationToken:
1266 case ThreadEnableAlignmentFaultFixup:
1267 case ThreadEventPair_Reusable:
1268 case ThreadQuerySetWin32StartAddress:
1269 case ThreadZeroTlsCell:
1270 case ThreadPerformanceCount:
1271 case ThreadIdealProcessor:
1272 case ThreadPriorityBoost:
1273 case ThreadSetTlsArrayAddress:
1274 case ThreadIsIoPending:
1276 FIXME( "info class %d not supported yet\n", class );
1277 return STATUS_NOT_IMPLEMENTED;
1282 /******************************************************************************
1283 * NtSetInformationThread (NTDLL.@)
1284 * ZwSetInformationThread (NTDLL.@)
1286 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1287 LPCVOID data, ULONG length )
1292 case ThreadZeroTlsCell:
1293 if (handle == GetCurrentThread())
1298 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1299 index = *(const DWORD *)data;
1300 if (index < TLS_MINIMUM_AVAILABLE)
1302 RtlAcquirePebLock();
1303 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1305 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1306 teb->TlsSlots[index] = 0;
1308 RtlReleasePebLock();
1312 index -= TLS_MINIMUM_AVAILABLE;
1313 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1314 return STATUS_INVALID_PARAMETER;
1315 RtlAcquirePebLock();
1316 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1318 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1319 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1321 RtlReleasePebLock();
1323 return STATUS_SUCCESS;
1325 FIXME( "ZeroTlsCell not supported on other threads\n" );
1326 return STATUS_NOT_IMPLEMENTED;
1328 case ThreadImpersonationToken:
1330 const HANDLE *phToken = data;
1331 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1332 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1333 SERVER_START_REQ( set_thread_info )
1335 req->handle = handle;
1336 req->token = *phToken;
1337 req->mask = SET_THREAD_INFO_TOKEN;
1338 status = wine_server_call( req );
1343 case ThreadBasePriority:
1345 const DWORD *pprio = data;
1346 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1347 SERVER_START_REQ( set_thread_info )
1349 req->handle = handle;
1350 req->priority = *pprio;
1351 req->mask = SET_THREAD_INFO_PRIORITY;
1352 status = wine_server_call( req );
1357 case ThreadAffinityMask:
1359 const DWORD *paff = data;
1360 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1361 SERVER_START_REQ( set_thread_info )
1363 req->handle = handle;
1364 req->affinity = *paff;
1365 req->mask = SET_THREAD_INFO_AFFINITY;
1366 status = wine_server_call( req );
1371 case ThreadBasicInformation:
1373 case ThreadPriority:
1374 case ThreadDescriptorTableEntry:
1375 case ThreadEnableAlignmentFaultFixup:
1376 case ThreadEventPair_Reusable:
1377 case ThreadQuerySetWin32StartAddress:
1378 case ThreadPerformanceCount:
1379 case ThreadAmILastThread:
1380 case ThreadIdealProcessor:
1381 case ThreadPriorityBoost:
1382 case ThreadSetTlsArrayAddress:
1383 case ThreadIsIoPending:
1385 FIXME( "info class %d not supported yet\n", class );
1386 return STATUS_NOT_IMPLEMENTED;
1391 /**********************************************************************
1392 * NtCurrentTeb (NTDLL.@)
1394 #if defined(__i386__) && defined(__GNUC__)
1396 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
1398 #elif defined(__i386__) && defined(_MSC_VER)
1400 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1404 /**********************************************************************/
1406 TEB * WINAPI NtCurrentTeb(void)
1408 return pthread_functions.get_current_teb();
1411 #endif /* __i386__ */