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"
44 #include "wine/exception.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(thread);
47 WINE_DECLARE_DEBUG_CHANNEL(relay);
49 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
51 /* info passed to a starting thread */
54 struct wine_pthread_thread_info pthread_info;
55 PRTL_THREAD_START_ROUTINE entry_point;
59 static PEB_LDR_DATA ldr;
60 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
61 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
62 static RTL_BITMAP tls_bitmap;
63 static RTL_BITMAP tls_expansion_bitmap;
64 static LIST_ENTRY tls_links;
65 static size_t sigstack_total_size;
66 static ULONG sigstack_zero_bits;
68 struct wine_pthread_functions pthread_functions = { NULL };
71 static RTL_CRITICAL_SECTION ldt_section;
72 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
75 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
76 0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
78 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
79 static sigset_t ldt_sigset;
81 /***********************************************************************
82 * locking for LDT routines
84 static void ldt_lock(void)
88 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
89 RtlEnterCriticalSection( &ldt_section );
90 if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
93 static void ldt_unlock(void)
95 if (ldt_section.RecursionCount == 1)
97 sigset_t sigset = ldt_sigset;
98 RtlLeaveCriticalSection( &ldt_section );
99 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
101 else RtlLeaveCriticalSection( &ldt_section );
105 /***********************************************************************
108 static inline NTSTATUS init_teb( TEB *teb )
110 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
111 struct ntdll_thread_regs *thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
113 teb->Tib.ExceptionList = (void *)~0UL;
114 teb->Tib.StackBase = (void *)~0UL;
115 teb->Tib.Self = &teb->Tib;
116 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
117 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
119 if (!(thread_regs->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
120 thread_data->request_fd = -1;
121 thread_data->reply_fd = -1;
122 thread_data->wait_fd[0] = -1;
123 thread_data->wait_fd[1] = -1;
125 return STATUS_SUCCESS;
129 /***********************************************************************
132 * Make sure the unicode string doesn't point beyond the end pointer
134 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
136 if ((char *)str->Buffer >= end_ptr)
138 str->Length = str->MaximumLength = 0;
142 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
144 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
146 if (str->Length >= str->MaximumLength)
148 if (str->MaximumLength >= sizeof(WCHAR))
149 str->Length = str->MaximumLength - sizeof(WCHAR);
151 str->Length = str->MaximumLength = 0;
156 /***********************************************************************
157 * init_user_process_params
159 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
161 static NTSTATUS init_user_process_params( SIZE_T info_size, HANDLE *exe_file )
166 RTL_USER_PROCESS_PARAMETERS *params = NULL;
168 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &info_size,
169 MEM_COMMIT, PAGE_READWRITE );
170 if (status != STATUS_SUCCESS) return status;
172 params->AllocationSize = info_size;
173 NtCurrentTeb()->Peb->ProcessParameters = params;
175 SERVER_START_REQ( get_startup_info )
177 wine_server_set_reply( req, params, info_size );
178 if (!(status = wine_server_call( req )))
180 info_size = wine_server_reply_size( reply );
181 *exe_file = reply->exe_file;
182 params->hStdInput = reply->hstdin;
183 params->hStdOutput = reply->hstdout;
184 params->hStdError = reply->hstderr;
188 if (status != STATUS_SUCCESS) return status;
190 if (params->Size > info_size) params->Size = info_size;
192 /* make sure the strings are valid */
193 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
194 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
195 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
196 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
197 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
198 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
199 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
200 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
202 /* environment needs to be a separate memory block */
203 env_size = info_size - params->Size;
204 if (!env_size) env_size = 1;
206 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
207 MEM_COMMIT, PAGE_READWRITE );
208 if (status != STATUS_SUCCESS) return status;
209 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
210 params->Environment = ptr;
212 RtlNormalizeProcessParams( params );
217 /***********************************************************************
220 * Setup the initial thread.
222 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
224 HANDLE thread_init(void)
229 SIZE_T size, info_size;
232 struct ntdll_thread_data *thread_data;
233 struct ntdll_thread_regs *thread_regs;
234 struct wine_pthread_thread_info thread_info;
235 static struct debug_info debug_info; /* debug info for initial thread */
239 /* reserve space for shared user data */
241 addr = (void *)0x7ffe0000;
243 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
244 user_shared_data = addr;
246 /* allocate and initialize the PEB */
250 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
251 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
254 peb->NumberOfProcessors = 1;
255 peb->ProcessParameters = ¶ms;
256 peb->TlsBitmap = &tls_bitmap;
257 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
259 params.CurrentDirectory.DosPath.Buffer = current_dir;
260 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
261 params.wShowWindow = 1; /* SW_SHOWNORMAL */
262 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
263 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
264 sizeof(peb->TlsExpansionBitmapBits) * 8 );
265 InitializeListHead( &ldr.InLoadOrderModuleList );
266 InitializeListHead( &ldr.InMemoryOrderModuleList );
267 InitializeListHead( &ldr.InInitializationOrderModuleList );
268 InitializeListHead( &tls_links );
270 /* allocate and initialize the initial TEB */
272 sigstack_total_size = get_signal_stack_total_size();
273 while (1 << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
274 assert( 1 << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
275 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
276 thread_info.teb_size = sigstack_total_size;
279 size = sigstack_total_size;
280 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
281 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
284 thread_info.teb_size = size;
286 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
287 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
288 thread_data->debug_info = &debug_info;
289 InsertHeadList( &tls_links, &teb->TlsLinks );
291 thread_info.stack_base = NULL;
292 thread_info.stack_size = 0;
293 thread_info.teb_base = teb;
294 thread_info.teb_sel = thread_regs->fs;
295 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
296 pthread_functions.init_current_teb( &thread_info );
297 pthread_functions.init_thread( &thread_info );
298 virtual_init_threading();
300 debug_info.str_pos = debug_info.strings;
301 debug_info.out_pos = debug_info.output;
304 /* setup the server connection */
305 server_init_process();
306 info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
308 /* create the process heap */
309 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
311 MESSAGE( "wine: failed to create the process heap\n" );
315 /* allocate user parameters */
318 init_user_process_params( info_size, &exe_file );
322 /* This is wine specific: we have no parent (we're started from unix)
323 * so, create a simple console with bare handles to unix stdio
325 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
326 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
327 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
330 /* initialize LDT locking */
331 wine_ldt_init_locking( ldt_lock, ldt_unlock );
333 /* initialize time values in user_shared_data */
334 NtQuerySystemTime( &now );
335 user_shared_data->SystemTime.LowPart = now.u.LowPart;
336 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
337 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
338 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
339 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
340 user_shared_data->TickCountMultiplier = 1 << 24;
345 typedef LONG (WINAPI *PUNHANDLED_EXCEPTION_FILTER)(PEXCEPTION_POINTERS);
346 static PUNHANDLED_EXCEPTION_FILTER get_unhandled_exception_filter(void)
348 static PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter;
349 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
350 UNICODE_STRING module_name;
351 ANSI_STRING func_name;
352 HMODULE kernel32_handle;
354 if (unhandled_exception_filter) return unhandled_exception_filter;
356 RtlInitUnicodeString(&module_name, kernel32W);
357 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
359 if (LdrGetDllHandle( 0, 0, &module_name, &kernel32_handle ) == STATUS_SUCCESS)
360 LdrGetProcedureAddress( kernel32_handle, &func_name, 0,
361 (void **)&unhandled_exception_filter );
363 return unhandled_exception_filter;
367 /* wrapper for apps that don't declare the thread function correctly */
368 extern DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg );
369 __ASM_GLOBAL_FUNC(call_thread_entry_point,
374 "movl 8(%ebp),%eax\n\t"
379 static inline DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg )
381 LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)entry;
386 /***********************************************************************
389 * Hack to make things compatible with the thread procedures used by kernel32.CreateThread.
391 static void DECLSPEC_NORETURN call_thread_func( PRTL_THREAD_START_ROUTINE rtl_func, void *arg )
396 MODULE_DllThreadAttach( NULL );
399 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), rtl_func, arg );
401 exit_code = call_thread_entry_point( rtl_func, arg );
403 /* send the exit code to the server */
404 SERVER_START_REQ( terminate_thread )
406 req->handle = GetCurrentThread();
407 req->exit_code = exit_code;
408 wine_server_call( req );
415 LdrShutdownProcess();
421 server_exit_thread( exit_code );
426 /***********************************************************************
429 * Startup routine for a newly created thread.
431 static void start_thread( struct wine_pthread_thread_info *info )
433 TEB *teb = info->teb_base;
434 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
435 struct startup_info *startup_info = (struct startup_info *)info;
436 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
437 void *arg = startup_info->entry_arg;
438 struct debug_info debug_info;
439 SIZE_T size, page_size = getpagesize();
441 debug_info.str_pos = debug_info.strings;
442 debug_info.out_pos = debug_info.output;
443 thread_data->debug_info = &debug_info;
445 pthread_functions.init_current_teb( info );
447 server_init_thread( info->pid, info->tid, func );
448 pthread_functions.init_thread( info );
450 /* allocate a memory view for the stack */
451 size = info->stack_size;
452 teb->DeallocationStack = info->stack_base;
453 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
454 &size, MEM_SYSTEM, PAGE_READWRITE );
455 /* limit is lower than base since the stack grows down */
456 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
457 teb->Tib.StackLimit = (char *)info->stack_base + page_size;
459 /* setup the guard page */
461 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, PAGE_NOACCESS, NULL );
463 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
466 InsertHeadList( &tls_links, &teb->TlsLinks );
469 /* NOTE: Windows does not have an exception handler around the call to
470 * the thread attach. We do for ease of debugging */
471 if (get_unhandled_exception_filter())
475 call_thread_func( func, arg );
477 __EXCEPT(get_unhandled_exception_filter())
479 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
484 call_thread_func( func, arg );
488 /***********************************************************************
489 * RtlCreateUserThread (NTDLL.@)
491 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
492 BOOLEAN suspended, PVOID stack_addr,
493 SIZE_T stack_reserve, SIZE_T stack_commit,
494 PRTL_THREAD_START_ROUTINE start, void *param,
495 HANDLE *handle_ptr, CLIENT_ID *id )
498 struct ntdll_thread_data *thread_data;
499 struct ntdll_thread_regs *thread_regs = NULL;
500 struct startup_info *info = NULL;
507 SIZE_T size, page_size = getpagesize();
509 if (process != NtCurrentProcess())
514 call.create_thread.type = APC_CREATE_THREAD;
515 call.create_thread.func = start;
516 call.create_thread.arg = param;
517 call.create_thread.reserve = stack_reserve;
518 call.create_thread.commit = stack_commit;
519 call.create_thread.suspend = suspended;
520 status = NTDLL_queue_process_apc( process, &call, &result );
521 if (status != STATUS_SUCCESS) return status;
523 if (result.create_thread.status == STATUS_SUCCESS)
525 if (id) id->UniqueThread = (HANDLE)result.create_thread.tid;
526 if (handle_ptr) *handle_ptr = result.create_thread.handle;
527 else NtClose( result.create_thread.handle );
529 return result.create_thread.status;
532 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
533 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
534 wine_server_send_fd( request_pipe[0] );
536 SERVER_START_REQ( new_thread )
538 req->access = THREAD_ALL_ACCESS;
539 req->attributes = 0; /* FIXME */
540 req->suspend = suspended;
541 req->request_fd = request_pipe[0];
542 if (!(status = wine_server_call( req )))
544 handle = reply->handle;
547 close( request_pipe[0] );
553 close( request_pipe[1] );
557 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &sigset );
560 size = sigstack_total_size;
561 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
562 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
565 teb->Peb = NtCurrentTeb()->Peb;
566 info = (struct startup_info *)(teb + 1);
567 info->pthread_info.teb_size = size;
568 if ((status = init_teb( teb ))) goto error;
570 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
571 teb->ClientId.UniqueThread = (HANDLE)tid;
573 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
574 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
575 thread_data->request_fd = request_pipe[1];
577 info->pthread_info.teb_base = teb;
578 info->pthread_info.teb_sel = thread_regs->fs;
580 /* inherit debug registers from parent thread */
581 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
582 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
583 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
584 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
585 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
586 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
588 if (!stack_reserve || !stack_commit)
590 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
591 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
592 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
594 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
595 stack_reserve += page_size; /* for the guard page */
596 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
597 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
599 info->pthread_info.stack_base = NULL;
600 info->pthread_info.stack_size = stack_reserve;
601 info->pthread_info.entry = start_thread;
602 info->entry_point = start;
603 info->entry_arg = param;
605 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
607 status = STATUS_NO_MEMORY;
610 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
612 if (id) id->UniqueThread = (HANDLE)tid;
613 if (handle_ptr) *handle_ptr = handle;
614 else NtClose( handle );
616 return STATUS_SUCCESS;
619 if (thread_regs) wine_ldt_free_fs( thread_regs->fs );
623 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
625 if (handle) NtClose( handle );
626 pthread_functions.sigprocmask( SIG_SETMASK, &sigset, NULL );
627 close( request_pipe[1] );
632 /***********************************************************************
633 * RtlExitUserThread (NTDLL.@)
635 void WINAPI RtlExitUserThread( ULONG status )
638 server_exit_thread( status );
642 /***********************************************************************
643 * NtOpenThread (NTDLL.@)
644 * ZwOpenThread (NTDLL.@)
646 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
647 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
651 SERVER_START_REQ( open_thread )
653 req->tid = (thread_id_t)id->UniqueThread;
654 req->access = access;
655 req->attributes = attr ? attr->Attributes : 0;
656 ret = wine_server_call( req );
657 *handle = reply->handle;
664 /******************************************************************************
665 * NtSuspendThread (NTDLL.@)
666 * ZwSuspendThread (NTDLL.@)
668 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
672 SERVER_START_REQ( suspend_thread )
674 req->handle = handle;
675 if (!(ret = wine_server_call( req ))) *count = reply->count;
682 /******************************************************************************
683 * NtResumeThread (NTDLL.@)
684 * ZwResumeThread (NTDLL.@)
686 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
690 SERVER_START_REQ( resume_thread )
692 req->handle = handle;
693 if (!(ret = wine_server_call( req ))) *count = reply->count;
700 /******************************************************************************
701 * NtAlertResumeThread (NTDLL.@)
702 * ZwAlertResumeThread (NTDLL.@)
704 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
706 FIXME( "stub: should alert thread %p\n", handle );
707 return NtResumeThread( handle, count );
711 /******************************************************************************
712 * NtAlertThread (NTDLL.@)
713 * ZwAlertThread (NTDLL.@)
715 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
717 FIXME( "stub: %p\n", handle );
718 return STATUS_NOT_IMPLEMENTED;
722 /******************************************************************************
723 * NtTerminateThread (NTDLL.@)
724 * ZwTerminateThread (NTDLL.@)
726 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
731 SERVER_START_REQ( terminate_thread )
733 req->handle = handle;
734 req->exit_code = exit_code;
735 ret = wine_server_call( req );
736 self = !ret && reply->self;
743 if (last) exit( exit_code );
744 else server_abort_thread( exit_code );
750 /******************************************************************************
751 * NtQueueApcThread (NTDLL.@)
753 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
754 ULONG_PTR arg2, ULONG_PTR arg3 )
757 SERVER_START_REQ( queue_apc )
759 req->thread = handle;
762 req->call.type = APC_USER;
763 req->call.user.func = func;
764 req->call.user.args[0] = arg1;
765 req->call.user.args[1] = arg2;
766 req->call.user.args[2] = arg3;
768 else req->call.type = APC_NONE; /* wake up only */
769 ret = wine_server_call( req );
776 /***********************************************************************
777 * NtSetContextThread (NTDLL.@)
778 * ZwSetContextThread (NTDLL.@)
780 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
787 /* on i386 debug registers always require a server call */
788 self = (handle == GetCurrentThread());
789 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
791 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
792 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
793 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
794 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
800 SERVER_START_REQ( set_thread_context )
802 req->handle = handle;
803 req->flags = context->ContextFlags;
805 wine_server_add_data( req, context, sizeof(*context) );
806 ret = wine_server_call( req );
811 if (ret == STATUS_PENDING)
813 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
815 for (i = 0; i < 100; i++)
817 SERVER_START_REQ( set_thread_context )
819 req->handle = handle;
820 req->flags = context->ContextFlags;
822 wine_server_add_data( req, context, sizeof(*context) );
823 ret = wine_server_call( req );
826 if (ret != STATUS_PENDING) break;
829 NtResumeThread( handle, &dummy );
831 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
837 if (self) set_cpu_context( context );
838 return STATUS_SUCCESS;
842 /* copy a context structure according to the flags */
843 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
846 flags &= ~CONTEXT_i386; /* get rid of CPU id */
847 if (flags & CONTEXT_INTEGER)
856 if (flags & CONTEXT_CONTROL)
861 to->SegCs = from->SegCs;
862 to->SegSs = from->SegSs;
863 to->EFlags = from->EFlags;
865 if (flags & CONTEXT_SEGMENTS)
867 to->SegDs = from->SegDs;
868 to->SegEs = from->SegEs;
869 to->SegFs = from->SegFs;
870 to->SegGs = from->SegGs;
872 if (flags & CONTEXT_DEBUG_REGISTERS)
881 if (flags & CONTEXT_FLOATING_POINT)
883 to->FloatSave = from->FloatSave;
885 #elif defined(__x86_64__)
886 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
887 if (flags & CONTEXT_CONTROL)
892 to->SegCs = from->SegCs;
893 to->SegSs = from->SegSs;
894 to->EFlags = from->EFlags;
895 to->MxCsr = from->MxCsr;
897 if (flags & CONTEXT_INTEGER)
914 if (flags & CONTEXT_SEGMENTS)
916 to->SegDs = from->SegDs;
917 to->SegEs = from->SegEs;
918 to->SegFs = from->SegFs;
919 to->SegGs = from->SegGs;
921 if (flags & CONTEXT_FLOATING_POINT)
923 to->u.FltSave = from->u.FltSave;
925 if (flags & CONTEXT_DEBUG_REGISTERS)
934 #elif defined(__sparc__)
935 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
936 if (flags & CONTEXT_CONTROL)
945 if (flags & CONTEXT_INTEGER)
980 if (flags & CONTEXT_FLOATING_POINT)
984 #elif defined(__powerpc__)
986 if (flags & CONTEXT_CONTROL)
992 if (flags & CONTEXT_INTEGER)
994 to->Gpr0 = from->Gpr0;
995 to->Gpr1 = from->Gpr1;
996 to->Gpr2 = from->Gpr2;
997 to->Gpr3 = from->Gpr3;
998 to->Gpr4 = from->Gpr4;
999 to->Gpr5 = from->Gpr5;
1000 to->Gpr6 = from->Gpr6;
1001 to->Gpr7 = from->Gpr7;
1002 to->Gpr8 = from->Gpr8;
1003 to->Gpr9 = from->Gpr9;
1004 to->Gpr10 = from->Gpr10;
1005 to->Gpr11 = from->Gpr11;
1006 to->Gpr12 = from->Gpr12;
1007 to->Gpr13 = from->Gpr13;
1008 to->Gpr14 = from->Gpr14;
1009 to->Gpr15 = from->Gpr15;
1010 to->Gpr16 = from->Gpr16;
1011 to->Gpr17 = from->Gpr17;
1012 to->Gpr18 = from->Gpr18;
1013 to->Gpr19 = from->Gpr19;
1014 to->Gpr20 = from->Gpr20;
1015 to->Gpr21 = from->Gpr21;
1016 to->Gpr22 = from->Gpr22;
1017 to->Gpr23 = from->Gpr23;
1018 to->Gpr24 = from->Gpr24;
1019 to->Gpr25 = from->Gpr25;
1020 to->Gpr26 = from->Gpr26;
1021 to->Gpr27 = from->Gpr27;
1022 to->Gpr28 = from->Gpr28;
1023 to->Gpr29 = from->Gpr29;
1024 to->Gpr30 = from->Gpr30;
1025 to->Gpr31 = from->Gpr31;
1026 to->Xer = from->Xer;
1029 if (flags & CONTEXT_FLOATING_POINT)
1031 to->Fpr0 = from->Fpr0;
1032 to->Fpr1 = from->Fpr1;
1033 to->Fpr2 = from->Fpr2;
1034 to->Fpr3 = from->Fpr3;
1035 to->Fpr4 = from->Fpr4;
1036 to->Fpr5 = from->Fpr5;
1037 to->Fpr6 = from->Fpr6;
1038 to->Fpr7 = from->Fpr7;
1039 to->Fpr8 = from->Fpr8;
1040 to->Fpr9 = from->Fpr9;
1041 to->Fpr10 = from->Fpr10;
1042 to->Fpr11 = from->Fpr11;
1043 to->Fpr12 = from->Fpr12;
1044 to->Fpr13 = from->Fpr13;
1045 to->Fpr14 = from->Fpr14;
1046 to->Fpr15 = from->Fpr15;
1047 to->Fpr16 = from->Fpr16;
1048 to->Fpr17 = from->Fpr17;
1049 to->Fpr18 = from->Fpr18;
1050 to->Fpr19 = from->Fpr19;
1051 to->Fpr20 = from->Fpr20;
1052 to->Fpr21 = from->Fpr21;
1053 to->Fpr22 = from->Fpr22;
1054 to->Fpr23 = from->Fpr23;
1055 to->Fpr24 = from->Fpr24;
1056 to->Fpr25 = from->Fpr25;
1057 to->Fpr26 = from->Fpr26;
1058 to->Fpr27 = from->Fpr27;
1059 to->Fpr28 = from->Fpr28;
1060 to->Fpr29 = from->Fpr29;
1061 to->Fpr30 = from->Fpr30;
1062 to->Fpr31 = from->Fpr31;
1063 to->Fpscr = from->Fpscr;
1066 #error You must implement context copying for your CPU
1071 /***********************************************************************
1072 * NtGetContextThread (NTDLL.@)
1073 * ZwGetContextThread (NTDLL.@)
1075 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
1080 DWORD needed_flags = context->ContextFlags;
1081 BOOL self = (handle == GetCurrentThread());
1084 /* on i386 debug registers always require a server call */
1085 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
1090 SERVER_START_REQ( get_thread_context )
1092 req->handle = handle;
1093 req->flags = context->ContextFlags;
1095 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1096 ret = wine_server_call( req );
1101 if (ret == STATUS_PENDING)
1103 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
1105 for (i = 0; i < 100; i++)
1107 SERVER_START_REQ( get_thread_context )
1109 req->handle = handle;
1110 req->flags = context->ContextFlags;
1112 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1113 ret = wine_server_call( req );
1116 if (ret != STATUS_PENDING) break;
1119 NtResumeThread( handle, &dummy );
1121 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1123 if (ret) return ret;
1124 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1125 needed_flags &= ~ctx.ContextFlags;
1132 get_cpu_context( &ctx );
1133 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1136 /* update the cached version of the debug registers */
1137 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1139 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1140 regs->dr0 = context->Dr0;
1141 regs->dr1 = context->Dr1;
1142 regs->dr2 = context->Dr2;
1143 regs->dr3 = context->Dr3;
1144 regs->dr6 = context->Dr6;
1145 regs->dr7 = context->Dr7;
1149 return STATUS_SUCCESS;
1153 /******************************************************************************
1154 * NtQueryInformationThread (NTDLL.@)
1155 * ZwQueryInformationThread (NTDLL.@)
1157 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1158 void *data, ULONG length, ULONG *ret_len )
1164 case ThreadBasicInformation:
1166 THREAD_BASIC_INFORMATION info;
1168 SERVER_START_REQ( get_thread_info )
1170 req->handle = handle;
1172 if (!(status = wine_server_call( req )))
1174 info.ExitStatus = reply->exit_code;
1175 info.TebBaseAddress = reply->teb;
1176 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
1177 info.ClientId.UniqueThread = (HANDLE)reply->tid;
1178 info.AffinityMask = reply->affinity;
1179 info.Priority = reply->priority;
1180 info.BasePriority = reply->priority; /* FIXME */
1184 if (status == STATUS_SUCCESS)
1186 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1187 if (ret_len) *ret_len = min( length, sizeof(info) );
1193 KERNEL_USER_TIMES kusrt;
1194 /* We need to do a server call to get the creation time or exit time */
1195 /* This works on any thread */
1196 SERVER_START_REQ( get_thread_info )
1198 req->handle = handle;
1200 status = wine_server_call( req );
1201 if (status == STATUS_SUCCESS)
1203 kusrt.CreateTime.QuadPart = reply->creation_time;
1204 kusrt.ExitTime.QuadPart = reply->exit_time;
1208 if (status == STATUS_SUCCESS)
1210 /* We call times(2) for kernel time or user time */
1211 /* We can only (portably) do this for the current thread */
1212 if (handle == GetCurrentThread())
1214 struct tms time_buf;
1215 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1218 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1219 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1223 kusrt.KernelTime.QuadPart = 0;
1224 kusrt.UserTime.QuadPart = 0;
1225 FIXME("Cannot get kerneltime or usertime of other threads\n");
1227 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1228 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1232 case ThreadDescriptorTableEntry:
1235 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1236 if (length < sizeof(*tdi))
1237 status = STATUS_INFO_LENGTH_MISMATCH;
1238 else if (!(tdi->Selector & 4)) /* GDT selector */
1240 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1241 status = STATUS_SUCCESS;
1242 if (!sel) /* null selector */
1243 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1246 tdi->Entry.BaseLow = 0;
1247 tdi->Entry.HighWord.Bits.BaseMid = 0;
1248 tdi->Entry.HighWord.Bits.BaseHi = 0;
1249 tdi->Entry.LimitLow = 0xffff;
1250 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1251 tdi->Entry.HighWord.Bits.Dpl = 3;
1252 tdi->Entry.HighWord.Bits.Sys = 0;
1253 tdi->Entry.HighWord.Bits.Pres = 1;
1254 tdi->Entry.HighWord.Bits.Granularity = 1;
1255 tdi->Entry.HighWord.Bits.Default_Big = 1;
1256 tdi->Entry.HighWord.Bits.Type = 0x12;
1257 /* it has to be one of the system GDT selectors */
1258 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1260 if (sel == (wine_get_cs() & ~3))
1261 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1262 else status = STATUS_ACCESS_DENIED;
1268 SERVER_START_REQ( get_selector_entry )
1270 req->handle = handle;
1271 req->entry = tdi->Selector >> 3;
1272 status = wine_server_call( req );
1275 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1276 status = STATUS_ACCESS_VIOLATION;
1279 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1280 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1281 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1287 if (status == STATUS_SUCCESS && ret_len)
1288 /* yes, that's a bit strange, but it's the way it is */
1289 *ret_len = sizeof(LDT_ENTRY);
1291 status = STATUS_NOT_IMPLEMENTED;
1295 case ThreadAmILastThread:
1297 SERVER_START_REQ(get_thread_info)
1299 req->handle = handle;
1301 status = wine_server_call( req );
1302 if (status == STATUS_SUCCESS)
1304 BOOLEAN last = reply->last;
1305 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1306 if (ret_len) *ret_len = min( length, sizeof(last) );
1312 case ThreadPriority:
1313 case ThreadBasePriority:
1314 case ThreadAffinityMask:
1315 case ThreadImpersonationToken:
1316 case ThreadEnableAlignmentFaultFixup:
1317 case ThreadEventPair_Reusable:
1318 case ThreadQuerySetWin32StartAddress:
1319 case ThreadZeroTlsCell:
1320 case ThreadPerformanceCount:
1321 case ThreadIdealProcessor:
1322 case ThreadPriorityBoost:
1323 case ThreadSetTlsArrayAddress:
1324 case ThreadIsIoPending:
1326 FIXME( "info class %d not supported yet\n", class );
1327 return STATUS_NOT_IMPLEMENTED;
1332 /******************************************************************************
1333 * NtSetInformationThread (NTDLL.@)
1334 * ZwSetInformationThread (NTDLL.@)
1336 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1337 LPCVOID data, ULONG length )
1342 case ThreadZeroTlsCell:
1343 if (handle == GetCurrentThread())
1348 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1349 index = *(const DWORD *)data;
1350 if (index < TLS_MINIMUM_AVAILABLE)
1352 RtlAcquirePebLock();
1353 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1355 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1356 teb->TlsSlots[index] = 0;
1358 RtlReleasePebLock();
1362 index -= TLS_MINIMUM_AVAILABLE;
1363 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1364 return STATUS_INVALID_PARAMETER;
1365 RtlAcquirePebLock();
1366 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1368 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1369 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1371 RtlReleasePebLock();
1373 return STATUS_SUCCESS;
1375 FIXME( "ZeroTlsCell not supported on other threads\n" );
1376 return STATUS_NOT_IMPLEMENTED;
1378 case ThreadImpersonationToken:
1380 const HANDLE *phToken = data;
1381 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1382 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1383 SERVER_START_REQ( set_thread_info )
1385 req->handle = handle;
1386 req->token = *phToken;
1387 req->mask = SET_THREAD_INFO_TOKEN;
1388 status = wine_server_call( req );
1393 case ThreadBasePriority:
1395 const DWORD *pprio = data;
1396 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1397 SERVER_START_REQ( set_thread_info )
1399 req->handle = handle;
1400 req->priority = *pprio;
1401 req->mask = SET_THREAD_INFO_PRIORITY;
1402 status = wine_server_call( req );
1407 case ThreadAffinityMask:
1409 const DWORD *paff = data;
1410 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1411 SERVER_START_REQ( set_thread_info )
1413 req->handle = handle;
1414 req->affinity = *paff;
1415 req->mask = SET_THREAD_INFO_AFFINITY;
1416 status = wine_server_call( req );
1421 case ThreadBasicInformation:
1423 case ThreadPriority:
1424 case ThreadDescriptorTableEntry:
1425 case ThreadEnableAlignmentFaultFixup:
1426 case ThreadEventPair_Reusable:
1427 case ThreadQuerySetWin32StartAddress:
1428 case ThreadPerformanceCount:
1429 case ThreadAmILastThread:
1430 case ThreadIdealProcessor:
1431 case ThreadPriorityBoost:
1432 case ThreadSetTlsArrayAddress:
1433 case ThreadIsIoPending:
1435 FIXME( "info class %d not supported yet\n", class );
1436 return STATUS_NOT_IMPLEMENTED;
1441 /**********************************************************************
1442 * NtCurrentTeb (NTDLL.@)
1444 #if defined(__i386__) && defined(__GNUC__)
1446 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" )
1448 #elif defined(__i386__) && defined(_MSC_VER)
1450 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1454 /**********************************************************************/
1456 TEB * WINAPI NtCurrentTeb(void)
1458 return pthread_functions.get_current_teb();
1461 #endif /* __i386__ */