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 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
235 thread_info.teb_size = sigstack_total_size;
238 size = sigstack_total_size;
239 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
240 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
243 thread_info.teb_size = size;
245 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
246 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
247 thread_data->debug_info = &debug_info;
248 InsertHeadList( &tls_links, &teb->TlsLinks );
250 thread_info.stack_base = NULL;
251 thread_info.stack_size = 0;
252 thread_info.teb_base = teb;
253 thread_info.teb_sel = thread_regs->fs;
254 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
255 pthread_functions.init_current_teb( &thread_info );
256 pthread_functions.init_thread( &thread_info );
257 virtual_init_threading();
259 debug_info.str_pos = debug_info.strings;
260 debug_info.out_pos = debug_info.output;
263 /* setup the server connection */
264 server_init_process();
265 info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
267 /* create the process heap */
268 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
270 MESSAGE( "wine: failed to create the process heap\n" );
274 /* allocate user parameters */
277 init_user_process_params( info_size, &exe_file );
281 /* This is wine specific: we have no parent (we're started from unix)
282 * so, create a simple console with bare handles to unix stdio
284 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
285 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
286 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
291 typedef LONG (WINAPI *PUNHANDLED_EXCEPTION_FILTER)(PEXCEPTION_POINTERS);
292 static PUNHANDLED_EXCEPTION_FILTER get_unhandled_exception_filter(void)
294 static PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter;
295 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
296 UNICODE_STRING module_name;
297 ANSI_STRING func_name;
298 HMODULE kernel32_handle;
300 if (unhandled_exception_filter) return unhandled_exception_filter;
302 RtlInitUnicodeString(&module_name, kernel32W);
303 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
305 if (LdrGetDllHandle( 0, 0, &module_name, &kernel32_handle ) == STATUS_SUCCESS)
306 LdrGetProcedureAddress( kernel32_handle, &func_name, 0,
307 (void **)&unhandled_exception_filter );
309 return unhandled_exception_filter;
312 /***********************************************************************
315 * Startup routine for a newly created thread.
317 static void start_thread( struct wine_pthread_thread_info *info )
319 TEB *teb = info->teb_base;
320 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
321 struct startup_info *startup_info = (struct startup_info *)info;
322 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
323 void *arg = startup_info->entry_arg;
324 struct debug_info debug_info;
325 SIZE_T size, page_size = getpagesize();
327 debug_info.str_pos = debug_info.strings;
328 debug_info.out_pos = debug_info.output;
329 thread_data->debug_info = &debug_info;
331 pthread_functions.init_current_teb( info );
333 server_init_thread( info->pid, info->tid, func );
334 pthread_functions.init_thread( info );
336 /* allocate a memory view for the stack */
337 size = info->stack_size;
338 teb->DeallocationStack = info->stack_base;
339 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
340 &size, MEM_SYSTEM, PAGE_READWRITE );
341 /* limit is lower than base since the stack grows down */
342 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
343 teb->Tib.StackLimit = (char *)info->stack_base + page_size;
345 /* setup the guard page */
347 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, PAGE_NOACCESS, NULL );
349 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
352 InsertHeadList( &tls_links, &teb->TlsLinks );
355 /* NOTE: Windows does not have an exception handler around the call to
356 * the thread attach. We do for ease of debugging */
357 if (get_unhandled_exception_filter())
361 MODULE_DllThreadAttach( NULL );
363 __EXCEPT(get_unhandled_exception_filter())
365 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
370 MODULE_DllThreadAttach( NULL );
376 /***********************************************************************
377 * RtlCreateUserThread (NTDLL.@)
379 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
380 BOOLEAN suspended, PVOID stack_addr,
381 SIZE_T stack_reserve, SIZE_T stack_commit,
382 PRTL_THREAD_START_ROUTINE start, void *param,
383 HANDLE *handle_ptr, CLIENT_ID *id )
386 struct ntdll_thread_data *thread_data;
387 struct ntdll_thread_regs *thread_regs = NULL;
388 struct startup_info *info = NULL;
395 SIZE_T size, page_size = getpagesize();
397 if( ! is_current_process( process ) )
399 ERR("Unsupported on other process\n");
400 return STATUS_ACCESS_DENIED;
403 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
404 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
405 wine_server_send_fd( request_pipe[0] );
407 SERVER_START_REQ( new_thread )
409 req->access = THREAD_ALL_ACCESS;
410 req->attributes = 0; /* FIXME */
411 req->suspend = suspended;
412 req->request_fd = request_pipe[0];
413 if (!(status = wine_server_call( req )))
415 handle = reply->handle;
418 close( request_pipe[0] );
424 close( request_pipe[1] );
428 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
431 size = sigstack_total_size;
432 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
433 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
436 teb->Peb = NtCurrentTeb()->Peb;
437 info = (struct startup_info *)(teb + 1);
438 info->pthread_info.teb_size = size;
439 if ((status = init_teb( teb ))) goto error;
441 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
442 teb->ClientId.UniqueThread = (HANDLE)tid;
444 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
445 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
446 thread_data->request_fd = request_pipe[1];
448 info->pthread_info.teb_base = teb;
449 info->pthread_info.teb_sel = thread_regs->fs;
451 /* inherit debug registers from parent thread */
452 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
453 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
454 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
455 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
456 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
457 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
459 if (!stack_reserve || !stack_commit)
461 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
462 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
463 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
465 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
466 stack_reserve += page_size; /* for the guard page */
467 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
468 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
470 info->pthread_info.stack_base = NULL;
471 info->pthread_info.stack_size = stack_reserve;
472 info->pthread_info.entry = start_thread;
473 info->entry_point = start;
474 info->entry_arg = param;
476 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
478 status = STATUS_NO_MEMORY;
481 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
483 if (id) id->UniqueThread = (HANDLE)tid;
484 if (handle_ptr) *handle_ptr = handle;
485 else NtClose( handle );
487 return STATUS_SUCCESS;
490 if (thread_regs) wine_ldt_free_fs( thread_regs->fs );
494 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
496 if (handle) NtClose( handle );
497 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
498 close( request_pipe[1] );
503 /***********************************************************************
504 * RtlExitUserThread (NTDLL.@)
506 void WINAPI RtlExitUserThread( ULONG status )
509 server_exit_thread( status );
513 /***********************************************************************
514 * NtOpenThread (NTDLL.@)
515 * ZwOpenThread (NTDLL.@)
517 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
518 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
522 SERVER_START_REQ( open_thread )
524 req->tid = (thread_id_t)id->UniqueThread;
525 req->access = access;
526 req->attributes = attr ? attr->Attributes : 0;
527 ret = wine_server_call( req );
528 *handle = reply->handle;
535 /******************************************************************************
536 * NtSuspendThread (NTDLL.@)
537 * ZwSuspendThread (NTDLL.@)
539 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
543 SERVER_START_REQ( suspend_thread )
545 req->handle = handle;
546 if (!(ret = wine_server_call( req ))) *count = reply->count;
553 /******************************************************************************
554 * NtResumeThread (NTDLL.@)
555 * ZwResumeThread (NTDLL.@)
557 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
561 SERVER_START_REQ( resume_thread )
563 req->handle = handle;
564 if (!(ret = wine_server_call( req ))) *count = reply->count;
571 /******************************************************************************
572 * NtAlertResumeThread (NTDLL.@)
573 * ZwAlertResumeThread (NTDLL.@)
575 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
577 FIXME( "stub: should alert thread %p\n", handle );
578 return NtResumeThread( handle, count );
582 /******************************************************************************
583 * NtAlertThread (NTDLL.@)
584 * ZwAlertThread (NTDLL.@)
586 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
588 FIXME( "stub: %p\n", handle );
589 return STATUS_NOT_IMPLEMENTED;
593 /******************************************************************************
594 * NtTerminateThread (NTDLL.@)
595 * ZwTerminateThread (NTDLL.@)
597 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
602 SERVER_START_REQ( terminate_thread )
604 req->handle = handle;
605 req->exit_code = exit_code;
606 ret = wine_server_call( req );
607 self = !ret && reply->self;
614 if (last) exit( exit_code );
615 else server_abort_thread( exit_code );
621 /******************************************************************************
622 * NtQueueApcThread (NTDLL.@)
624 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
625 ULONG_PTR arg2, ULONG_PTR arg3 )
628 SERVER_START_REQ( queue_apc )
630 req->thread = handle;
633 req->call.type = APC_USER;
634 req->call.user.func = func;
635 req->call.user.args[0] = arg1;
636 req->call.user.args[1] = arg2;
637 req->call.user.args[2] = arg3;
639 else req->call.type = APC_NONE; /* wake up only */
640 ret = wine_server_call( req );
647 /***********************************************************************
648 * NtSetContextThread (NTDLL.@)
649 * ZwSetContextThread (NTDLL.@)
651 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
658 /* on i386 debug registers always require a server call */
659 self = (handle == GetCurrentThread());
660 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
662 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
663 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
664 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
665 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
671 SERVER_START_REQ( set_thread_context )
673 req->handle = handle;
674 req->flags = context->ContextFlags;
676 wine_server_add_data( req, context, sizeof(*context) );
677 ret = wine_server_call( req );
682 if (ret == STATUS_PENDING)
684 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
686 for (i = 0; i < 100; i++)
688 SERVER_START_REQ( set_thread_context )
690 req->handle = handle;
691 req->flags = context->ContextFlags;
693 wine_server_add_data( req, context, sizeof(*context) );
694 ret = wine_server_call( req );
697 if (ret != STATUS_PENDING) break;
700 NtResumeThread( handle, &dummy );
702 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
708 if (self) set_cpu_context( context );
709 return STATUS_SUCCESS;
713 /* copy a context structure according to the flags */
714 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
717 flags &= ~CONTEXT_i386; /* get rid of CPU id */
718 if (flags & CONTEXT_INTEGER)
727 if (flags & CONTEXT_CONTROL)
732 to->SegCs = from->SegCs;
733 to->SegSs = from->SegSs;
734 to->EFlags = from->EFlags;
736 if (flags & CONTEXT_SEGMENTS)
738 to->SegDs = from->SegDs;
739 to->SegEs = from->SegEs;
740 to->SegFs = from->SegFs;
741 to->SegGs = from->SegGs;
743 if (flags & CONTEXT_DEBUG_REGISTERS)
752 if (flags & CONTEXT_FLOATING_POINT)
754 to->FloatSave = from->FloatSave;
756 #elif defined(__x86_64__)
757 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
758 if (flags & CONTEXT_CONTROL)
763 to->SegCs = from->SegCs;
764 to->SegSs = from->SegSs;
765 to->EFlags = from->EFlags;
766 to->MxCsr = from->MxCsr;
768 if (flags & CONTEXT_INTEGER)
785 if (flags & CONTEXT_SEGMENTS)
787 to->SegDs = from->SegDs;
788 to->SegEs = from->SegEs;
789 to->SegFs = from->SegFs;
790 to->SegGs = from->SegGs;
792 if (flags & CONTEXT_FLOATING_POINT)
794 to->u.FltSave = from->u.FltSave;
796 if (flags & CONTEXT_DEBUG_REGISTERS)
805 #elif defined(__sparc__)
806 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
807 if (flags & CONTEXT_CONTROL)
816 if (flags & CONTEXT_INTEGER)
851 if (flags & CONTEXT_FLOATING_POINT)
855 #elif defined(__powerpc__)
857 if (flags & CONTEXT_CONTROL)
863 if (flags & CONTEXT_INTEGER)
865 to->Gpr0 = from->Gpr0;
866 to->Gpr1 = from->Gpr1;
867 to->Gpr2 = from->Gpr2;
868 to->Gpr3 = from->Gpr3;
869 to->Gpr4 = from->Gpr4;
870 to->Gpr5 = from->Gpr5;
871 to->Gpr6 = from->Gpr6;
872 to->Gpr7 = from->Gpr7;
873 to->Gpr8 = from->Gpr8;
874 to->Gpr9 = from->Gpr9;
875 to->Gpr10 = from->Gpr10;
876 to->Gpr11 = from->Gpr11;
877 to->Gpr12 = from->Gpr12;
878 to->Gpr13 = from->Gpr13;
879 to->Gpr14 = from->Gpr14;
880 to->Gpr15 = from->Gpr15;
881 to->Gpr16 = from->Gpr16;
882 to->Gpr17 = from->Gpr17;
883 to->Gpr18 = from->Gpr18;
884 to->Gpr19 = from->Gpr19;
885 to->Gpr20 = from->Gpr20;
886 to->Gpr21 = from->Gpr21;
887 to->Gpr22 = from->Gpr22;
888 to->Gpr23 = from->Gpr23;
889 to->Gpr24 = from->Gpr24;
890 to->Gpr25 = from->Gpr25;
891 to->Gpr26 = from->Gpr26;
892 to->Gpr27 = from->Gpr27;
893 to->Gpr28 = from->Gpr28;
894 to->Gpr29 = from->Gpr29;
895 to->Gpr30 = from->Gpr30;
896 to->Gpr31 = from->Gpr31;
900 if (flags & CONTEXT_FLOATING_POINT)
902 to->Fpr0 = from->Fpr0;
903 to->Fpr1 = from->Fpr1;
904 to->Fpr2 = from->Fpr2;
905 to->Fpr3 = from->Fpr3;
906 to->Fpr4 = from->Fpr4;
907 to->Fpr5 = from->Fpr5;
908 to->Fpr6 = from->Fpr6;
909 to->Fpr7 = from->Fpr7;
910 to->Fpr8 = from->Fpr8;
911 to->Fpr9 = from->Fpr9;
912 to->Fpr10 = from->Fpr10;
913 to->Fpr11 = from->Fpr11;
914 to->Fpr12 = from->Fpr12;
915 to->Fpr13 = from->Fpr13;
916 to->Fpr14 = from->Fpr14;
917 to->Fpr15 = from->Fpr15;
918 to->Fpr16 = from->Fpr16;
919 to->Fpr17 = from->Fpr17;
920 to->Fpr18 = from->Fpr18;
921 to->Fpr19 = from->Fpr19;
922 to->Fpr20 = from->Fpr20;
923 to->Fpr21 = from->Fpr21;
924 to->Fpr22 = from->Fpr22;
925 to->Fpr23 = from->Fpr23;
926 to->Fpr24 = from->Fpr24;
927 to->Fpr25 = from->Fpr25;
928 to->Fpr26 = from->Fpr26;
929 to->Fpr27 = from->Fpr27;
930 to->Fpr28 = from->Fpr28;
931 to->Fpr29 = from->Fpr29;
932 to->Fpr30 = from->Fpr30;
933 to->Fpr31 = from->Fpr31;
934 to->Fpscr = from->Fpscr;
937 #error You must implement context copying for your CPU
942 /***********************************************************************
943 * NtGetContextThread (NTDLL.@)
944 * ZwGetContextThread (NTDLL.@)
946 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
951 DWORD needed_flags = context->ContextFlags;
952 BOOL self = (handle == GetCurrentThread());
955 /* on i386 debug registers always require a server call */
956 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
961 SERVER_START_REQ( get_thread_context )
963 req->handle = handle;
964 req->flags = context->ContextFlags;
966 wine_server_set_reply( req, &ctx, sizeof(ctx) );
967 ret = wine_server_call( req );
972 if (ret == STATUS_PENDING)
974 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
976 for (i = 0; i < 100; i++)
978 SERVER_START_REQ( get_thread_context )
980 req->handle = handle;
981 req->flags = context->ContextFlags;
983 wine_server_set_reply( req, &ctx, sizeof(ctx) );
984 ret = wine_server_call( req );
987 if (ret != STATUS_PENDING) break;
990 NtResumeThread( handle, &dummy );
992 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
995 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
996 needed_flags &= ~ctx.ContextFlags;
1003 get_cpu_context( &ctx );
1004 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1007 /* update the cached version of the debug registers */
1008 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1010 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1011 regs->dr0 = context->Dr0;
1012 regs->dr1 = context->Dr1;
1013 regs->dr2 = context->Dr2;
1014 regs->dr3 = context->Dr3;
1015 regs->dr6 = context->Dr6;
1016 regs->dr7 = context->Dr7;
1020 return STATUS_SUCCESS;
1024 /******************************************************************************
1025 * NtQueryInformationThread (NTDLL.@)
1026 * ZwQueryInformationThread (NTDLL.@)
1028 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1029 void *data, ULONG length, ULONG *ret_len )
1035 case ThreadBasicInformation:
1037 THREAD_BASIC_INFORMATION info;
1039 SERVER_START_REQ( get_thread_info )
1041 req->handle = handle;
1043 if (!(status = wine_server_call( req )))
1045 info.ExitStatus = reply->exit_code;
1046 info.TebBaseAddress = reply->teb;
1047 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
1048 info.ClientId.UniqueThread = (HANDLE)reply->tid;
1049 info.AffinityMask = reply->affinity;
1050 info.Priority = reply->priority;
1051 info.BasePriority = reply->priority; /* FIXME */
1055 if (status == STATUS_SUCCESS)
1057 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1058 if (ret_len) *ret_len = min( length, sizeof(info) );
1064 KERNEL_USER_TIMES kusrt;
1065 /* We need to do a server call to get the creation time or exit time */
1066 /* This works on any thread */
1067 SERVER_START_REQ( get_thread_info )
1069 req->handle = handle;
1071 status = wine_server_call( req );
1072 if (status == STATUS_SUCCESS)
1074 NTDLL_from_server_abstime( &kusrt.CreateTime, &reply->creation_time );
1075 NTDLL_from_server_abstime( &kusrt.ExitTime, &reply->exit_time );
1079 if (status == STATUS_SUCCESS)
1081 /* We call times(2) for kernel time or user time */
1082 /* We can only (portably) do this for the current thread */
1083 if (handle == GetCurrentThread())
1085 struct tms time_buf;
1086 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1089 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1090 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1094 kusrt.KernelTime.QuadPart = 0;
1095 kusrt.UserTime.QuadPart = 0;
1096 FIXME("Cannot get kerneltime or usertime of other threads\n");
1098 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1099 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1103 case ThreadDescriptorTableEntry:
1106 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1107 if (length < sizeof(*tdi))
1108 status = STATUS_INFO_LENGTH_MISMATCH;
1109 else if (!(tdi->Selector & 4)) /* GDT selector */
1111 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1112 status = STATUS_SUCCESS;
1113 if (!sel) /* null selector */
1114 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1117 tdi->Entry.BaseLow = 0;
1118 tdi->Entry.HighWord.Bits.BaseMid = 0;
1119 tdi->Entry.HighWord.Bits.BaseHi = 0;
1120 tdi->Entry.LimitLow = 0xffff;
1121 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1122 tdi->Entry.HighWord.Bits.Dpl = 3;
1123 tdi->Entry.HighWord.Bits.Sys = 0;
1124 tdi->Entry.HighWord.Bits.Pres = 1;
1125 tdi->Entry.HighWord.Bits.Granularity = 1;
1126 tdi->Entry.HighWord.Bits.Default_Big = 1;
1127 tdi->Entry.HighWord.Bits.Type = 0x12;
1128 /* it has to be one of the system GDT selectors */
1129 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1131 if (sel == (wine_get_cs() & ~3))
1132 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1133 else status = STATUS_ACCESS_DENIED;
1139 SERVER_START_REQ( get_selector_entry )
1141 req->handle = handle;
1142 req->entry = tdi->Selector >> 3;
1143 status = wine_server_call( req );
1146 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1147 status = STATUS_ACCESS_VIOLATION;
1150 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1151 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1152 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1158 if (status == STATUS_SUCCESS && ret_len)
1159 /* yes, that's a bit strange, but it's the way it is */
1160 *ret_len = sizeof(LDT_ENTRY);
1162 status = STATUS_NOT_IMPLEMENTED;
1166 case ThreadAmILastThread:
1168 SERVER_START_REQ(get_thread_info)
1170 req->handle = handle;
1172 status = wine_server_call( req );
1173 if (status == STATUS_SUCCESS)
1175 BOOLEAN last = reply->last;
1176 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1177 if (ret_len) *ret_len = min( length, sizeof(last) );
1183 case ThreadPriority:
1184 case ThreadBasePriority:
1185 case ThreadAffinityMask:
1186 case ThreadImpersonationToken:
1187 case ThreadEnableAlignmentFaultFixup:
1188 case ThreadEventPair_Reusable:
1189 case ThreadQuerySetWin32StartAddress:
1190 case ThreadZeroTlsCell:
1191 case ThreadPerformanceCount:
1192 case ThreadIdealProcessor:
1193 case ThreadPriorityBoost:
1194 case ThreadSetTlsArrayAddress:
1195 case ThreadIsIoPending:
1197 FIXME( "info class %d not supported yet\n", class );
1198 return STATUS_NOT_IMPLEMENTED;
1203 /******************************************************************************
1204 * NtSetInformationThread (NTDLL.@)
1205 * ZwSetInformationThread (NTDLL.@)
1207 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1208 LPCVOID data, ULONG length )
1213 case ThreadZeroTlsCell:
1214 if (handle == GetCurrentThread())
1219 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1220 index = *(const DWORD *)data;
1221 if (index < TLS_MINIMUM_AVAILABLE)
1223 RtlAcquirePebLock();
1224 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1226 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1227 teb->TlsSlots[index] = 0;
1229 RtlReleasePebLock();
1233 index -= TLS_MINIMUM_AVAILABLE;
1234 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1235 return STATUS_INVALID_PARAMETER;
1236 RtlAcquirePebLock();
1237 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1239 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1240 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1242 RtlReleasePebLock();
1244 return STATUS_SUCCESS;
1246 FIXME( "ZeroTlsCell not supported on other threads\n" );
1247 return STATUS_NOT_IMPLEMENTED;
1249 case ThreadImpersonationToken:
1251 const HANDLE *phToken = data;
1252 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1253 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1254 SERVER_START_REQ( set_thread_info )
1256 req->handle = handle;
1257 req->token = *phToken;
1258 req->mask = SET_THREAD_INFO_TOKEN;
1259 status = wine_server_call( req );
1264 case ThreadBasePriority:
1266 const DWORD *pprio = data;
1267 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1268 SERVER_START_REQ( set_thread_info )
1270 req->handle = handle;
1271 req->priority = *pprio;
1272 req->mask = SET_THREAD_INFO_PRIORITY;
1273 status = wine_server_call( req );
1278 case ThreadAffinityMask:
1280 const DWORD *paff = data;
1281 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1282 SERVER_START_REQ( set_thread_info )
1284 req->handle = handle;
1285 req->affinity = *paff;
1286 req->mask = SET_THREAD_INFO_AFFINITY;
1287 status = wine_server_call( req );
1292 case ThreadBasicInformation:
1294 case ThreadPriority:
1295 case ThreadDescriptorTableEntry:
1296 case ThreadEnableAlignmentFaultFixup:
1297 case ThreadEventPair_Reusable:
1298 case ThreadQuerySetWin32StartAddress:
1299 case ThreadPerformanceCount:
1300 case ThreadAmILastThread:
1301 case ThreadIdealProcessor:
1302 case ThreadPriorityBoost:
1303 case ThreadSetTlsArrayAddress:
1304 case ThreadIsIoPending:
1306 FIXME( "info class %d not supported yet\n", class );
1307 return STATUS_NOT_IMPLEMENTED;
1312 /**********************************************************************
1313 * NtCurrentTeb (NTDLL.@)
1315 #if defined(__i386__) && defined(__GNUC__)
1317 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
1319 #elif defined(__i386__) && defined(_MSC_VER)
1321 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1325 /**********************************************************************/
1327 TEB * WINAPI NtCurrentTeb(void)
1329 return pthread_functions.get_current_teb();
1332 #endif /* __i386__ */