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);
47 /* info passed to a starting thread */
50 struct wine_pthread_thread_info pthread_info;
51 PRTL_THREAD_START_ROUTINE entry_point;
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 };
66 /***********************************************************************
69 static inline NTSTATUS init_teb( TEB *teb )
71 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
72 struct ntdll_thread_regs *thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
74 teb->Tib.ExceptionList = (void *)~0UL;
75 teb->Tib.StackBase = (void *)~0UL;
76 teb->Tib.Self = &teb->Tib;
77 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
78 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
80 if (!(thread_regs->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
81 thread_data->request_fd = -1;
82 thread_data->reply_fd = -1;
83 thread_data->wait_fd[0] = -1;
84 thread_data->wait_fd[1] = -1;
86 return STATUS_SUCCESS;
90 /***********************************************************************
93 * Make sure the unicode string doesn't point beyond the end pointer
95 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
97 if ((char *)str->Buffer >= end_ptr)
99 str->Length = str->MaximumLength = 0;
103 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
105 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
107 if (str->Length >= str->MaximumLength)
109 if (str->MaximumLength >= sizeof(WCHAR))
110 str->Length = str->MaximumLength - sizeof(WCHAR);
112 str->Length = str->MaximumLength = 0;
117 /***********************************************************************
118 * init_user_process_params
120 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
122 static NTSTATUS init_user_process_params( SIZE_T info_size, HANDLE *exe_file )
127 RTL_USER_PROCESS_PARAMETERS *params = NULL;
129 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &info_size,
130 MEM_COMMIT, PAGE_READWRITE );
131 if (status != STATUS_SUCCESS) return status;
133 params->AllocationSize = info_size;
134 NtCurrentTeb()->Peb->ProcessParameters = params;
136 SERVER_START_REQ( get_startup_info )
138 wine_server_set_reply( req, params, info_size );
139 if (!(status = wine_server_call( req )))
141 info_size = wine_server_reply_size( reply );
142 *exe_file = reply->exe_file;
143 params->hStdInput = reply->hstdin;
144 params->hStdOutput = reply->hstdout;
145 params->hStdError = reply->hstderr;
149 if (status != STATUS_SUCCESS) return status;
151 if (params->Size > info_size) params->Size = info_size;
153 /* make sure the strings are valid */
154 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
155 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
156 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
157 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
158 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
159 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
160 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
161 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
163 /* environment needs to be a separate memory block */
164 env_size = info_size - params->Size;
165 if (!env_size) env_size = 1;
167 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
168 MEM_COMMIT, PAGE_READWRITE );
169 if (status != STATUS_SUCCESS) return status;
170 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
171 params->Environment = ptr;
173 RtlNormalizeProcessParams( params );
178 /***********************************************************************
181 * Setup the initial thread.
183 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
185 HANDLE thread_init(void)
190 SIZE_T size, info_size;
192 struct ntdll_thread_data *thread_data;
193 struct ntdll_thread_regs *thread_regs;
194 struct wine_pthread_thread_info thread_info;
195 static struct debug_info debug_info; /* debug info for initial thread */
199 /* reserve space for shared user data */
201 addr = (void *)0x7ffe0000;
203 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE, PAGE_READONLY );
205 /* allocate and initialize the PEB */
209 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
210 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
213 peb->NumberOfProcessors = 1;
214 peb->ProcessParameters = ¶ms;
215 peb->TlsBitmap = &tls_bitmap;
216 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
218 params.CurrentDirectory.DosPath.Buffer = current_dir;
219 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
220 params.wShowWindow = 1; /* SW_SHOWNORMAL */
221 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
222 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
223 sizeof(peb->TlsExpansionBitmapBits) * 8 );
224 InitializeListHead( &ldr.InLoadOrderModuleList );
225 InitializeListHead( &ldr.InMemoryOrderModuleList );
226 InitializeListHead( &ldr.InInitializationOrderModuleList );
227 InitializeListHead( &tls_links );
229 /* allocate and initialize the initial TEB */
231 sigstack_total_size = get_signal_stack_total_size();
232 while (1 << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
233 assert( 1 << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
234 thread_info.teb_size = sigstack_total_size;
237 size = sigstack_total_size;
238 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
239 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
242 thread_info.teb_size = size;
244 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
245 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
246 thread_data->debug_info = &debug_info;
247 InsertHeadList( &tls_links, &teb->TlsLinks );
249 thread_info.stack_base = NULL;
250 thread_info.stack_size = 0;
251 thread_info.teb_base = teb;
252 thread_info.teb_sel = thread_regs->fs;
253 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
254 pthread_functions.init_current_teb( &thread_info );
255 pthread_functions.init_thread( &thread_info );
256 virtual_init_threading();
258 debug_info.str_pos = debug_info.strings;
259 debug_info.out_pos = debug_info.output;
262 /* setup the server connection */
263 server_init_process();
264 info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
266 /* create the process heap */
267 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
269 MESSAGE( "wine: failed to create the process heap\n" );
273 /* allocate user parameters */
276 init_user_process_params( info_size, &exe_file );
280 /* This is wine specific: we have no parent (we're started from unix)
281 * so, create a simple console with bare handles to unix stdio
283 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
284 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
285 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
290 typedef LONG (WINAPI *PUNHANDLED_EXCEPTION_FILTER)(PEXCEPTION_POINTERS);
291 static PUNHANDLED_EXCEPTION_FILTER get_unhandled_exception_filter(void)
293 static PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter;
294 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
295 UNICODE_STRING module_name;
296 ANSI_STRING func_name;
297 HMODULE kernel32_handle;
299 if (unhandled_exception_filter) return unhandled_exception_filter;
301 RtlInitUnicodeString(&module_name, kernel32W);
302 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
304 if (LdrGetDllHandle( 0, 0, &module_name, &kernel32_handle ) == STATUS_SUCCESS)
305 LdrGetProcedureAddress( kernel32_handle, &func_name, 0,
306 (void **)&unhandled_exception_filter );
308 return unhandled_exception_filter;
311 /***********************************************************************
314 * Startup routine for a newly created thread.
316 static void start_thread( struct wine_pthread_thread_info *info )
318 TEB *teb = info->teb_base;
319 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
320 struct startup_info *startup_info = (struct startup_info *)info;
321 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
322 void *arg = startup_info->entry_arg;
323 struct debug_info debug_info;
324 SIZE_T size, page_size = getpagesize();
326 debug_info.str_pos = debug_info.strings;
327 debug_info.out_pos = debug_info.output;
328 thread_data->debug_info = &debug_info;
330 pthread_functions.init_current_teb( info );
332 server_init_thread( info->pid, info->tid, func );
333 pthread_functions.init_thread( info );
335 /* allocate a memory view for the stack */
336 size = info->stack_size;
337 teb->DeallocationStack = info->stack_base;
338 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
339 &size, MEM_SYSTEM, PAGE_READWRITE );
340 /* limit is lower than base since the stack grows down */
341 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
342 teb->Tib.StackLimit = (char *)info->stack_base + page_size;
344 /* setup the guard page */
346 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, PAGE_NOACCESS, NULL );
347 RtlFreeHeap( GetProcessHeap(), 0, info );
350 InsertHeadList( &tls_links, &teb->TlsLinks );
353 /* NOTE: Windows does not have an exception handler around the call to
354 * the thread attach. We do for ease of debugging */
355 if (get_unhandled_exception_filter())
359 MODULE_DllThreadAttach( NULL );
361 __EXCEPT(get_unhandled_exception_filter())
363 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
368 MODULE_DllThreadAttach( NULL );
374 /***********************************************************************
375 * RtlCreateUserThread (NTDLL.@)
377 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
378 BOOLEAN suspended, PVOID stack_addr,
379 SIZE_T stack_reserve, SIZE_T stack_commit,
380 PRTL_THREAD_START_ROUTINE start, void *param,
381 HANDLE *handle_ptr, CLIENT_ID *id )
383 struct ntdll_thread_data *thread_data;
384 struct ntdll_thread_regs *thread_regs = NULL;
385 struct startup_info *info = NULL;
392 SIZE_T size, page_size = getpagesize();
394 if( ! is_current_process( process ) )
396 ERR("Unsupported on other process\n");
397 return STATUS_ACCESS_DENIED;
400 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
401 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
402 wine_server_send_fd( request_pipe[0] );
404 SERVER_START_REQ( new_thread )
406 req->access = THREAD_ALL_ACCESS;
407 req->attributes = 0; /* FIXME */
408 req->suspend = suspended;
409 req->request_fd = request_pipe[0];
410 if (!(status = wine_server_call( req )))
412 handle = reply->handle;
415 close( request_pipe[0] );
419 if (status) goto error;
421 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
423 status = STATUS_NO_MEMORY;
428 size = sigstack_total_size;
429 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
430 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
433 teb->Peb = NtCurrentTeb()->Peb;
434 info->pthread_info.teb_size = size;
435 if ((status = init_teb( teb ))) goto error;
437 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
438 teb->ClientId.UniqueThread = (HANDLE)tid;
440 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
441 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
442 thread_data->request_fd = request_pipe[1];
444 info->pthread_info.teb_base = teb;
445 info->pthread_info.teb_sel = thread_regs->fs;
447 /* inherit debug registers from parent thread */
448 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
449 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
450 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
451 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
452 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
453 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
455 if (!stack_reserve || !stack_commit)
457 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
458 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
459 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
461 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
462 stack_reserve += page_size; /* for the guard page */
463 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
464 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
466 info->pthread_info.stack_base = NULL;
467 info->pthread_info.stack_size = stack_reserve;
468 info->pthread_info.entry = start_thread;
469 info->entry_point = start;
470 info->entry_arg = param;
472 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
474 status = STATUS_NO_MEMORY;
478 if (id) id->UniqueThread = (HANDLE)tid;
479 if (handle_ptr) *handle_ptr = handle;
480 else NtClose( handle );
482 return STATUS_SUCCESS;
485 if (thread_regs) wine_ldt_free_fs( thread_regs->fs );
489 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
491 RtlFreeHeap( GetProcessHeap(), 0, info );
492 if (handle) NtClose( handle );
493 close( request_pipe[1] );
498 /***********************************************************************
499 * RtlExitUserThread (NTDLL.@)
501 void WINAPI RtlExitUserThread( ULONG status )
504 server_exit_thread( status );
508 /***********************************************************************
509 * NtOpenThread (NTDLL.@)
510 * ZwOpenThread (NTDLL.@)
512 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
513 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
517 SERVER_START_REQ( open_thread )
519 req->tid = (thread_id_t)id->UniqueThread;
520 req->access = access;
521 req->attributes = attr ? attr->Attributes : 0;
522 ret = wine_server_call( req );
523 *handle = reply->handle;
530 /******************************************************************************
531 * NtSuspendThread (NTDLL.@)
532 * ZwSuspendThread (NTDLL.@)
534 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
538 SERVER_START_REQ( suspend_thread )
540 req->handle = handle;
541 if (!(ret = wine_server_call( req ))) *count = reply->count;
548 /******************************************************************************
549 * NtResumeThread (NTDLL.@)
550 * ZwResumeThread (NTDLL.@)
552 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
556 SERVER_START_REQ( resume_thread )
558 req->handle = handle;
559 if (!(ret = wine_server_call( req ))) *count = reply->count;
566 /******************************************************************************
567 * NtAlertResumeThread (NTDLL.@)
568 * ZwAlertResumeThread (NTDLL.@)
570 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
572 FIXME( "stub: should alert thread %p\n", handle );
573 return NtResumeThread( handle, count );
577 /******************************************************************************
578 * NtAlertThread (NTDLL.@)
579 * ZwAlertThread (NTDLL.@)
581 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
583 FIXME( "stub: %p\n", handle );
584 return STATUS_NOT_IMPLEMENTED;
588 /******************************************************************************
589 * NtTerminateThread (NTDLL.@)
590 * ZwTerminateThread (NTDLL.@)
592 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
597 SERVER_START_REQ( terminate_thread )
599 req->handle = handle;
600 req->exit_code = exit_code;
601 ret = wine_server_call( req );
602 self = !ret && reply->self;
609 if (last) exit( exit_code );
610 else server_abort_thread( exit_code );
616 /******************************************************************************
617 * NtQueueApcThread (NTDLL.@)
619 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
620 ULONG_PTR arg2, ULONG_PTR arg3 )
623 SERVER_START_REQ( queue_apc )
625 req->handle = handle;
628 req->call.type = APC_USER;
629 req->call.user.func = func;
630 req->call.user.args[0] = arg1;
631 req->call.user.args[1] = arg2;
632 req->call.user.args[2] = arg3;
634 else req->call.type = APC_NONE; /* wake up only */
635 ret = wine_server_call( req );
642 /***********************************************************************
643 * NtSetContextThread (NTDLL.@)
644 * ZwSetContextThread (NTDLL.@)
646 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
653 /* on i386 debug registers always require a server call */
654 self = (handle == GetCurrentThread());
655 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
657 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
658 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
659 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
660 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
666 SERVER_START_REQ( set_thread_context )
668 req->handle = handle;
669 req->flags = context->ContextFlags;
671 wine_server_add_data( req, context, sizeof(*context) );
672 ret = wine_server_call( req );
677 if (ret == STATUS_PENDING)
679 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
681 for (i = 0; i < 100; i++)
683 SERVER_START_REQ( set_thread_context )
685 req->handle = handle;
686 req->flags = context->ContextFlags;
688 wine_server_add_data( req, context, sizeof(*context) );
689 ret = wine_server_call( req );
692 if (ret != STATUS_PENDING) break;
695 NtResumeThread( handle, &dummy );
697 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
703 if (self) set_cpu_context( context );
704 return STATUS_SUCCESS;
708 /* copy a context structure according to the flags */
709 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
712 flags &= ~CONTEXT_i386; /* get rid of CPU id */
713 if (flags & CONTEXT_INTEGER)
722 if (flags & CONTEXT_CONTROL)
727 to->SegCs = from->SegCs;
728 to->SegSs = from->SegSs;
729 to->EFlags = from->EFlags;
731 if (flags & CONTEXT_SEGMENTS)
733 to->SegDs = from->SegDs;
734 to->SegEs = from->SegEs;
735 to->SegFs = from->SegFs;
736 to->SegGs = from->SegGs;
738 if (flags & CONTEXT_DEBUG_REGISTERS)
747 if (flags & CONTEXT_FLOATING_POINT)
749 to->FloatSave = from->FloatSave;
751 #elif defined(__x86_64__)
752 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
753 if (flags & CONTEXT_CONTROL)
758 to->SegCs = from->SegCs;
759 to->SegSs = from->SegSs;
760 to->EFlags = from->EFlags;
761 to->MxCsr = from->MxCsr;
763 if (flags & CONTEXT_INTEGER)
780 if (flags & CONTEXT_SEGMENTS)
782 to->SegDs = from->SegDs;
783 to->SegEs = from->SegEs;
784 to->SegFs = from->SegFs;
785 to->SegGs = from->SegGs;
787 if (flags & CONTEXT_FLOATING_POINT)
789 to->u.FltSave = from->u.FltSave;
791 if (flags & CONTEXT_DEBUG_REGISTERS)
800 #elif defined(__sparc__)
801 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
802 if (flags & CONTEXT_CONTROL)
811 if (flags & CONTEXT_INTEGER)
846 if (flags & CONTEXT_FLOATING_POINT)
850 #elif defined(__powerpc__)
852 if (flags & CONTEXT_CONTROL)
858 if (flags & CONTEXT_INTEGER)
860 to->Gpr0 = from->Gpr0;
861 to->Gpr1 = from->Gpr1;
862 to->Gpr2 = from->Gpr2;
863 to->Gpr3 = from->Gpr3;
864 to->Gpr4 = from->Gpr4;
865 to->Gpr5 = from->Gpr5;
866 to->Gpr6 = from->Gpr6;
867 to->Gpr7 = from->Gpr7;
868 to->Gpr8 = from->Gpr8;
869 to->Gpr9 = from->Gpr9;
870 to->Gpr10 = from->Gpr10;
871 to->Gpr11 = from->Gpr11;
872 to->Gpr12 = from->Gpr12;
873 to->Gpr13 = from->Gpr13;
874 to->Gpr14 = from->Gpr14;
875 to->Gpr15 = from->Gpr15;
876 to->Gpr16 = from->Gpr16;
877 to->Gpr17 = from->Gpr17;
878 to->Gpr18 = from->Gpr18;
879 to->Gpr19 = from->Gpr19;
880 to->Gpr20 = from->Gpr20;
881 to->Gpr21 = from->Gpr21;
882 to->Gpr22 = from->Gpr22;
883 to->Gpr23 = from->Gpr23;
884 to->Gpr24 = from->Gpr24;
885 to->Gpr25 = from->Gpr25;
886 to->Gpr26 = from->Gpr26;
887 to->Gpr27 = from->Gpr27;
888 to->Gpr28 = from->Gpr28;
889 to->Gpr29 = from->Gpr29;
890 to->Gpr30 = from->Gpr30;
891 to->Gpr31 = from->Gpr31;
895 if (flags & CONTEXT_FLOATING_POINT)
897 to->Fpr0 = from->Fpr0;
898 to->Fpr1 = from->Fpr1;
899 to->Fpr2 = from->Fpr2;
900 to->Fpr3 = from->Fpr3;
901 to->Fpr4 = from->Fpr4;
902 to->Fpr5 = from->Fpr5;
903 to->Fpr6 = from->Fpr6;
904 to->Fpr7 = from->Fpr7;
905 to->Fpr8 = from->Fpr8;
906 to->Fpr9 = from->Fpr9;
907 to->Fpr10 = from->Fpr10;
908 to->Fpr11 = from->Fpr11;
909 to->Fpr12 = from->Fpr12;
910 to->Fpr13 = from->Fpr13;
911 to->Fpr14 = from->Fpr14;
912 to->Fpr15 = from->Fpr15;
913 to->Fpr16 = from->Fpr16;
914 to->Fpr17 = from->Fpr17;
915 to->Fpr18 = from->Fpr18;
916 to->Fpr19 = from->Fpr19;
917 to->Fpr20 = from->Fpr20;
918 to->Fpr21 = from->Fpr21;
919 to->Fpr22 = from->Fpr22;
920 to->Fpr23 = from->Fpr23;
921 to->Fpr24 = from->Fpr24;
922 to->Fpr25 = from->Fpr25;
923 to->Fpr26 = from->Fpr26;
924 to->Fpr27 = from->Fpr27;
925 to->Fpr28 = from->Fpr28;
926 to->Fpr29 = from->Fpr29;
927 to->Fpr30 = from->Fpr30;
928 to->Fpr31 = from->Fpr31;
929 to->Fpscr = from->Fpscr;
932 #error You must implement context copying for your CPU
937 /***********************************************************************
938 * NtGetContextThread (NTDLL.@)
939 * ZwGetContextThread (NTDLL.@)
941 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
946 DWORD needed_flags = context->ContextFlags;
947 BOOL self = (handle == GetCurrentThread());
950 /* on i386 debug registers always require a server call */
951 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
956 SERVER_START_REQ( get_thread_context )
958 req->handle = handle;
959 req->flags = context->ContextFlags;
961 wine_server_set_reply( req, &ctx, sizeof(ctx) );
962 ret = wine_server_call( req );
967 if (ret == STATUS_PENDING)
969 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
971 for (i = 0; i < 100; i++)
973 SERVER_START_REQ( get_thread_context )
975 req->handle = handle;
976 req->flags = context->ContextFlags;
978 wine_server_set_reply( req, &ctx, sizeof(ctx) );
979 ret = wine_server_call( req );
982 if (ret != STATUS_PENDING) break;
985 NtResumeThread( handle, &dummy );
987 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
990 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
991 needed_flags &= ~ctx.ContextFlags;
998 get_cpu_context( &ctx );
999 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1002 /* update the cached version of the debug registers */
1003 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1005 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1006 regs->dr0 = context->Dr0;
1007 regs->dr1 = context->Dr1;
1008 regs->dr2 = context->Dr2;
1009 regs->dr3 = context->Dr3;
1010 regs->dr6 = context->Dr6;
1011 regs->dr7 = context->Dr7;
1015 return STATUS_SUCCESS;
1019 /******************************************************************************
1020 * NtQueryInformationThread (NTDLL.@)
1021 * ZwQueryInformationThread (NTDLL.@)
1023 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1024 void *data, ULONG length, ULONG *ret_len )
1030 case ThreadBasicInformation:
1032 THREAD_BASIC_INFORMATION info;
1034 SERVER_START_REQ( get_thread_info )
1036 req->handle = handle;
1038 if (!(status = wine_server_call( req )))
1040 info.ExitStatus = reply->exit_code;
1041 info.TebBaseAddress = reply->teb;
1042 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
1043 info.ClientId.UniqueThread = (HANDLE)reply->tid;
1044 info.AffinityMask = reply->affinity;
1045 info.Priority = reply->priority;
1046 info.BasePriority = reply->priority; /* FIXME */
1050 if (status == STATUS_SUCCESS)
1052 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1053 if (ret_len) *ret_len = min( length, sizeof(info) );
1059 KERNEL_USER_TIMES kusrt;
1060 /* We need to do a server call to get the creation time or exit time */
1061 /* This works on any thread */
1062 SERVER_START_REQ( get_thread_info )
1064 req->handle = handle;
1066 status = wine_server_call( req );
1067 if (status == STATUS_SUCCESS)
1069 NTDLL_from_server_abstime( &kusrt.CreateTime, &reply->creation_time );
1070 NTDLL_from_server_abstime( &kusrt.ExitTime, &reply->exit_time );
1074 if (status == STATUS_SUCCESS)
1076 /* We call times(2) for kernel time or user time */
1077 /* We can only (portably) do this for the current thread */
1078 if (handle == GetCurrentThread())
1080 struct tms time_buf;
1081 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1084 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1085 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1089 kusrt.KernelTime.QuadPart = 0;
1090 kusrt.UserTime.QuadPart = 0;
1091 FIXME("Cannot get kerneltime or usertime of other threads\n");
1093 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1094 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1098 case ThreadDescriptorTableEntry:
1101 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1102 if (length < sizeof(*tdi))
1103 status = STATUS_INFO_LENGTH_MISMATCH;
1104 else if (!(tdi->Selector & 4)) /* GDT selector */
1106 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1107 status = STATUS_SUCCESS;
1108 if (!sel) /* null selector */
1109 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1112 tdi->Entry.BaseLow = 0;
1113 tdi->Entry.HighWord.Bits.BaseMid = 0;
1114 tdi->Entry.HighWord.Bits.BaseHi = 0;
1115 tdi->Entry.LimitLow = 0xffff;
1116 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1117 tdi->Entry.HighWord.Bits.Dpl = 3;
1118 tdi->Entry.HighWord.Bits.Sys = 0;
1119 tdi->Entry.HighWord.Bits.Pres = 1;
1120 tdi->Entry.HighWord.Bits.Granularity = 1;
1121 tdi->Entry.HighWord.Bits.Default_Big = 1;
1122 tdi->Entry.HighWord.Bits.Type = 0x12;
1123 /* it has to be one of the system GDT selectors */
1124 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1126 if (sel == (wine_get_cs() & ~3))
1127 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1128 else status = STATUS_ACCESS_DENIED;
1134 SERVER_START_REQ( get_selector_entry )
1136 req->handle = handle;
1137 req->entry = tdi->Selector >> 3;
1138 status = wine_server_call( req );
1141 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1142 status = STATUS_ACCESS_VIOLATION;
1145 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1146 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1147 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1153 if (status == STATUS_SUCCESS && ret_len)
1154 /* yes, that's a bit strange, but it's the way it is */
1155 *ret_len = sizeof(LDT_ENTRY);
1157 status = STATUS_NOT_IMPLEMENTED;
1161 case ThreadAmILastThread:
1163 SERVER_START_REQ(get_thread_info)
1165 req->handle = handle;
1167 status = wine_server_call( req );
1168 if (status == STATUS_SUCCESS)
1170 BOOLEAN last = reply->last;
1171 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1172 if (ret_len) *ret_len = min( length, sizeof(last) );
1178 case ThreadPriority:
1179 case ThreadBasePriority:
1180 case ThreadAffinityMask:
1181 case ThreadImpersonationToken:
1182 case ThreadEnableAlignmentFaultFixup:
1183 case ThreadEventPair_Reusable:
1184 case ThreadQuerySetWin32StartAddress:
1185 case ThreadZeroTlsCell:
1186 case ThreadPerformanceCount:
1187 case ThreadIdealProcessor:
1188 case ThreadPriorityBoost:
1189 case ThreadSetTlsArrayAddress:
1190 case ThreadIsIoPending:
1192 FIXME( "info class %d not supported yet\n", class );
1193 return STATUS_NOT_IMPLEMENTED;
1198 /******************************************************************************
1199 * NtSetInformationThread (NTDLL.@)
1200 * ZwSetInformationThread (NTDLL.@)
1202 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1203 LPCVOID data, ULONG length )
1208 case ThreadZeroTlsCell:
1209 if (handle == GetCurrentThread())
1214 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1215 index = *(const DWORD *)data;
1216 if (index < TLS_MINIMUM_AVAILABLE)
1218 RtlAcquirePebLock();
1219 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1221 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1222 teb->TlsSlots[index] = 0;
1224 RtlReleasePebLock();
1228 index -= TLS_MINIMUM_AVAILABLE;
1229 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1230 return STATUS_INVALID_PARAMETER;
1231 RtlAcquirePebLock();
1232 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1234 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1235 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1237 RtlReleasePebLock();
1239 return STATUS_SUCCESS;
1241 FIXME( "ZeroTlsCell not supported on other threads\n" );
1242 return STATUS_NOT_IMPLEMENTED;
1244 case ThreadImpersonationToken:
1246 const HANDLE *phToken = data;
1247 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1248 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1249 SERVER_START_REQ( set_thread_info )
1251 req->handle = handle;
1252 req->token = *phToken;
1253 req->mask = SET_THREAD_INFO_TOKEN;
1254 status = wine_server_call( req );
1259 case ThreadBasePriority:
1261 const DWORD *pprio = data;
1262 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1263 SERVER_START_REQ( set_thread_info )
1265 req->handle = handle;
1266 req->priority = *pprio;
1267 req->mask = SET_THREAD_INFO_PRIORITY;
1268 status = wine_server_call( req );
1273 case ThreadAffinityMask:
1275 const DWORD *paff = data;
1276 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1277 SERVER_START_REQ( set_thread_info )
1279 req->handle = handle;
1280 req->affinity = *paff;
1281 req->mask = SET_THREAD_INFO_AFFINITY;
1282 status = wine_server_call( req );
1287 case ThreadBasicInformation:
1289 case ThreadPriority:
1290 case ThreadDescriptorTableEntry:
1291 case ThreadEnableAlignmentFaultFixup:
1292 case ThreadEventPair_Reusable:
1293 case ThreadQuerySetWin32StartAddress:
1294 case ThreadPerformanceCount:
1295 case ThreadAmILastThread:
1296 case ThreadIdealProcessor:
1297 case ThreadPriorityBoost:
1298 case ThreadSetTlsArrayAddress:
1299 case ThreadIsIoPending:
1301 FIXME( "info class %d not supported yet\n", class );
1302 return STATUS_NOT_IMPLEMENTED;
1307 /**********************************************************************
1308 * NtCurrentTeb (NTDLL.@)
1310 #if defined(__i386__) && defined(__GNUC__)
1312 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
1314 #elif defined(__i386__) && defined(_MSC_VER)
1316 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1320 /**********************************************************************/
1322 TEB * WINAPI NtCurrentTeb(void)
1324 return pthread_functions.get_current_teb();
1327 #endif /* __i386__ */