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"
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_MMAN_H
30 #ifdef HAVE_SYS_TIMES_H
31 #include <sys/times.h>
34 #define NONAMELESSUNION
36 #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 PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;
53 /* info passed to a starting thread */
56 struct wine_pthread_thread_info pthread_info;
57 PRTL_THREAD_START_ROUTINE entry_point;
61 static PEB_LDR_DATA ldr;
62 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
63 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
64 static RTL_BITMAP tls_bitmap;
65 static RTL_BITMAP tls_expansion_bitmap;
66 static RTL_BITMAP fls_bitmap;
67 static LIST_ENTRY tls_links;
68 static size_t sigstack_total_size;
69 static ULONG sigstack_zero_bits;
70 static int nb_threads = 1;
72 static struct wine_pthread_functions pthread_functions;
75 static RTL_CRITICAL_SECTION ldt_section;
76 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
79 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
80 0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
82 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
83 static sigset_t ldt_sigset;
85 /***********************************************************************
86 * locking for LDT routines
88 static void ldt_lock(void)
92 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
93 RtlEnterCriticalSection( &ldt_section );
94 if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
97 static void ldt_unlock(void)
99 if (ldt_section.RecursionCount == 1)
101 sigset_t sigset = ldt_sigset;
102 RtlLeaveCriticalSection( &ldt_section );
103 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
105 else RtlLeaveCriticalSection( &ldt_section );
109 /***********************************************************************
112 static inline NTSTATUS init_teb( TEB *teb )
114 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
116 teb->Tib.ExceptionList = (void *)~0UL;
117 teb->Tib.StackBase = (void *)~0UL;
118 teb->Tib.Self = &teb->Tib;
119 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
120 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
122 if (!(thread_data->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
123 thread_data->request_fd = -1;
124 thread_data->reply_fd = -1;
125 thread_data->wait_fd[0] = -1;
126 thread_data->wait_fd[1] = -1;
128 return STATUS_SUCCESS;
132 /***********************************************************************
135 * Make sure the unicode string doesn't point beyond the end pointer
137 static inline void fix_unicode_string( UNICODE_STRING *str, const char *end_ptr )
139 if ((char *)str->Buffer >= end_ptr)
141 str->Length = str->MaximumLength = 0;
145 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
147 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
149 if (str->Length >= str->MaximumLength)
151 if (str->MaximumLength >= sizeof(WCHAR))
152 str->Length = str->MaximumLength - sizeof(WCHAR);
154 str->Length = str->MaximumLength = 0;
159 /***********************************************************************
160 * init_user_process_params
162 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
164 static NTSTATUS init_user_process_params( SIZE_T info_size, HANDLE *exe_file )
169 RTL_USER_PROCESS_PARAMETERS *params = NULL;
171 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &info_size,
172 MEM_COMMIT, PAGE_READWRITE );
173 if (status != STATUS_SUCCESS) return status;
175 params->AllocationSize = info_size;
176 NtCurrentTeb()->Peb->ProcessParameters = params;
178 SERVER_START_REQ( get_startup_info )
180 wine_server_set_reply( req, params, info_size );
181 if (!(status = wine_server_call( req )))
183 info_size = wine_server_reply_size( reply );
184 *exe_file = wine_server_ptr_handle( reply->exe_file );
185 params->hStdInput = wine_server_ptr_handle( reply->hstdin );
186 params->hStdOutput = wine_server_ptr_handle( reply->hstdout );
187 params->hStdError = wine_server_ptr_handle( reply->hstderr );
191 if (status != STATUS_SUCCESS) return status;
193 if (params->Size > info_size) params->Size = info_size;
195 /* make sure the strings are valid */
196 fix_unicode_string( ¶ms->CurrentDirectory.DosPath, (char *)info_size );
197 fix_unicode_string( ¶ms->DllPath, (char *)info_size );
198 fix_unicode_string( ¶ms->ImagePathName, (char *)info_size );
199 fix_unicode_string( ¶ms->CommandLine, (char *)info_size );
200 fix_unicode_string( ¶ms->WindowTitle, (char *)info_size );
201 fix_unicode_string( ¶ms->Desktop, (char *)info_size );
202 fix_unicode_string( ¶ms->ShellInfo, (char *)info_size );
203 fix_unicode_string( ¶ms->RuntimeInfo, (char *)info_size );
205 /* environment needs to be a separate memory block */
206 env_size = info_size - params->Size;
207 if (!env_size) env_size = 1;
209 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
210 MEM_COMMIT, PAGE_READWRITE );
211 if (status != STATUS_SUCCESS) return status;
212 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
213 params->Environment = ptr;
215 RtlNormalizeProcessParams( params );
220 /***********************************************************************
223 * Setup the initial thread.
225 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
227 HANDLE thread_init(void)
232 SIZE_T size, info_size;
235 struct ntdll_thread_data *thread_data;
236 struct wine_pthread_thread_info thread_info;
237 static struct debug_info debug_info; /* debug info for initial thread */
241 /* reserve space for shared user data */
243 addr = (void *)0x7ffe0000;
245 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
246 user_shared_data = addr;
248 /* allocate and initialize the PEB */
252 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
253 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
256 peb->NumberOfProcessors = 1;
257 peb->ProcessParameters = ¶ms;
258 peb->TlsBitmap = &tls_bitmap;
259 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
260 peb->FlsBitmap = &fls_bitmap;
262 params.CurrentDirectory.DosPath.Buffer = current_dir;
263 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
264 params.wShowWindow = 1; /* SW_SHOWNORMAL */
265 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
266 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
267 sizeof(peb->TlsExpansionBitmapBits) * 8 );
268 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
269 InitializeListHead( &peb->FlsListHead );
270 InitializeListHead( &ldr.InLoadOrderModuleList );
271 InitializeListHead( &ldr.InMemoryOrderModuleList );
272 InitializeListHead( &ldr.InInitializationOrderModuleList );
273 InitializeListHead( &tls_links );
275 /* allocate and initialize the initial TEB */
277 sigstack_total_size = get_signal_stack_total_size();
278 while (1U << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
279 assert( 1U << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
280 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
281 thread_info.teb_size = sigstack_total_size;
284 size = sigstack_total_size;
285 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
286 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
289 thread_info.teb_size = size;
291 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
292 thread_data->debug_info = &debug_info;
293 InsertHeadList( &tls_links, &teb->TlsLinks );
295 thread_info.stack_base = NULL;
296 thread_info.stack_size = 0;
297 thread_info.teb_base = teb;
298 thread_info.teb_sel = thread_data->fs;
299 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
300 signal_init_thread( teb );
301 pthread_functions.init_thread( &thread_info );
302 virtual_init_threading();
304 debug_info.str_pos = debug_info.strings;
305 debug_info.out_pos = debug_info.output;
308 /* setup the server connection */
309 server_init_process();
310 info_size = server_init_thread( NULL );
312 /* create the process heap */
313 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
315 MESSAGE( "wine: failed to create the process heap\n" );
319 /* allocate user parameters */
322 init_user_process_params( info_size, &exe_file );
326 /* This is wine specific: we have no parent (we're started from unix)
327 * so, create a simple console with bare handles to unix stdio
329 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
330 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
331 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
334 /* initialize LDT locking */
335 wine_ldt_init_locking( ldt_lock, ldt_unlock );
337 /* initialize time values in user_shared_data */
338 NtQuerySystemTime( &now );
339 user_shared_data->SystemTime.LowPart = now.u.LowPart;
340 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
341 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
342 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
343 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
344 user_shared_data->TickCountMultiplier = 1 << 24;
351 /***********************************************************************
354 void abort_thread( int status )
356 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
357 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
359 close( ntdll_get_thread_data()->wait_fd[0] );
360 close( ntdll_get_thread_data()->wait_fd[1] );
361 close( ntdll_get_thread_data()->reply_fd );
362 close( ntdll_get_thread_data()->request_fd );
363 pthread_exit( UIntToPtr(status) );
367 /***********************************************************************
370 static void DECLSPEC_NORETURN exit_thread( int status )
372 static void *prev_teb;
376 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
378 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
379 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
381 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
382 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) exit( status );
384 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
386 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
389 pthread_join( thread_data->pthread_id, NULL );
390 wine_ldt_free_fs( thread_data->fs );
392 NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
394 NtFreeVirtualMemory( GetCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
397 close( ntdll_get_thread_data()->wait_fd[0] );
398 close( ntdll_get_thread_data()->wait_fd[1] );
399 close( ntdll_get_thread_data()->reply_fd );
400 close( ntdll_get_thread_data()->request_fd );
401 pthread_exit( UIntToPtr(status) );
406 /* wrapper for apps that don't declare the thread function correctly */
407 extern DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg );
408 __ASM_GLOBAL_FUNC(call_thread_entry_point,
413 "movl 8(%ebp),%eax\n\t"
418 static inline DWORD call_thread_entry_point( PRTL_THREAD_START_ROUTINE entry, void *arg )
420 LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)entry;
425 /***********************************************************************
428 * Hack to make things compatible with the thread procedures used by kernel32.CreateThread.
430 static void DECLSPEC_NORETURN call_thread_func( PRTL_THREAD_START_ROUTINE rtl_func, void *arg )
435 MODULE_DllThreadAttach( NULL );
438 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), rtl_func, arg );
440 exit_code = call_thread_entry_point( rtl_func, arg );
442 /* send the exit code to the server */
443 SERVER_START_REQ( terminate_thread )
445 req->handle = wine_server_obj_handle( GetCurrentThread() );
446 req->exit_code = exit_code;
447 wine_server_call( req );
454 LdrShutdownProcess();
460 exit_thread( exit_code );
465 /***********************************************************************
468 * Startup routine for a newly created thread.
470 static void start_thread( struct wine_pthread_thread_info *info )
472 TEB *teb = info->teb_base;
473 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
474 struct startup_info *startup_info = (struct startup_info *)info;
475 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
476 void *arg = startup_info->entry_arg;
477 struct debug_info debug_info;
479 debug_info.str_pos = debug_info.strings;
480 debug_info.out_pos = debug_info.output;
481 thread_data->debug_info = &debug_info;
482 thread_data->pthread_id = pthread_self();
484 signal_init_thread( teb );
485 server_init_thread( func );
486 pthread_functions.init_thread( info );
487 virtual_alloc_thread_stack( info->stack_base, info->stack_size );
488 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
491 InsertHeadList( &tls_links, &teb->TlsLinks );
494 /* NOTE: Windows does not have an exception handler around the call to
495 * the thread attach. We do for ease of debugging */
496 if (unhandled_exception_filter)
500 call_thread_func( func, arg );
502 __EXCEPT(unhandled_exception_filter)
504 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
509 call_thread_func( func, arg );
513 /***********************************************************************
514 * RtlCreateUserThread (NTDLL.@)
516 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
517 BOOLEAN suspended, PVOID stack_addr,
518 SIZE_T stack_reserve, SIZE_T stack_commit,
519 PRTL_THREAD_START_ROUTINE start, void *param,
520 HANDLE *handle_ptr, CLIENT_ID *id )
523 pthread_t pthread_id;
525 struct ntdll_thread_data *thread_data = NULL;
526 struct ntdll_thread_regs *thread_regs;
527 struct startup_info *info = NULL;
534 SIZE_T size, page_size = getpagesize();
536 if (process != NtCurrentProcess())
541 memset( &call, 0, sizeof(call) );
543 call.create_thread.type = APC_CREATE_THREAD;
544 call.create_thread.func = wine_server_client_ptr( start );
545 call.create_thread.arg = wine_server_client_ptr( param );
546 call.create_thread.reserve = stack_reserve;
547 call.create_thread.commit = stack_commit;
548 call.create_thread.suspend = suspended;
549 status = NTDLL_queue_process_apc( process, &call, &result );
550 if (status != STATUS_SUCCESS) return status;
552 if (result.create_thread.status == STATUS_SUCCESS)
554 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
555 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
556 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
558 return result.create_thread.status;
561 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
562 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
563 wine_server_send_fd( request_pipe[0] );
565 SERVER_START_REQ( new_thread )
567 req->access = THREAD_ALL_ACCESS;
568 req->attributes = 0; /* FIXME */
569 req->suspend = suspended;
570 req->request_fd = request_pipe[0];
571 if (!(status = wine_server_call( req )))
573 handle = wine_server_ptr_handle( reply->handle );
576 close( request_pipe[0] );
582 close( request_pipe[1] );
586 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
589 size = sigstack_total_size;
590 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
591 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
594 teb->Peb = NtCurrentTeb()->Peb;
595 info = (struct startup_info *)(teb + 1);
596 info->pthread_info.teb_size = size;
597 if ((status = init_teb( teb ))) goto error;
599 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
600 teb->ClientId.UniqueThread = ULongToHandle(tid);
602 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
603 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
604 thread_data->request_fd = request_pipe[1];
606 info->pthread_info.teb_base = teb;
607 info->pthread_info.teb_sel = thread_data->fs;
609 /* inherit debug registers from parent thread */
610 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
611 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
612 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
613 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
614 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
615 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
617 if (!stack_reserve || !stack_commit)
619 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
620 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
621 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
623 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
624 stack_reserve += page_size; /* for the guard page */
625 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
626 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
628 info->pthread_info.stack_base = NULL;
629 info->pthread_info.stack_size = stack_reserve;
630 info->pthread_info.entry = start_thread;
631 info->entry_point = start;
632 info->entry_arg = param;
634 pthread_attr_init( &attr );
635 pthread_attr_setstacksize( &attr, stack_reserve );
636 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
637 interlocked_xchg_add( &nb_threads, 1 );
638 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
640 interlocked_xchg_add( &nb_threads, -1 );
641 pthread_attr_destroy( &attr );
642 status = STATUS_NO_MEMORY;
645 pthread_attr_destroy( &attr );
646 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
648 if (id) id->UniqueThread = ULongToHandle(tid);
649 if (handle_ptr) *handle_ptr = handle;
650 else NtClose( handle );
652 return STATUS_SUCCESS;
655 if (thread_data) wine_ldt_free_fs( thread_data->fs );
659 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
661 if (handle) NtClose( handle );
662 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
663 close( request_pipe[1] );
668 /***********************************************************************
669 * RtlExitUserThread (NTDLL.@)
671 void WINAPI RtlExitUserThread( ULONG status )
675 SERVER_START_REQ( terminate_thread )
677 /* send the exit code to the server */
678 req->handle = wine_server_obj_handle( GetCurrentThread() );
679 req->exit_code = status;
680 wine_server_call( req );
687 LdrShutdownProcess();
693 exit_thread( status );
698 /***********************************************************************
699 * NtOpenThread (NTDLL.@)
700 * ZwOpenThread (NTDLL.@)
702 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
703 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
707 SERVER_START_REQ( open_thread )
709 req->tid = HandleToULong(id->UniqueThread);
710 req->access = access;
711 req->attributes = attr ? attr->Attributes : 0;
712 ret = wine_server_call( req );
713 *handle = wine_server_ptr_handle( reply->handle );
720 /******************************************************************************
721 * NtSuspendThread (NTDLL.@)
722 * ZwSuspendThread (NTDLL.@)
724 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
728 SERVER_START_REQ( suspend_thread )
730 req->handle = wine_server_obj_handle( handle );
731 if (!(ret = wine_server_call( req ))) *count = reply->count;
738 /******************************************************************************
739 * NtResumeThread (NTDLL.@)
740 * ZwResumeThread (NTDLL.@)
742 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
746 SERVER_START_REQ( resume_thread )
748 req->handle = wine_server_obj_handle( handle );
749 if (!(ret = wine_server_call( req ))) *count = reply->count;
756 /******************************************************************************
757 * NtAlertResumeThread (NTDLL.@)
758 * ZwAlertResumeThread (NTDLL.@)
760 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
762 FIXME( "stub: should alert thread %p\n", handle );
763 return NtResumeThread( handle, count );
767 /******************************************************************************
768 * NtAlertThread (NTDLL.@)
769 * ZwAlertThread (NTDLL.@)
771 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
773 FIXME( "stub: %p\n", handle );
774 return STATUS_NOT_IMPLEMENTED;
778 /******************************************************************************
779 * NtTerminateThread (NTDLL.@)
780 * ZwTerminateThread (NTDLL.@)
782 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
787 SERVER_START_REQ( terminate_thread )
789 req->handle = wine_server_obj_handle( handle );
790 req->exit_code = exit_code;
791 ret = wine_server_call( req );
792 self = !ret && reply->self;
799 if (last) _exit( exit_code );
800 else abort_thread( exit_code );
806 /******************************************************************************
807 * NtQueueApcThread (NTDLL.@)
809 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
810 ULONG_PTR arg2, ULONG_PTR arg3 )
813 SERVER_START_REQ( queue_apc )
815 req->handle = wine_server_obj_handle( handle );
818 req->call.type = APC_USER;
819 req->call.user.func = wine_server_client_ptr( func );
820 req->call.user.args[0] = arg1;
821 req->call.user.args[1] = arg2;
822 req->call.user.args[2] = arg3;
824 else req->call.type = APC_NONE; /* wake up only */
825 ret = wine_server_call( req );
832 /***********************************************************************
833 * NtSetContextThread (NTDLL.@)
834 * ZwSetContextThread (NTDLL.@)
836 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
843 /* on i386 debug registers always require a server call */
844 self = (handle == GetCurrentThread());
845 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
847 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
848 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
849 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
850 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
856 SERVER_START_REQ( set_thread_context )
858 req->handle = wine_server_obj_handle( handle );
859 req->flags = context->ContextFlags;
861 wine_server_add_data( req, context, sizeof(*context) );
862 ret = wine_server_call( req );
867 if (ret == STATUS_PENDING)
869 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
871 for (i = 0; i < 100; i++)
873 SERVER_START_REQ( set_thread_context )
875 req->handle = wine_server_obj_handle( handle );
876 req->flags = context->ContextFlags;
878 wine_server_add_data( req, context, sizeof(*context) );
879 ret = wine_server_call( req );
882 if (ret == STATUS_PENDING)
884 LARGE_INTEGER timeout;
885 timeout.QuadPart = -10000;
886 NtDelayExecution( FALSE, &timeout );
890 NtResumeThread( handle, &dummy );
892 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
898 if (self) set_cpu_context( context );
899 return STATUS_SUCCESS;
903 /* copy a context structure according to the flags */
904 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
907 flags &= ~CONTEXT_i386; /* get rid of CPU id */
908 if (flags & CONTEXT_INTEGER)
917 if (flags & CONTEXT_CONTROL)
922 to->SegCs = from->SegCs;
923 to->SegSs = from->SegSs;
924 to->EFlags = from->EFlags;
926 if (flags & CONTEXT_SEGMENTS)
928 to->SegDs = from->SegDs;
929 to->SegEs = from->SegEs;
930 to->SegFs = from->SegFs;
931 to->SegGs = from->SegGs;
933 if (flags & CONTEXT_DEBUG_REGISTERS)
942 if (flags & CONTEXT_FLOATING_POINT)
944 to->FloatSave = from->FloatSave;
946 if (flags & CONTEXT_EXTENDED_REGISTERS)
948 memcpy( to->ExtendedRegisters, from->ExtendedRegisters, sizeof(to->ExtendedRegisters) );
950 #elif defined(__x86_64__)
951 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
952 if (flags & CONTEXT_CONTROL)
957 to->SegCs = from->SegCs;
958 to->SegSs = from->SegSs;
959 to->EFlags = from->EFlags;
960 to->MxCsr = from->MxCsr;
962 if (flags & CONTEXT_INTEGER)
979 if (flags & CONTEXT_SEGMENTS)
981 to->SegDs = from->SegDs;
982 to->SegEs = from->SegEs;
983 to->SegFs = from->SegFs;
984 to->SegGs = from->SegGs;
986 if (flags & CONTEXT_FLOATING_POINT)
988 to->u.FltSave = from->u.FltSave;
990 if (flags & CONTEXT_DEBUG_REGISTERS)
999 #elif defined(__sparc__)
1000 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
1001 if (flags & CONTEXT_CONTROL)
1003 to->psr = from->psr;
1005 to->npc = from->npc;
1007 to->wim = from->wim;
1008 to->tbr = from->tbr;
1010 if (flags & CONTEXT_INTEGER)
1045 if (flags & CONTEXT_FLOATING_POINT)
1049 #elif defined(__powerpc__)
1051 if (flags & CONTEXT_CONTROL)
1053 to->Msr = from->Msr;
1054 to->Ctr = from->Ctr;
1055 to->Iar = from->Iar;
1057 if (flags & CONTEXT_INTEGER)
1059 to->Gpr0 = from->Gpr0;
1060 to->Gpr1 = from->Gpr1;
1061 to->Gpr2 = from->Gpr2;
1062 to->Gpr3 = from->Gpr3;
1063 to->Gpr4 = from->Gpr4;
1064 to->Gpr5 = from->Gpr5;
1065 to->Gpr6 = from->Gpr6;
1066 to->Gpr7 = from->Gpr7;
1067 to->Gpr8 = from->Gpr8;
1068 to->Gpr9 = from->Gpr9;
1069 to->Gpr10 = from->Gpr10;
1070 to->Gpr11 = from->Gpr11;
1071 to->Gpr12 = from->Gpr12;
1072 to->Gpr13 = from->Gpr13;
1073 to->Gpr14 = from->Gpr14;
1074 to->Gpr15 = from->Gpr15;
1075 to->Gpr16 = from->Gpr16;
1076 to->Gpr17 = from->Gpr17;
1077 to->Gpr18 = from->Gpr18;
1078 to->Gpr19 = from->Gpr19;
1079 to->Gpr20 = from->Gpr20;
1080 to->Gpr21 = from->Gpr21;
1081 to->Gpr22 = from->Gpr22;
1082 to->Gpr23 = from->Gpr23;
1083 to->Gpr24 = from->Gpr24;
1084 to->Gpr25 = from->Gpr25;
1085 to->Gpr26 = from->Gpr26;
1086 to->Gpr27 = from->Gpr27;
1087 to->Gpr28 = from->Gpr28;
1088 to->Gpr29 = from->Gpr29;
1089 to->Gpr30 = from->Gpr30;
1090 to->Gpr31 = from->Gpr31;
1091 to->Xer = from->Xer;
1094 if (flags & CONTEXT_FLOATING_POINT)
1096 to->Fpr0 = from->Fpr0;
1097 to->Fpr1 = from->Fpr1;
1098 to->Fpr2 = from->Fpr2;
1099 to->Fpr3 = from->Fpr3;
1100 to->Fpr4 = from->Fpr4;
1101 to->Fpr5 = from->Fpr5;
1102 to->Fpr6 = from->Fpr6;
1103 to->Fpr7 = from->Fpr7;
1104 to->Fpr8 = from->Fpr8;
1105 to->Fpr9 = from->Fpr9;
1106 to->Fpr10 = from->Fpr10;
1107 to->Fpr11 = from->Fpr11;
1108 to->Fpr12 = from->Fpr12;
1109 to->Fpr13 = from->Fpr13;
1110 to->Fpr14 = from->Fpr14;
1111 to->Fpr15 = from->Fpr15;
1112 to->Fpr16 = from->Fpr16;
1113 to->Fpr17 = from->Fpr17;
1114 to->Fpr18 = from->Fpr18;
1115 to->Fpr19 = from->Fpr19;
1116 to->Fpr20 = from->Fpr20;
1117 to->Fpr21 = from->Fpr21;
1118 to->Fpr22 = from->Fpr22;
1119 to->Fpr23 = from->Fpr23;
1120 to->Fpr24 = from->Fpr24;
1121 to->Fpr25 = from->Fpr25;
1122 to->Fpr26 = from->Fpr26;
1123 to->Fpr27 = from->Fpr27;
1124 to->Fpr28 = from->Fpr28;
1125 to->Fpr29 = from->Fpr29;
1126 to->Fpr30 = from->Fpr30;
1127 to->Fpr31 = from->Fpr31;
1128 to->Fpscr = from->Fpscr;
1131 #error You must implement context copying for your CPU
1136 /***********************************************************************
1137 * NtGetContextThread (NTDLL.@)
1138 * ZwGetContextThread (NTDLL.@)
1140 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
1145 DWORD needed_flags = context->ContextFlags;
1146 BOOL self = (handle == GetCurrentThread());
1149 /* on i386 debug registers always require a server call */
1150 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
1155 SERVER_START_REQ( get_thread_context )
1157 req->handle = wine_server_obj_handle( handle );
1158 req->flags = context->ContextFlags;
1160 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1161 ret = wine_server_call( req );
1166 if (ret == STATUS_PENDING)
1168 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
1170 for (i = 0; i < 100; i++)
1172 SERVER_START_REQ( get_thread_context )
1174 req->handle = wine_server_obj_handle( handle );
1175 req->flags = context->ContextFlags;
1177 wine_server_set_reply( req, &ctx, sizeof(ctx) );
1178 ret = wine_server_call( req );
1181 if (ret == STATUS_PENDING)
1183 LARGE_INTEGER timeout;
1184 timeout.QuadPart = -10000;
1185 NtDelayExecution( FALSE, &timeout );
1189 NtResumeThread( handle, &dummy );
1191 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1193 if (ret) return ret;
1194 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1195 needed_flags &= ~ctx.ContextFlags;
1202 RtlCaptureContext( &ctx );
1203 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1206 /* update the cached version of the debug registers */
1207 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1209 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1210 regs->dr0 = context->Dr0;
1211 regs->dr1 = context->Dr1;
1212 regs->dr2 = context->Dr2;
1213 regs->dr3 = context->Dr3;
1214 regs->dr6 = context->Dr6;
1215 regs->dr7 = context->Dr7;
1219 return STATUS_SUCCESS;
1223 /******************************************************************************
1224 * NtQueryInformationThread (NTDLL.@)
1225 * ZwQueryInformationThread (NTDLL.@)
1227 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1228 void *data, ULONG length, ULONG *ret_len )
1234 case ThreadBasicInformation:
1236 THREAD_BASIC_INFORMATION info;
1237 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1239 SERVER_START_REQ( get_thread_info )
1241 req->handle = wine_server_obj_handle( handle );
1243 if (!(status = wine_server_call( req )))
1245 info.ExitStatus = reply->exit_code;
1246 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
1247 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
1248 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
1249 info.AffinityMask = reply->affinity & affinity_mask;
1250 info.Priority = reply->priority;
1251 info.BasePriority = reply->priority; /* FIXME */
1255 if (status == STATUS_SUCCESS)
1257 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1258 if (ret_len) *ret_len = min( length, sizeof(info) );
1262 case ThreadAffinityMask:
1264 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1265 ULONG_PTR affinity = 0;
1267 SERVER_START_REQ( get_thread_info )
1269 req->handle = wine_server_obj_handle( handle );
1271 if (!(status = wine_server_call( req )))
1272 affinity = reply->affinity & affinity_mask;
1275 if (status == STATUS_SUCCESS)
1277 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
1278 if (ret_len) *ret_len = min( length, sizeof(affinity) );
1284 KERNEL_USER_TIMES kusrt;
1285 /* We need to do a server call to get the creation time or exit time */
1286 /* This works on any thread */
1287 SERVER_START_REQ( get_thread_info )
1289 req->handle = wine_server_obj_handle( handle );
1291 status = wine_server_call( req );
1292 if (status == STATUS_SUCCESS)
1294 kusrt.CreateTime.QuadPart = reply->creation_time;
1295 kusrt.ExitTime.QuadPart = reply->exit_time;
1299 if (status == STATUS_SUCCESS)
1301 /* We call times(2) for kernel time or user time */
1302 /* We can only (portably) do this for the current thread */
1303 if (handle == GetCurrentThread())
1305 struct tms time_buf;
1306 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1309 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1310 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1314 static BOOL reported = FALSE;
1316 kusrt.KernelTime.QuadPart = 0;
1317 kusrt.UserTime.QuadPart = 0;
1319 TRACE("Cannot get kerneltime or usertime of other threads\n");
1322 FIXME("Cannot get kerneltime or usertime of other threads\n");
1326 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1327 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1331 case ThreadDescriptorTableEntry:
1334 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1335 if (length < sizeof(*tdi))
1336 status = STATUS_INFO_LENGTH_MISMATCH;
1337 else if (!(tdi->Selector & 4)) /* GDT selector */
1339 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1340 status = STATUS_SUCCESS;
1341 if (!sel) /* null selector */
1342 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1345 tdi->Entry.BaseLow = 0;
1346 tdi->Entry.HighWord.Bits.BaseMid = 0;
1347 tdi->Entry.HighWord.Bits.BaseHi = 0;
1348 tdi->Entry.LimitLow = 0xffff;
1349 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1350 tdi->Entry.HighWord.Bits.Dpl = 3;
1351 tdi->Entry.HighWord.Bits.Sys = 0;
1352 tdi->Entry.HighWord.Bits.Pres = 1;
1353 tdi->Entry.HighWord.Bits.Granularity = 1;
1354 tdi->Entry.HighWord.Bits.Default_Big = 1;
1355 tdi->Entry.HighWord.Bits.Type = 0x12;
1356 /* it has to be one of the system GDT selectors */
1357 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1359 if (sel == (wine_get_cs() & ~3))
1360 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1361 else status = STATUS_ACCESS_DENIED;
1367 SERVER_START_REQ( get_selector_entry )
1369 req->handle = wine_server_obj_handle( handle );
1370 req->entry = tdi->Selector >> 3;
1371 status = wine_server_call( req );
1374 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1375 status = STATUS_ACCESS_VIOLATION;
1378 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1379 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1380 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1386 if (status == STATUS_SUCCESS && ret_len)
1387 /* yes, that's a bit strange, but it's the way it is */
1388 *ret_len = sizeof(LDT_ENTRY);
1390 status = STATUS_NOT_IMPLEMENTED;
1394 case ThreadAmILastThread:
1396 SERVER_START_REQ(get_thread_info)
1398 req->handle = wine_server_obj_handle( handle );
1400 status = wine_server_call( req );
1401 if (status == STATUS_SUCCESS)
1403 BOOLEAN last = reply->last;
1404 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1405 if (ret_len) *ret_len = min( length, sizeof(last) );
1411 case ThreadPriority:
1412 case ThreadBasePriority:
1413 case ThreadImpersonationToken:
1414 case ThreadEnableAlignmentFaultFixup:
1415 case ThreadEventPair_Reusable:
1416 case ThreadQuerySetWin32StartAddress:
1417 case ThreadZeroTlsCell:
1418 case ThreadPerformanceCount:
1419 case ThreadIdealProcessor:
1420 case ThreadPriorityBoost:
1421 case ThreadSetTlsArrayAddress:
1422 case ThreadIsIoPending:
1424 FIXME( "info class %d not supported yet\n", class );
1425 return STATUS_NOT_IMPLEMENTED;
1430 /******************************************************************************
1431 * NtSetInformationThread (NTDLL.@)
1432 * ZwSetInformationThread (NTDLL.@)
1434 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1435 LPCVOID data, ULONG length )
1440 case ThreadZeroTlsCell:
1441 if (handle == GetCurrentThread())
1446 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1447 index = *(const DWORD *)data;
1448 if (index < TLS_MINIMUM_AVAILABLE)
1450 RtlAcquirePebLock();
1451 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1453 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1454 teb->TlsSlots[index] = 0;
1456 RtlReleasePebLock();
1460 index -= TLS_MINIMUM_AVAILABLE;
1461 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1462 return STATUS_INVALID_PARAMETER;
1463 RtlAcquirePebLock();
1464 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1466 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1467 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1469 RtlReleasePebLock();
1471 return STATUS_SUCCESS;
1473 FIXME( "ZeroTlsCell not supported on other threads\n" );
1474 return STATUS_NOT_IMPLEMENTED;
1476 case ThreadImpersonationToken:
1478 const HANDLE *phToken = data;
1479 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1480 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1481 SERVER_START_REQ( set_thread_info )
1483 req->handle = wine_server_obj_handle( handle );
1484 req->token = wine_server_obj_handle( *phToken );
1485 req->mask = SET_THREAD_INFO_TOKEN;
1486 status = wine_server_call( req );
1491 case ThreadBasePriority:
1493 const DWORD *pprio = data;
1494 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1495 SERVER_START_REQ( set_thread_info )
1497 req->handle = wine_server_obj_handle( handle );
1498 req->priority = *pprio;
1499 req->mask = SET_THREAD_INFO_PRIORITY;
1500 status = wine_server_call( req );
1505 case ThreadAffinityMask:
1507 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1508 const ULONG_PTR *paff = data;
1509 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1510 if (*paff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1511 SERVER_START_REQ( set_thread_info )
1513 req->handle = wine_server_obj_handle( handle );
1514 req->affinity = *paff;
1515 req->mask = SET_THREAD_INFO_AFFINITY;
1516 status = wine_server_call( req );
1521 case ThreadBasicInformation:
1523 case ThreadPriority:
1524 case ThreadDescriptorTableEntry:
1525 case ThreadEnableAlignmentFaultFixup:
1526 case ThreadEventPair_Reusable:
1527 case ThreadQuerySetWin32StartAddress:
1528 case ThreadPerformanceCount:
1529 case ThreadAmILastThread:
1530 case ThreadIdealProcessor:
1531 case ThreadPriorityBoost:
1532 case ThreadSetTlsArrayAddress:
1533 case ThreadIsIoPending:
1535 FIXME( "info class %d not supported yet\n", class );
1536 return STATUS_NOT_IMPLEMENTED;